This is another pdf viewer tutorial, I am creating a simple angular 13 tutorial that will display pdf using ng2 pdf viewer libs. We will create an input type element that will take the source path of a pdf file and display it into a div container.
I’m assuming you’ve already created an Angular 13 application; if not, please build a sample project called angular13-pdf-viewer-example. in your terminal, type the following command:
ng new pdf-example
If you are getting ng
command issue then you don’t have ng-cli
installed, You can get help to install angular CLI from Getting started with angular 13.
You can also read other pdf viewer tutorials,
- Simple Example of angular pdf viewer using pdf.js
- PDFObject : Embedded PDF viewer using HTML5
- Exporting a DataTable into PDF File
- Popular JavaScript and jQuery PDF Viewer Plugins
Angular pdf Viewer
Once you’ve created the project using the above command, Please navigate inside the project:
d:\angular13-pdf-viewer-example>
Now install ng2-pdf-viewer
package using npm
as below:
d:\angular13-pdf-viewer-example>npm install ng2-pdf-viewer --save
–save used to save package information into package.json
file.
After successfully installed ng2-pdf-viewer
package, open app.module.ts
file in src/app/
folder and import ng2-pdf-viewer
module, the app.module.ts
looks like this:
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { PdfViewerModule } from 'ng2-pdf-viewer'; import { FormsModule } from '@angular/forms'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, PdfViewerModule, FormsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
We have included package FormsModule
for input element which will have src of pdf file.
Define PDF Viewer Component
Now, Open app.component.ts
file from src/app/
folder, We will define pdf container and input element which will display in the UI. Please replace it’s content with the following:
import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: " <div><label>PDF src</label><input type="text" placeholder="PDF src" [(ngmodel)]="pdfSrc"></div> <pdf-viewer [src]="pdfSrc" [render-text]="true" style="display: block;"></pdf-viewer>", styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'app'; pdfSrc: string = '/assets/sample.pdf'; }
We have to define pdfSrc variable that has the source path of pdf file.
Now Run 'npm start'
and open https://localhost:4200
into browser and you’ll see our rendered PDF file.