简体   繁体   中英

How can I open a PDF from array of bytes in Angular 9?

I have a WebApi method that returns a byte array to an angular frontend. I have tried everything from reading it as a Blob, reading it as an arraybuffer, converting it to a Blob from the byte array, nothing works. Everytime i get the cannot open pdf error.

Sample code in component:

  this.service.getPDF().subscribe((response)=>{

  let file = new Blob([response], { type: 'application/pdf' });            
  var fileURL = URL.createObjectURL(file);
  window.open(fileURL);

Sample code in service.ts:

getPDF(){
const url = `${this.serviceUrl}/pdf`;

const httpOptions = {
  'responseType'  : 'arraybuffer' as 'json'
   //'responseType'  : 'blob' as 'json'        //This also worked
};

return this.http.get<any>(url, httpOptions);

}

Problem can exist in angular's HttpClient which for some reason doesn't read your response as an array buffer correctly. Try to convert it into Uint8Array before, it could give you proper structure that would become ready to further process:

Try that:

const blob = new Blob([new Uint8Array(byteArrays)], { type: "application/pdf" });
    const exportUrl = URL.createObjectURL(blob);
    window.open(exportUrl);
    URL.revokeObjectURL(exportUrl);

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