Search code examples
javascriptangularpdfblobpdf-viewer

How to insert blob (response from server) into ngx-extended-pdf-viewer?


I'm setting a new view which contains a pdf viewer. I don't have any path to a pdf file, just back-end returns me a blob object which contains pdf and I have to show this pdf. Now I'm using library ngx-extended-pdf-viewer (link: https://www.npmjs.com/package/ngx-extended-pdf-viewer)

Now I have to use the response from the server (which returns BLOB) and display file. I've tried to ascribe response to the variable then use it inside HTML with an async pipe. Next try was add new FileReader object, pass blob inside it and put it into [src] property. In these two cases browser doesn't show pdf and download it directly.

My all tries: https://ghostbin.com/paste/57akz

Edited: https://ghostbin.com/paste/rb8ou

I just want to use inside [src] my blob object and display properly pdf file without downloading it etc.


Solution

  • Though I haven't used the aforementioned library yet, I had quite success with blob objects and ng2-pdfjs-viewer(https://www.npmjs.com/package/ng2-pdfjs-viewer) building a pdf intense portal.

    Use case for blob objects is like

    <!-- your.component.html -->
    <button (click)="openPdf();">Open Pdf</button>
    
    <!-- your.component.ts-->
    export class SampelComponent 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"; (Blob works here)
        this.downloadFile(url).subscribe(
         (res) => {
            this.pdfViewer.pdfSrc = res; // pdfSrc can be Blob or Uint8Array
            this.pdfViewer.refresh(); // Ask pdf viewer to load/reresh pdf
          }
        );
      }