Blog Post

How to build an Angular PDF viewer with PDF.js

Illustration: How to build an Angular PDF viewer with PDF.js
Information

This article was first published in September 2021 and was updated in October 2024.

Angular, developed by Google, is a powerful TypeScript framework for building dynamic web applications. PDF.js, an open source JavaScript library by Mozilla, enables rendering of PDF files in the browser. In this article, you’ll combine Angular and PDF.js to create a simple PDF viewer in an Angular app.

In the first part, you’ll use an open source library to build the PDF viewer, and in the second part, you’ll integrate the JavaScript PDF library into the Angular project.

PDF.js vs. Nutrient

Deploying PDF.js in the Angular framework is a low-cost option for viewing PDFs. Once deployed, you’ll be able to:

  • View PDF files
  • Zoom in and out
  • Add pagination
  • Search words and move through searches
  • Rotate pages
  • Resize pages
  • See fullscreen pages
  • Open a new PDF file
  • Download and print files
  • Scroll vertically
  • Scroll horizontally

However, in some situations, a commercial Angular PDF viewer might make better sense. The most common use cases we see are from developers who need to add features or file types that aren’t supported by PDF.js. Here are some of the top reasons our customers migrate from PDF.js to our Angular PDF viewer:

  • A prebuilt UI — Save time with a well-documented list of APIs when customizing the UI to meet your exact requirements.
  • Annotation tools — Draw, circle, highlight, comment, and add notes to documents with 15+ prebuilt annotation tools.
  • Multiple file types — Support client-side viewing of PDFs, MS Office documents, and image files.
  • 30+ features — Easily add features like PDF editing, digital signatures, form filling, real-time document collaboration, and more.
  • Dedicated support — Deploy faster by working 1-on-1 with our developers.

Open source Angular PDF viewer libraries

There are a couple of open source Angular PDF viewer libraries we looked into while writing this blog post. The most popular one is ng2-pdf-viewer, with 71K weekly downloads on npm. This library is still active, but it doesn’t provide a user interface (UI). You might prefer this library if you want to use it as a core viewer.

Another popular library is ngx-extended-pdf-viewer, with around 30K weekly downloads on npm. This is the library we’ll use in this article because it:

  • Uses PDF.js under the hood.
  • Has great documentation, with library owners who are very responsive.
  • Is highly customizable.

Requirements

To get started, you’ll need:

Information

When you install Node.js, npm is installed by default.

Setup

Go to your terminal and install the Angular command-line interface (CLI). This will help you get up and running quickly with Angular:

npm install -g @angular/cli
yarn global add @angular/cli

Now, you can check the version of Angular:

ng version

Building an Angular PDF viewer with ngx-extended-pdf-viewer

Now, open your favorite integrated development environment (IDE). This demo uses Visual Studio Code. Navigate to the directory where you want your new Angular project to be. We created a directory named pdf-viewer:

mkdir pdf-viewer

Change your directory into pdf-viewer with cd pdf-viewer.

Go to the project terminal and create a new Angular project:

ng new ngx-pdf-viewer

Choose No for adding Angular routing and CSS for the stylesheet.

Angular Project Configuration

Change your directory into the newly created folder:

cd ngx-pdf-viewer

Run the project on a server. This command will serve the Angular project:

npm start
yarn start

The project is running on localhost:4200.

Adding ngx-extended-pdf-viewer

Run the command below to install the ngx-extended-pdf-viewer library via npm or yarn. This will install the latest version of the library:

npm install ngx-extended-pdf-viewer
yarn add ngx-extended-pdf-viewer

Now you need to configure the angular.json file. You’ll add this configuration under the projects > yourProjectName > architect > build > options > assets section:

"assets": [
    "src/favicon.ico",
     "src/assets",
    {
      "glob": "**/*",
      "input": "node_modules/ngx-extended-pdf-viewer/assets/",
       "output": "/assets/"
     }
],

Go to the app.component.ts file and import NgxExtendedPdfViewerModule from ngx-extended-pdf-viewer and pass it to the imports array:

// src/app/app.component.ts
import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { NgxExtendedPdfViewerModule } from 'ngx-extended-pdf-viewer';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterOutlet, NgxExtendedPdfViewerModule],
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

Displaying a PDF

Add your PDF document to the src/assets directory. You can use our demo document as an example.

There’s one more step left to see the PDF file on the browser. Go to the app.component.html file and replace the contents of app.component.html with:

<ngx-extended-pdf-viewer
  [src]="'assets/example.pdf'"
  [textLayer]="true"
  [showHandToolButton]="true"
  [showPresentationModeButton]="true"
  [showDownloadButton]="true"
></ngx-extended-pdf-viewer>

There are many configuration options you can use. You can see all the options on the ngx-extended-pdf-viewer website.

Now, you can run your project with the following command:

ng serve

Navigate to localhost:4200 to see your PDF file.

Information

You can access the project on GitHub.

ngx-extended-pdf-viewer demo

Building an Angular PDF viewer with Nutrient

ngx-extended-pdf-viewer is a great open source project, but it does have some disadvantages:

  • The library changes regularly and can result in your app breaking at unexpected times. You need to ensure that you’re running the most up-to-date version to avoid these disruptions.
  • Some users report slow performance when previewing documents with more than 1,000 pages.

Nutrient offers a powerful PDF library that can be used to build your own Angular PDF viewer. On top of all the features you get with an open source library, some additional features you get with Nutrient include:

  • Improved rendering performance
  • PDF editing and annotating
  • Image and MS Office file viewing
  • Powerful document search
  • A rich bookmark UI that enables you to add, remove, and sort bookmarks
  • Dark mode support
  • Responsive design
  • PDF form viewing and designing
  • And much more

