如何从 Angular 9 中的字节数组打开 PDF?

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

我有一个 WebApi 方法,它 returns 一个字节数组到 angular 前端。 我已经尝试了所有方法,从将其作为 Blob 读取、将其作为数组缓冲区读取、将其从字节数组转换为 Blob,但均无济于事。每次我都收到无法打开 pdf 的错误。

组件中的示例代码:

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

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

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

}

angular 的 HttpClient 中可能存在问题,由于某种原因,它无法正确读取您作为数组缓冲区的响应。之前尝试将其转换为 Uint8Array,它可以为您提供适合进一步处理的结构:

试试看:


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