Search code examples
javascriptangularpdfdownloadangular11

how to download PDF from byteArray in angular 11?


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


Solution

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