Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying PDF files in Angular with ng2-pdf-viewer

Tags:

angular

pdf

I'm trying to use the ng2-pdf-viewer component to display several PDFs from my ASP.NET Web API backend. I've added PdfViewerComponent to my module's declarations and the provided example works fine:

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

@Component({
  selector: 'example-app',
  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>
  `
})
export class AppComponent {
  pdfSrc: string = '/pdf-test.pdf';
}

The problem arise when I try to load the pdf src from my any other resource.

I first encountered CORS issues, but I later resolved this with the DomSanitizer. The new error I get whenever I try to load PDFs are:

ERROR Error: Invalid parameter object: need either .data, .range or .url
    at Object.getDocument (pdf.js:2867)
    at PdfViewerComponent.webpackJsonp.../../../../ng2-pdf-viewer/dist/pdf-viewer.component.js.PdfViewerComponent.loadPDF

I've searched high and low for a solution to the problem, but I just can't figure it out. Any help will be deeply appreciated.

If you want me to provide any additional information, please let me know.

like image 949
Mathis Garberg Avatar asked Oct 15 '17 09:10

Mathis Garberg


1 Answers

I noticed that you've posted this question across several forums. I hope that by this time you already have this sorted out. In case you haven't, here's my solution:

So the problem is that my API (and yours I'm presuming) is returning a stream. This apparently does not work with ng2-pdf-viewer. What does work with it are strings, objects, and UInt8Arrays.

If, like myself, you aren't keen on changing the actual response of the API since a lot of other logic depend on it, you can instead transform it on the front end. This is done by setting the HttpResponseType:

this.http.get(
  `/url/to/photo/stream`,
  {responseType: 'arraybuffer' as 'json'}
)

What this essentially does is it typecasts the response which is an arraybuffer to something that can be consumed: json. This is the way I understand it though. More information about this can be found in the Angular repository issues.

The response from this call is now readable by ng2-pdf-viewer!

I hope this helps!

like image 172
Alec Gerona Avatar answered Oct 23 '22 18:10

Alec Gerona