5

In Angular, I need to open a PDF in a new tab and allow the user to download it with a specific name (Example.pdf). The code below downloads the PDF however doesn't open a new tab (target=_blank is not working). Any ideas how to fix this?

show(blob){
    var fileURL: any = URL.createObjectURL(blob);
    var a = document.createElement("a");
    a.href = fileURL;
    a.target = '_blank';
    a.download = "Example.pdf";
    a.click();
}
ps0604
  • 1,513
  • 20
  • 113
  • 274

2 Answers2

6

Don't set the download attribute if you would like to open the PDF in new tab.

  public show(blob){
    var fileURL: any = URL.createObjectURL(blob);
    var a = document.createElement("a");
    a.href = fileURL;
    a.target = '_blank';
    // Don't set download attribute
    // a.download = "Example.pdf";
    a.click();
}

However, in new tab, when user tries to download the file, user will see random string instead of a fileName. Explanation here: https://stackoverflow.com/a/41947861/5171009

Prabh
  • 909
  • 5
  • 9
0

I solved it using the method below if anyone is interested in a different method.

Service code:

 fetchDocument(fileUrl) {
        //pass document url to the service
        return this.http.post(
          `http://localhost:3000/mydocuments/${fileUrl}`,
          {},
          {
            responseType: 'arraybuffer',
          }
        );
      }

In your component ts file:

downloadPDF(content) {
    //make a call to the service passing in document url
    this.service.fetchDocument(fileUrl)
      .subscribe(
        (response: any) => {
          let array = new Uint8Array(response);

          //service returns an array buffer so convert array buffer to blob
          let file = new Blob([array], { type: 'application/pdf' });
          let fileURL = URL.createObjectURL(file);
          window.open(fileURL);
        },
        (err) => {
          console.error(err);
        }
      );
  }
Leon Matota
  • 142
  • 1
  • 7