Build an Angular PDF Viewer with ng2-pdf-viewer
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:
-
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
-
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.
-
Change your directory into the newly created folder:
cd ng2-pdf-viewer
Adding ng2-pdf-viewer to Your Angular Project
-
Run the command below to install the
ng2-pdf-viewer
library vianpm
oryarn
. This will install the latest version of the library:
npm install ng2-pdf-viewer
yarn add ng2-pdf-viewer
-
Now, go to the
app.module.ts
file and importPdfViewerModule
fromng2-pdf-viewer
and pass it to theimports
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
-
Add your PDF document to the
src/assets
directory. You can use our demo document as an example. -
Go to the
app.component.html
file and replace the contents of the file with the<pdf-viewer></pdf-viewer>
tag. You’ll use thesrc
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.
-
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; }
-
Now, go to
src/app/app.component.ts
and declare thesrc
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. }
-
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.
Adding Navigation Features to Your ng2-pdf-viewer PDF Viewer
-
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.
-
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--; } }
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
-
Install
pspdfkit
as a dependency withnpm
oryarn
:
npm install pspdfkit
yarn add pspdfkit
-
Now, add the following to your
angular.json
file. Angular will copy the PSPDFKit library assets to theassets
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 our demo document as an example. -
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>
-
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.
-
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); }
You can access the project on GitHub.
-
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:
- Adding annotations
- Editing documents
- Filling PDF forms
- Adding signatures to documents
- Real-time collaboration
- Redaction
- UI customization
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.