0

I have a PDF file stored in a directory within the application (assets/pdf/fileName.pdf). I need to display it on a new tab on a button click from a dialog.

Here is what I have, after looking at various answers:

In *.component.ts:

  openPDF() {
    this.myService.fetchPDF().subscribe(
      res => {
        let file = new window.Blob([res], {type: 'application/pdf'});
        let fileURL = window.URL.createObjectURL(file);
        window.open(fileURL, '_blank');
      }
    );
  }

In *.service.ts:

  fetchPDF(): any {
    const path = 'assets/pdf/fileName.pdf';
    return this.httpClient.get(PathResolver.resolveStatic(path),{responseType : 'blob'});
  }

I already tried using responseType : 'arraybuffer', but it didn't work out either.

Here are the threads I have looked at:

Tung
  • 5
  • 1
  • 7
  • What is the outcome of your current code? – amanpurohit Apr 21 '20 at 05:58
  • @amanpurohit: On Chrome, the new tab opens and closes right away. On Firefox, I was able to see the error saying something along the line of the PDF file is corrupted or invalid. – Tung Apr 21 '20 at 15:04

2 Answers2

1

I am not sure why are you using httpClient. The outcome that you want could be simply achieved by the following code

In *.service.ts:

fetchPDF(): any {
  const path = 'assets/pdf/fileName.pdf'
  return path;
}

In *.component.ts:

openPDF() {
  window.open(this.myService.fetchPDF(), '_blank');
}
amanpurohit
  • 1,246
  • 11
  • 19
  • I tried your suggestion with different PDF files, but on Firefox, all of them got a 304 response code, whilst on Chrome, they showed the "failed to load" error. – Tung Apr 21 '20 at 22:49
  • I looked at the "target" folder after doing a local maven build. It seems like the pdf file is somehow malformed. It's just a blank document when I opened it. Any idea why? – Tung Apr 21 '20 at 23:46
  • It turns out the maven build corrupted the `.pdf` file. I followed the instruction in this answer and the pdf file being rendered just fine: https://stackoverflow.com/a/16088835/4570571 – Tung Apr 22 '20 at 00:17
0

You will either need to use the html embed tag (most likely also using a safe pipe), a PDF viewer (like Google PDF Viewer) or you can open the PDF in a new tab (this is the more common approach I see). It depends on your preference.

anothercoder
  • 563
  • 5
  • 10