'Open a PDF in a new tab AND download with file name in Angular

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();
}


Solution 1:[1]

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);
        }
      );
  }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Leon Matota