How to create pdf viewer in angular application

Share the post

Hello All, In this angular tutorial we will learn how to create pdf viewer in angular application in detail with the help of an example. In this example, we are going to use the npm package ng2-pdf-viewer.

ng2-pdf-viewer helps us to create a PDF viewer & also we can do many useful things with the help of this package.

Note: ng2-pdf-viewer only supports Angular 5+ versions.

Now, let’s start to create pdf viewer in our angular application.

Step1: Create angular project

Create a new angular project using the following command.

ng new <APPNAME>

Now, move to our root project directory using the following command

cd <APPNAME>

Open the newly created angular project in Visual Studio Code. Use the following command to open the project.

code .

Step2: Install ng2-pdf-viewer NPM package

It’s time to install ng2-pdf-viewer. Open the terminal & write the below command

npm install ng2-pdf-viewer

Step3: Import PdfViewerModule

Now, Import the PdfViewerModule in app.module.ts as shown below.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';
import { PdfViewerModule } from 'ng2-pdf-viewer';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    PdfViewerModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Step4: HTML, TS Code

Write HTML code in app.component.html as follows

<pdf-viewer [src]="pdfSrc" style="width: 500px; height: 500px"></pdf-viewer>

Now, Write the logic in app.component.ts as shown below

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'angular-pdf-viewer';
  pdfSrc = "./assets/doc.pdf";
}

Don’t forget to add your pdf inside the assets folder. If you want to view any external pdf then put the correct URL instead of the local path.

Step5: Output

pdf_viewer_output
Output

Leave a Comment