Home > Software design >  how to download PDF from byteArray in angular 11?
how to download PDF from byteArray in angular 11?

Time:05-19

I have byte array and I want to download pdf without any library, for example file-saver.

service.ts

    return this.http.get(`${this.invoiceUrl}/GenerateInvoice`,
         { responseType: "arraybuffer", observe: "response", params }
    );

component.ts

file(byte) {
    var byteArray = new Uint8Array(byte);
    var a = window.document.createElement('a');

    a.href = window.URL.createObjectURL(new Blob([byteArray], { type: 'application/json' }));
    a.download = "data.txt";

    // Append anchor to body.
    document.body.appendChild(a)
    a.click();


    // Remove anchor from body
    document.body.removeChild(a)
  }

//   download   function
    this.invoiceService.generateInvoice(id).pipe(
      finalize(() => this.loadingFlag = false)
    ).subscribe(
      resp => {
        console.log(resp);
         this.file(resp.body)
}

enter image description hereenter image description here

If I write this version resp is :enter image description here

and if I rite:

 return this.http.get(`${this.invoiceUrl}/GenerateInvoice`,
  { responseType: "arraybuffer", observe: "response", params }
);

resp is enter image description here

CodePudding user response:

try this it's worked for me without file-saver:

file(data: any) {
    const blob = new Blob([data], {type: 'application/pdf'});
      let url = URL.createObjectURL(blob);
      const pwa = window.open(url);
      if (!pwa || pwa.closed || typeof pwa.closed === 'undefined') {
        throw error( 'check if your browser block windows');
    }
 }

or you can use this example:

file(data: any) {
    const blob = new Blob([data], {type: 'application/pdf'});
      let filename = 'myPdfFile';
      let url= URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = fileName;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
}

The first example open pdf on your browser and the second download the file.

CodePudding user response:

Solution: In the service file there is no need of responseType.

  downloadPDF(str) {
    const linkSource = 'data:application/pdf;base64,'   str;
    const downloadLink = document.createElement("a");
    const fileName = "sample.pdf";

    downloadLink.href = linkSource;
    downloadLink.download = fileName;
    downloadLink.click();
  }
  • Related