Blog Post

How to Build an Angular PDF Viewer with PDF.js

Illustration: How to Build an Angular PDF Viewer with PDF.js

Angular is a TypeScript web application framework developed by Google, and according to the Stack Overflow 2021 Developer Survey, it’s the web’s third-most popular framework. Meanwhile, PDF.js is a lightweight JavaScript library for parsing and rendering Portable Document Format files (PDFs). In this article, we’ll use the power of these two JavaScript libraries to build an Angular PDF viewer.

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

PDF.js vs. PSPDFKit

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:

  1. Prebuilt UI — A clean and polished UI that’s easily integrated into an Angular application. This includes an extensive and well-documented list of APIs that can save time when customizing the UI to meet your exact requirements.
  2. Document annotation — 15+ prebuilt annotation tools so users can draw, circle, highlight, comment, and add notes to documents.
  3. Image file support — Users can view PNG, JPG, and TIFF files on the client side. With server deployment, users can view MS Office documents.
  4. Dedicated support — When working under tight timelines, having dedicated support from one of our developers often helps resolve integration issues faster.
  5. Scalable solutions —When the time is right, easily add features like PDF editing, digital signatures, form filling, real-time document collaboration, and more.

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:

  • Supports Angular 9, 10, 11, 12, and 13.
  • 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:

💡 Tip: 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

Screenshot showing the Angular version installed.

The Angular team releases a new version of Angular every six months. We’ll use the newest version, which is Angular 13. You can get Angular v13 by running the following command:

ng update

You can also check out the update guide for more details.

If you’re starting from scratch, when you install the Angular CLI, you’ll be using Angular v13.

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

Now, open your favorite integrated development environment (IDE). In this demo, we’re using 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

Say No for adding Angular routing, and choose 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.module.ts file and import NgxExtendedPdfViewerModule from ngx-extended-pdf-viewer and pass it to the imports array:

// src/app/app.module.ts

import { NgxExtendedPdfViewerModule } from 'ngx-extended-pdf-viewer';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, NgxExtendedPdfViewerModule],
  providers: [],
  bootstrap: [AppComponent],
})

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:

<!-- src/app/app.component.html -->

<ngx-extended-pdf-viewer
	[src]="'assets/example.pdf'"
	[useBrowserLocale]="true"
	[textLayer]="true"
	[showHandToolButton]="true"
	[showPresentationModeButton]="true"
	[showDownloadButton]="false"
></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 see the PDF file on localhost:4200. You can find the demo application on GitHub.

ngx-extended-pdf-viewer demo

Building an Angular PDF Viewer with PSPDFKit

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.

PSPDFKit 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 PSPDFKit 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.

Now, let’s go back to our tutorial and see how to integrate PSPDFKit into your Angular project.

Stay in the same directory (pdf-viewer) and create a new Angular project for PSPDFKit 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 PSPDFKit

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 PSPDFKit 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:

<!-- src/app/app.component.html -->

<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:

// src/app/app.component.ts

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

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

  ngAfterViewInit(): void {
    PSPDFKit.load({
		// Use the assets directory URL as a base URL. PSPDFKit 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 PSPDFKit for Web instance
      // on the global object so that you can open the dev tools and
      // play with the PSPDFKit 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:

/* src/app/app.component.css */

: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);
}

You can find the example project on GitHub.

Start the app and open it in your default browser:

npm start
yarn start

Conclusion

In this article, we first looked at how to build a PDF viewer with the ngx-extended-pdf-viewer library. In the second part of the article, we walked through how to deploy the PSPDFKit 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 PSPDFKit, 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.

Related Products
Share Post
Free 60-Day Trial Try PSPDFKit in your app today.
Free Trial

Related Articles

Explore more
DEVELOPMENT  |  Web • TypeScript • Insights

Migrating Our Web Codebase from Flow to TypeScript

DEVELOPMENT  |  Web • JavaScript • Tips

Practical Uses of Object URLs

PRODUCTS  |  Web • Releases • Components

PSPDFKit for Web 2021.6 Adds Document Comparison and Date/Time Picker Feature