Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use PDF.js in Angular 2/4/5?

I'm trying to develop PDfViewer Application using Mozilla's PDF.js (example here). It would be great if there is any github project as a reference.

Thanks inadvance!!

like image 784
Ravi Kumar B Avatar asked Mar 29 '18 04:03

Ravi Kumar B


People also ask

How do I open a PDF in angular 9?

Open your web browser and navigate to the http://localhost:4200/ address to see your app running. Once the library has been imported, you can use the ng2-pdf-viewer component in your Angular application.

Does PDF JS work on Chrome?

What Browsers does PDF. js Support. PDF. js is used within Mozilla Firefox today as the built-in PDF viewer, and it works well within a website when viewed using the latest versions of Chrome and Firefox, whether through the pre-built PDF.


3 Answers

PDF.js with typings in Angualr 10

ng2-pdf-viewer is a great solution. I needed to use PDF.js directly as for the requirement to generate thumbnail in a service without creating a component.

This works as of Angular 10:

  • npm i pdfjs-dist
  • npm i @types/pdfjs-dist

Import and Usage. Note the GlobalWorkerOptions.workerSrc = pdfWorkerSrc;:

import { getDocument, GlobalWorkerOptions, PDFDocumentProxy, PDFRenderParams, version, ViewportParameters } from 'pdfjs-dist';

export class MyPdfService {
  private document: Document;

  constructor(@Inject(DOCUMENT) document) {
    this.document = document;
    const pdfWorkerSrc = `https://cdnjs.cloudflare.com/ajax/libs/pdf.js/${version}/pdf.worker.min.js`;
    GlobalWorkerOptions.workerSrc = pdfWorkerSrc;
  }

  // My use case demonstrating strongly typed usage.
  public async pdfToImageDataURLAsync(pdfFile: File): Promise<string> {
    const arrayBuffer = await new Response(pdfFile).arrayBuffer();
    const canvas = this.document.createElement('canvas'),
      ctx = canvas.getContext('2d') as CanvasRenderingContext2D,
      data = arrayBuffer;

    const pdf: PDFDocumentProxy = await getDocument(data).promise;
    const page = await pdf.getPage(1);

    const viewPortParams: ViewportParameters = { scale: 2 };
    const viewport = page.getViewport(viewPortParams);

    canvas.height = viewport.height;
    canvas.width = viewport.width;

    const renderContext: PDFRenderParams = {
      canvasContext: ctx,
      viewport: viewport
    };

    const renderedPage = await page.render(renderContext).promise;
    const res = canvas.toDataURL();
    if (pdf != null) pdf.destroy();
    return res;
  }
}
like image 162
ttugates Avatar answered Oct 05 '22 04:10

ttugates


If it is not a must to use Mozilla's PDF.js then you can use ng2-pdf-viewer npm module which uses PDF.js in background. You can start of it with following steps

Install

npm install ng2-pdf-viewer --save

Note: For angular 4 or less use version 3.0.8

Then, import the module in app.module.js

import { PdfViewerModule } from 'ng2-pdf-viewer';

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

And then use it in your component

@Component({
  selector: 'example-app',
  template: `
  <pdf-viewer [src]="pdfSrc" 
              [render-text]="true"
              style="display: block;">
  </pdf-viewer>
})

For more details, refer the below git URL and the demo URL.

https://github.com/VadimDez/ng2-pdf-viewer

https://vadimdez.github.io/ng2-pdf-viewer/

Hope this helps you.

like image 39
Suvethan Nantha Avatar answered Oct 05 '22 05:10

Suvethan Nantha


If the requirement is to use pdfjs directly on angular, here is the relevant code

  1. copy the 'web' and 'build' folders from https://github.com/mozilla/pdfjs-dist under your application's assets folder.
  2. Get/Create your `Blob() object
this.http.get(url, { responseType: ResponseContentType.Blob }).map(
(res) => {
  return new Blob([res.blob()], { type: fileType });
});

3.Create url using blob and supply to viewer.html

// myBlob object is created over http call response. See item 2.
const fileUrl = URL.createObjectURL(myBlobObject);
let myFileName = "sample";
var viewerUrl = `assets/pdfjs/web/viewer.html?file=${encodeURIComponent(fileUrl)}&fileName=${sample}.pdf`;
window.open(viewerUrl);

You may have to manually upgrade pdfjs if you follow this steps.

If you are looking to use an easier solution without all these manual steps, install https://www.npmjs.com/package/ng2-pdfjs-viewer and follow the instructions.

The usage would be as easy as
<ng2-pdfjs-viewer pdfSrc="report.pdf"></ng2-pdfjs-viewer>

like image 31
int-i Avatar answered Oct 05 '22 04:10

int-i