You can integrate it into your existing or new Angular projects with a couple of steps.

Note on assets directory

In recent Angular setups, especially when creating a new project, you might notice there isn’t an assets directory created by default. This is often due to changes in Angular’s project structure in newer versions. If you don’t have this directory, create it under src:

mkdir src/assets

Now, continue with the tutorial to see how to integrate Nutrient into your Angular project.

Stay in the same directory (pdf-viewer) and create a new Angular project for Nutrient integration:

ng new pspdfkit-web-example-angular

This will ask some configuration questions. Again, choose No for routing and CSS for the stylesheet. Now, change your directory to this project:

cd pspdfkit-web-example-angular

Adding Nutrient

Install pspdfkit as a dependency with npm or yarn:

npm install pspdfkit
yarn add pspdfkit

Now, add the following to your angular.json file. Angular will copy the Nutrient library assets to the assets directory before running your app:

"assets": [
   "src/favicon.ico",
	"src/assets",
   {
  	"glob": "**/*",
	"input": "./node_modules/pspdfkit/dist/pspdfkit-lib/",
	"output": "./assets/pspdfkit-lib/"
	}
]

Displaying the PDF

Add the PDF document you want to display to the src/assets directory. You can use the same file as in the ngx-extended-pdf-viewer demo as an example.

Replace the contents of app.component.html with:

<div class="app">
	<div class="toolbar">
		<img class="logo" src="/favicon.ico" height="32" />

		PSPDFKit Angular Application
	</div>

	<!-- We'll mount the PSPDFKit UI to this element. -->
	<div class="pspdfkit-container"></div>
</div>

Replace the contents of app.component.ts with the following:

import { Component } from "@angular/core";
import PSPDFKit from "pspdfkit";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["app.component.css"],
  standalone: true,
})
export class AppComponent {
  title = "PSPDFKit for Web Angular Example";

  ngAfterViewInit(): void {
    PSPDFKit.load({
		// Use the assets directory URL as a base URL. Nutrient will download its library assets from here.
      baseUrl: location.protocol + "//" + location.host + "/assets/",
      document: "/assets/example.pdf",
      container: ".pspdfkit-container",
      licenseKey: "YOUR_LICENSE_KEY_GOES_HERE", // optional license key
    }).then((instance) => {
      // For the sake of this demo, store the Nutrient Web SDK instance
      // on the global object so that you can open the dev tools and
      // play with the Nutrient API.

      (<any>window).instance = instance;
    });
  }
}

The license key is optional; however, you may see a watermark on your PDF files without a key. To get a key, contact Sales.

If you try to run your project, you may get an error stating the mounting container has no height. To fix this issue, add the following styles to the src/app/app.component.css file:

:host {
	height: 100%;
}

.app {
	position: fixed;
	width: 100%;
	height: 100%;
	top: 0;
	right: 0;
	bottom: 0;
	left: 0;
}

.toolbar {
	position: relative;
	display: flex;
	align-items: center;
	height: 64px;
	width: 100%;
	padding: 0 24px;
	box-shadow: 0 1px 0 rgba(0, 0, 0, 0.1);
	font-family: sans-serif;
	font-size: 20px;
	font-weight: 500;
	color: rgba(0, 0, 0, 0.8);
}

.logo {
	margin-right: 20px;
}

.pspdfkit-container {
	height: calc(100% - 64px);
}
Information

You can access the project on GitHub.

Start the app and open it in your default browser:

npm start
yarn start

Conclusion

In this article, you first looked at how to build a PDF viewer with the ngx-extended-pdf-viewer library. In the second part of the article, you learned how to deploy the Nutrient Angular PDF viewer.

For simple use cases where the primary objective is viewing PDF documents, PDF.js offers a great low-cost solution. For more complex use cases, a commercial PDF viewer can provide some additional benefits:

  • An out-of-the-box UI to help speed up development time. Quickly deploy a polished UI in your application and use well-documented APIs to customize the design and layout.
  • Embed prebuilt tools to easily add functionality like annotating documents, editing PDFs, adding digital signatures to a PDF form, and much more.
  • View multiple file types — from image files (JPG, PNG, TIFF) to MS Office documents.
  • Get a quick response from a dedicated support team if you encounter a challenge or issue when integrating the viewer.

At Nutrient, we offer a commercial, feature-rich, and completely customizable Angular PDF library that’s easy to integrate and comes with well-documented APIs to handle advanced use cases. Try it for free or visit our demo to see it in action.

We created similar how-to blog posts using different web frameworks and libraries:

FAQ

Here are a few frequently asked questions about building an Angular PDF viewer.

What are the key features of ngx-extended-pdf-viewer?

ngx-extended-pdf-viewer supports Angular 9-13, uses PDF.js, and is highly customizable with features like text layers, zoom controls, and more.

When should I use Nutrient instead of PDF.js?

Use Nutrient if you need advanced features like PDF editing, annotation tools, multi-format support, or improved performance.

What are the basic steps to integrate ngx-extended-pdf-viewer into an Angular project?

Install Angular CLI, create a new Angular project, add ngx-extended-pdf-viewer via npm or yarn, configure it in angular.json, and update app.component.html to display your PDF.

How do I add Nutrient to an Angular project?

Install Nutrient, configure angular.json to include its assets, and update app.component.html and app.component.ts to load and display the PDF using Nutrient.

Author
Hulya Masharipov Technical Writer

Hulya is a frontend web developer and technical writer at PSPDFKit who enjoys creating responsive, scalable, and maintainable web experiences. She’s passionate about open source, web accessibility, cybersecurity privacy, and blockchain.

Related products
Share post
Free trial Ready to get started?
Free trial