Displaying PDF in Angular App

Dhrubo Dh
3 min readMar 10, 2021

--

In a previous post, I wrote about my experience with viewing PDF files in a React app with a library called react-pdf. Check out the post here: https://dhrubot.medium.com/displaying-pdf-in-react-383540a30a26. In this post, I am going to share my experience and the library that I used to achieve the same thing (viewing PDF) in an Angular app.

So there are few popular options when it comes to viewing PDF files in an Angular app:

  • Using the built-in PDF viewer of your browser,
  • The PDF viewer of Mozilla and Chrome named pdf.js,
  • Using an Angular library like ng2-pdf-viewer .

For this post, I am going to share my experience with the ng2-pdf-viewer library.

First, using the Angular CLI, I have created a demo app for this post:

ng new angular-pdf

Next, I went into the project folder and ran the local development server:

cd angular-pdf
ng serve -o

Next, I opened another tab in the terminal in the same project folder and installed the ng2-pdf-viewer pdf library:

npm install ng2-pdf-viewer

Now it was time to import the library to the app module so I could use it in my app. For that, I opened the app with visual studio code and navigated to the app.module.ts file, and imported the PdfViewerModule from the library as follows:

Since the module had been imported now I could use the <pdf-viewer> that was provided by the library in the template. <pdf-viewer> takes an src attribute among others and that’s where I needed to point out the pdf file that I needed to display. For that, I declared a variable in the app.component.ts and in the template just passed that variable. In this demo, I decided to use a local PDF file that I am hosting in my project's assets folder. Alternatively, I could just pass in a URL string to the variable as well if I wanted to view a pdf that’s been hosted somewhere else. After the set up my app.component.ts and app.component.html looked like this:

app.component.ts
app.component.html

And in the browser:

There is the pdf file in my angular app. By default, this will show all the pages one after another, but I wanted to show one page at a time so I took advantage of the ‘page’ property of ng2-pdf-viewer and (after-load-complete) event property and finally my component and templates looked like this:

App.component.html

The final result in the browser is:

That’s it. That’s how I integrated the PDF file viewing option in an Angular app. thanks for reading. Any suggestions and feedback would be appreciated.

--

--

Responses (1)