Build an Angular PDF viewer with ng2-pdf-viewer

Build an Angular PDF viewer with ng2-pdf-viewer

In this blog post, we’ll walk you through building an Angular PDF viewer using the popular ng2-pdf-viewer(opens in a new tab) 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 Nutrient 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.

Introduction to ng2-pdf-viewer

ng2-pdf-viewer is a widely used PDF viewer component for Angular applications, offering a seamless way to render PDF files directly within your app. This robust and user-friendly library supports both local and remote PDF files, making it a versatile choice for developers aiming to add PDF viewing capabilities to their Angular projects.

With ng2-pdf-viewer, you can easily integrate PDF functionality, with options for zooming, rotating, and navigating through PDF pages, all customizable to fit the needs of your application. This component is particularly valuable for projects where users need to view, interact with, or manipulate PDF documents. Whether handling simple documents or complex PDF files, ng2-pdf-viewer is an ideal choice for enhancing user experience in Angular applications.

Requirements for building an Angular PDF viewer with ng2-pdf-viewer

To get started, you’ll need:

Setup for ng2-pdf-viewer in Angular

Go to your terminal and install the Angular command-line interface (CLI)(opens in a new tab). 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:

Terminal window
ng version

Building an Angular PDF viewer with ng2-pdf-viewer

  1. Create a new Angular project from your terminal:
Terminal window
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:
Terminal window
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(opens in a new tab) 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/document.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:
Terminal window
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/document.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(opens in a new tab).

Optimizing performance and compatibility

To enhance performance and compatibility, you can implement the following techniques with ng2-pdf-viewer:

  • Lazy loading — Use lazy loading to load PDF files only when required, minimizing the initial load time, and enhancing app performance.

  • Caching — Caching frequently accessed PDF files can reduce reload times and decrease server requests, enhancing efficiency.

  • Using ngZone and ChangeDetectorRef — For improved performance, you can use Angular’s NgZone service to run the PDF viewer’s operations outside Angular’s default change detection. Additionally, ChangeDetectorRef allows you to manually control change detection, reducing unnecessary cycles, and boosting performance.

Building an Angular PDF viewer with Nutrient

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.

Now, you’ll return to the tutorial and see how to integrate Nutrient into your Angular project.

Step 1: Create a new Angular project

Start by generating a new Angular project:

Terminal window
ng new nutrient-angular-viewer

When prompted:

  • Choose No for Angular routing
  • Choose CSS for stylesheet format

Then navigate to your project directory:

Terminal window
cd nutrient-angular-viewer

Step 2: Install Nutrient Web SDK

Install the SDK with your package manager:

Terminal window
yarn add @nutrient-sdk/viewer

Or, install it with npm:

Terminal window
npm install @nutrient-sdk/viewer

Step 3: Configure angular.json to include SDK assets

In angular.json, locate the assets array and add the following entry to copy the Nutrient SDK files:

"assets": [
"src/assets",
{
"glob": "**/*",
"input": "./node_modules/@nutrient-sdk/viewer/dist/nutrient-viewer-lib/",
"output": "./assets/nutrient-viewer-lib/"
}
]

This allows Nutrient to access its library files from the assets directory at runtime.

Step 4: Add the PDF viewer component

Generate a new component:

Terminal window
ng generate component pdf-viewer

Replace the content of pdf-viewer.component.html with the following code to create a container for the Nutrient viewer:

<div id="nutrient-container" style="width: 100%; height: 100vh;"></div>

Replace pdf-viewer.component.ts with the following code to initialize the Nutrient viewer:

import { Component, OnInit } from "@angular/core";
import NutrientViewer from "@nutrient-sdk/viewer";
@Component({
selector: "pdf-viewer",
templateUrl: "./pdf-viewer.component.html",
styleUrls: ["./pdf-viewer.component.css"],
standalone: true,
})
export class PdfViewerComponent implements OnInit {
ngOnInit(): void {
NutrientViewer.load({
baseUrl: `${location.protocol}//${location.host}/assets/`,
container: "#nutrient-container",
document: "/assets/document.pdf", // replace with your document
}).then((instance) => {
(window as any).instance = instance;
});
}
}

This code initializes the Nutrient viewer and loads a sample PDF document. You can replace the document path with your own PDF file. Place your PDF document in the src/assets/ directory — for example, document.pdf.

Step 5: Use the viewer in your app

Open app.component.ts and import the component:

import { Component } from "@angular/core";
import { PdfViewerComponent } from "./pdf-viewer/pdf-viewer.component";
@Component({
selector: "app-root",
standalone: true,
imports: [PdfViewerComponent],
template: "<pdf-viewer></pdf-viewer>",
})
export class AppComponent {}

Step 6: Run the app

Use the Angular CLI to start your development server:

Terminal window
yarn start

or

Terminal window
npm start

Then open http://localhost:4200 in your browser. You’ll see the Nutrient PDF viewer embedded with a full UI.

You can access the project on GitHub(opens in a new tab).

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

FAQ

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, page number, and enabling features such as text layers and custom navigation.

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

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

How do you integrate Nutrient into an Angular project?

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

Hulya Masharipov

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.

Explore related topics

FREE TRIAL Ready to get started?