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

3

14

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!!

Hirokohiroshi answered 29/3, 2018 at 4:53 Comment(2)
Please do some research before asking here. There are many examples from Mozilla itslef. Check here: github.com/mozilla/pdf.js/blob/master/examples/components/…Turnstone
Hi @VicJordan, Thanks for the reply !! Actually I tried implementing the viewer application using sample example as you mentioned. But I'm facing Please build the pdfjs-dist library using\n' + ' gulp dist-install issue. But the minimal reproducible example (github.com/mozilla/pdf.js/blob/master/examples/components/…) it is in Javascript but Angular support typescript.Hirokohiroshi
S
13

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;
  }
}
Sunroom answered 20/9, 2020 at 17:57 Comment(1)
Above solution getting some exceptions Module '"pdfjs-dist"' has no exported member 'PDFRenderParams'.ts(2305) AND 'ViewportParameters' . Angular 10 version only using with it.Logbook
S
6

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.

Shirlshirlee answered 29/3, 2018 at 5:25 Comment(5)
Hi @Suvethan ,Thanks for the answer. Actually it is must to use Mozila's PDF.js. I'm told to not to use any npm packages like (ng2-pdf-viwer) you mentioned. Do you have any suggestion other than npm package? Thanks in advance!!Hirokohiroshi
@RaviKumarB did you found a solution sir ?Hauteur
ng2-pdfjs-viewer is new and less popular but much betterBrumfield
The problem is that ng2-pdf-viwer doesn't include the controls a normal pdf viewer hasPresidency
@Brumfield ng2-pdfjs-viewer is an interesting suggestion. I took a look at it, and while it does offer some nice functionality, this comment on their npm page is what should take it out of consideration for most people: "This project is currently maintained by a single developer on his spare time."Upturned
U
4

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>

Uncommon answered 7/6, 2019 at 15:39 Comment(4)
Can you please create plunkr/stackblitz example to directly use pdfjs in angular application.Limestone
How about a more concrete example please (i.e stackblitz) ?Hibernicism
Find samples here: ng2-pdfjs-viewer.azurewebsites.net/homeUncommon
Thanks this worked with me in angular but with a little bit extra code.Unlicensed

© 2022 - 2024 — McMap. All rights reserved.