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

Question

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

Answer

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

This answer was originally posted on Stack Overflow. You can find the full discussion here

Related Posts

Transfer git repositories from GitLab to GitHub - can we, how to and pitfalls (if any)?

## Question Can one transfer repositories from GitLab to GitHub if the need be. If so, how exactly can I go about doing the same? Also, are there any pitfalls in doing so or precautionary measures

Read More

Cannot set headers after they are sent to the client - error

## Question Error `[ERR_HTTP_HEADERS_SENT]`: Cannot set headers after they are sent to the client ```text `at ServerResponse.setHeader (_http_outgoing.js:558:11) at ServerResponse.header (D:\D

Read More

Pulling data with 'Where' and 'Include' statements at the same time

## Question I have managed to get my include statements working with my foreign keys however when I try to add a 'where' statement to the findAll statement I am getting the below error. I have check

Read More