Render PDF in Angular 4+
By the end of this reading you’ll be able to show PDFs in your angular application.
Create demo project
Firstly we will need to create a demo project. For simplicity we will use ng cli.
After you installed ng-cli, we will create our demo project called pdf-examle with this command in your terminal:
ng new pdf-example
once you’ve created the project — navigate inside the project with:
cd pdf-example
ng2-pdf-viewer integration
Once we are all set up with our demo project, add ng2-pdf-viewer package to our application:
npm install ng2-pdf-viewer --save
After we installed package open app.module.ts
in src/app/
, import PdfViewerModule from ng2-pdf-viewer
and add it to imports
of our module, so that in the end our app.module.ts
looks like this:
We are done with app.module.ts
, now lets move directly to our component. Open app.component.html
in src/app/
and replace it’s content with following:
<pdf-viewer src="https://vadimdez.github.io/ng2-pdf-viewer/assets/pdf-test.pdf" [original-size]="false" style="height: 500px; width: 400px;"></pdf-viewer>
Here you go, our PDF is rendered.
Run npm start
and open https://localhost:4200 and you’ll see our rendered PDF.
Configure
Wouldn’t it be better to configure our pdf viewer exactly for our use case?
ng2-pdf-viewer has several properties:
- [src]
- [(page)]
- [stick-to-page]
- [external-link-target]
- [render-text]
- [rotation]
- [zoom]
- [original-size]
- [fit-to-page]
- [show-all]
- [autoresize]
- (after-load-complete)
- (error)
- (on-progress)
Now imagine that we want to make a PDF presentation. To do that we need the following:
- show PDF pages one by one
- show next and previous buttons
- show both actual page and total pages
navigate to our view app.component.html
and replace it with this:
now you can see that pdf-viewer component has more properties: [show-all], [page] and (after-load-complete)
[show-all] is an input property that tells component that we want all or only one page to be rendered. In our case we set it to false — so only one page will be rendered.
[page] is an input property, used in combination with [show-all]=”false” and tells component which page to render. In our case page
is dynamic and will change on previous or next button press.
(after-load-complete) is an event property that returns data about PDF once it is loaded. afterLoadComplete
function will be fired with PDF data once load is complete. We will make use of it to get total number of pages.
To see all the properties available visit https://github.com/vadimdez/ng2-pdf-viewer
Now lets move to our app.component.ts
and replace it with:
The result look like this: