Blog Post

Build an Angular PDF Viewer with ng2-pdf-viewer

Illustration: Build an Angular PDF Viewer with ng2-pdf-viewer
Information

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

In this blog post, we’ll walk you through building an Angular PDF viewer using the popular ng2-pdf-viewer library. ng2-pdf-viewer is a powerful, open source library designed for rendering PDF files in Angular applications. In our example, we’ll show how to implement navigation between pages, display the page number, and get the total number of pages with ng2-pdf-viewer.

Keep in mind that ng2-pdf-viewer doesn’t provide an out-of-the-box user interface (UI), but you can build your own user interface with custom code. ng2-pdf-viewer has more than 145K weekly downloads on npm, and it can be used as a core viewer.

In the final section of this post, we’ll provide a walkthrough of how you can integrate the PSPDFKit Angular PDF viewer library into an Angular project. Our commercial viewer comes with a customizable UI and out-of-the-box tools like annotations, e-signatures, PDF editing, form filling, and more.

You can also check out our Angular PDF.js blog, in which we build a PDF viewer using ngx-extended-pdf-viewer.

Requirements for Building an Angular PDF Viewer with ng2-pdf-viewer

To get started, you’ll need:

  • The latest version of Node.js.

  • A package manager for installing the Angular CLI and importing packages. You can use npm or Yarn. When you install Node.js, npm is installed by default.

Setup for ng2-pdf-viewer in Angular

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 ng2-pdf-viewer

  1. Create a new Angular project from your terminal:

ng new ng2-pdf-viewer

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

  1. Change your directory into the newly created folder:

cd ng2-pdf-viewer

Adding ng2-pdf-viewer to Your Angular Project

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

npm install ng2-pdf-viewer
yarn add ng2-pdf-viewer
  1. Now, go to the app.module.ts file and import PdfViewerModule from ng2-pdf-viewer and pass it to the imports array:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { PdfViewerModule } from 'ng2-pdf-viewer'; // Import `PdfViewerModule`.

import { AppComponent } from './app.component';

@NgModule({
	declarations: [AppComponent],
	imports: [BrowserModule, PdfViewerModule],
	providers: [],
	bootstrap: [AppComponent],
})
export class AppModule {}

Displaying a PDF with ng2-pdf-viewer

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

  2. Go to the app.component.html file and replace the contents of the file with the <pdf-viewer></pdf-viewer> tag. You’ll use the src attribute to specify the path to the PDF document:

<pdf-viewer
  [src]="src"
  [original-size]="true"
  [render-text]="true"
  [rotation]="0"
  [show-all]="true"
  [fit-to-page]="false"
  [zoom]="1"
  [zoom-scale]="'page-width'"
  [stick-to-page]="true"
  [external-link-target]="'blank'"
  [autoresize]="true"
  [show-borders]="false"
  class="pdf-viewer"
></pdf-viewer>

There are many configuration options you can use. You can see all the options in the ng2-pdf-viewer documentation.

  1. You have to specify the width and height of the viewer. You can add styles to your app.component.css file:

.pdf-viewer {
  height: 100vh;
  width: 80vw;
  display: block;
  margin: 0 auto;
}
  1. Now, go to src/app/app.component.ts and declare the src property to point to the PDF document you want to display:

import { Component } from '@angular/core';

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

export class AppComponent {
  title: string = 'ng2-pdf-viewer';
  src: string = 'assets/pspdfkit-web-demo.pdf';  // Path to your PDF document.
}
  1. All that’s left is to run your project. You can do this by executing the following command:

ng serve

Now, navigate to localhost:4200 to see your PDF file.

ng2-pdf-viewer demo

Adding Navigation Features to Your ng2-pdf-viewer PDF Viewer

  1. You’ll add previous and next buttons, the page number, and the total number of pages. For this, go back to the app.component.html file and add the following code:

<div class="page">
  <nav *ngIf="isLoaded">
    <button (click)="prevPage()" [disabled]="page === 1" class="previous">
      Prev
    </button>
    <button (click)="nextPage()" [disabled]="page === totalPages" class="next">
      Next
    </button>
    <p>{{ page }} / {{ totalPages }}</p>
  </nav>

  <pdf-viewer
    [src]="src"
    [original-size]="true"
    [render-text]="true"
    [rotation]="0"
    [show-all]="false"
    [fit-to-page]="true"
    [zoom]="1"
    [zoom-scale]="'page-width'"
    [stick-to-page]="true"
    [external-link-target]="'blank'"
    [autoresize]="true"
    [show-borders]="false"
    class="pdf-viewer"
    [page]="page"
    (after-load-complete)="afterLoadComplete($event)"
    class="pdf-viewer"
  ></pdf-viewer>
</div>

In the code above, you changed the show-all property to false to display only one page at a time. You also added a page property to dynamically display the current page.

The after-load-complete event is triggered when the PDF is loaded. You can use this event to get the totalPages property.

  1. Now, go to the app.component.ts file and add the following code:

import { Component } from '@angular/core';

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

export class AppComponent {
  title: string = 'ng2-pdf-viewer';
  src: string = 'assets/pspdfkit-web-demo.pdf';

  page: number = 1;
  totalPages: number = 0;
  isLoaded: boolean = false;

  afterLoadComplete(pdfData: any) {
    this.totalPages = pdfData.numPages;
    this.isLoaded = true;
  }

  nextPage() {
    this.page++;
  }

  prevPage() {
    this.page--;
  }
}

Information

You can access the project on GitHub.

Building an Angular PDF Viewer with PSPDFKit

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, you’ll return to the tutorial and see how to integrate PSPDFKit into your Angular project.

First, 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

  1. Install pspdfkit as a dependency with npm or yarn:

npm install pspdfkit
yarn add pspdfkit
  1. 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

  1. Add the PDF document you want to display to the src/assets directory. You can use our demo document as an example.

  2. Replace the contents of app.component.html with the following:

<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>
  1. 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'],
})
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/pspdfkit-web-demo.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.

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

  1. Start the app and navigate to localhost:4200 to see the PDF file:

npm start
yarn start

Adding Even More Capabilities

Once you’ve deployed your viewer, you can start customizing it to meet your specific requirements or easily add more capabilities. To help you get started, here are some of our most popular Angular guides:

Conclusion

In this post, you learned how to set up an Angular PDF viewer using ng2-pdf-viewer, along with how to add basic navigation features. For simple use cases where the primary objective is viewing PDF documents, ng2-pdf-viewer 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 inside the browser — 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.

FAQ

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

What is ng2-pdf-viewer?

ng2-pdf-viewer is an Angular library that allows you to display PDF documents within an Angular application.

How do you display a PDF using ng2-pdf-viewer?

Add the <pdf-viewer> component in your template and specify the path to the PDF document in the src attribute.

Can I customize the PDF viewer in Angular with ng2-pdf-viewer?

Yes, you can customize the PDF viewer by using various input properties and events to control aspects like zoom level and page number, and enable features such as text layers and custom navigation.

What additional features does PSPDFKit offer over ng2-pdf-viewer?

PSPDFKit provides an out-of-the-box UI, annotations, eSignatures, PDF editing, form filling, and more.

How do you integrate PSPDFKit into an Angular project?

Install PSPDFKit via npm or yarn, configure angular.json to include PSPDFKit assets, and initialize it in your component.

Author
Hulya Masharipov Technical Writer

Hulya is a frontend web developer and technical writer at Nutrient 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