简体   繁体   中英

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

在此处输入图像描述 在此处输入图像描述

If I write this version resp is : 在此处输入图像描述

and if I rite:

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

resp is在此处输入图像描述

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM