ng2-pdfjs-viewer
Installation
Step 1: To use this library you need a copy of pdfjs
A. Using pdf-js-gh-pages
a. Download pdfjs-gh-pages from here: https://github.com/mozilla/pdf.js/archive/gh-pages.zip and extract it.
b. Create a `pdfjs` folder under your angular2+ applications `assets` folder
c. Copy `pdf.js-gh-pages/build` and `pdf.js-gh-pages/web` folders from extracted package to `pdfjs` folder.
d. The web/ directory contains a 1 MB PDF file called "compressed.tracemonkey-pldi-09.pdf". This file is a sample and can safely be removed.
ps: More info can be found here: https://github.com/mozilla/pdf.js/wiki/setup-pdf.js-in-a-website
OR
B. Using modified version of viewerJs (Recommended approach)
a. Download/copy the folder pdfjs from https://github.com/intbot/ng2-pdfjs-viewer/tree/master/pdfjs and put it under your angular2+ application's `assets` folder.
b. Now you can use additional settings such as
`[pdfJsFolder]`: To set the folder path under `web` and `build` resides.
`[externalWindow]`: To decide pdf should be inline or in a new tab
`[openFile]`: Show/hide open file icon
`[viewBookmark]`: Show/hide bookmark icon
`[download]`: Show/hide download icon
`[showSpinner]`: Show a simple css based spinner/progress before the pdf loads
Step 2: To install ng2-pdfjs-viewer
, run:
$ npm install ng2-pdfjs-viewer --save
and then from your Angular AppModule
:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { PdfJsViewerComponent } from 'ng2-pdfjs-viewer';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
PdfJsViewerComponent
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Once your PdfJsViewerComponent is imported you can use it in your Angular application like this:
<h1>
{{title}}
</h1>
<ng2-pdfjs-viewer pdfSrc="your pdf file path"></ng2-pdfjs-viewer>
Here is a use case to download and open the pdf as byte array and open in new tab/window:
Please note, pdfSrc can be a Blob or Uint8Array as well
For [externalWindow]="true" to work, pop-ups needs to be enabled at browser level
<button (click)="openPdf();"></button>
<ng2-pdfjs-viewer #pdfViewer style="width: 800px; height: 400px"
[pdfJsFolder]="pdfjs"
[externalWindow]="true"
[openFile]="false"
[viewBookmark]="false"
[download]="false"></ng2-pdfjs-viewer>
<!-- your.component.ts-->
export class RateCardComponent implements OnInit {
@ViewChild('pdfViewer') pdfViewer
...
private downloadFile(url: string): any {
return this.http.get(url, { responseType: ResponseContentType.Blob }).map(
(res) => {
return new Blob([res.blob()], { type: "application/pdf" });
});
}
public openPdf() {
let url = "url to fetch pdf as byte array";
this.downloadFile(url).subscribe(
(res) => {
this.pdfViewer.pdfSrc = res;
}
);
}
License
MIT © Code Hippie