【问题标题】:Error Failed to load PDF document. (Angular5)错误 无法加载 PDF 文档。 (角5)
【发布时间】:2018-10-05 17:12:54
【问题描述】:

我正在尝试从 Web API 获取 PDF 文档,并希望在 Angular App 中显示。收到“无法加载 PDF 文档错误”。

请按照我的代码:

我的服务.ts

public download_pdf(id: string): Observable<any> {
        let params = new URLSearchParams();
        let headers = new Headers();
        headers.append('x-access-token', this.auth.getCurrentUser().token);
        headers.append('id', id);
        return this.http.get(Api.getUrl(Api.URLS.download_pdf), {
          headers: headers,
          responseType: ResponseContentType.ArrayBuffer,

        }).map(
          response => (<Response>response).blob())
    }

我的组件.ts

  downloadFile2(id) {
    this.ws.download_pdf(id).subscribe(
      (response) => {
        let mediaType = 'application/pdf';
        let blob = new Blob([response._body], {type: mediaType});
        let filename = 'test.pdf';
        FileSaver.saveAs(blob, filename);
      });
  }

模板.html

  <button>
   <i class="fa fa-save" aria-hidden="true"(click)="downloadFile2(item.id)"></i>
  </button>

结果是:下载一个 test.pdf --> Error Failed to load PDF document.

【问题讨论】:

    标签: angular typescript pdf download blob


    【解决方案1】:

    按照以下步骤解决问题。

    步骤 1. 在 API 中将字节数组转换为 base64 字符串,如下所示

    [HttpGet("Downloadpdf/{SessionKey}")]
            public IActionResult Downloadpdf(string SessionKey)
            {
                Byte[] pdf = null;
                try
                {
                    pdf = PDFService.Downloadpdf(SessionKey);//Here you need to modify and get byte array like byte[]
                    string pdfBase64 = Convert.ToBase64String(pdf);
                    return Ok(pdfBase64);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
    

    步骤 2. 添加以下函数,将 base64 字符串转换为 .ts 文件中的 ArrayBuffer

    base64ToArrayBuffer(base64:any):ArrayBuffer {
          var binary_string =  window.atob(base64);
          var len = binary_string.length;
          var bytes = new Uint8Array( len );
          for (var i = 0; i < len; i++)        {
              bytes[i] = binary_string.charCodeAt(i);
          }
          return bytes.buffer;
      }
    

    步骤 3. 在自定义函数中为按钮单击事件调用 step2 函数

    let sessionKey: any ="sessiontoken";
          this.pdfService.downloadpdf(sessionKey).subscribe((data: any) => {
            var byteArray = this.base64ToArrayBuffer(data);
            let blob: any = new Blob([byteArray], { type: 'application/octet-stream' });
            saveAs(blob, 'Report.pdf',true);
          },
          (error: HttpErrorResponse) => {
            console.log(error)
        });
    

    【讨论】:

    • 您提到的更改对我来说效果很好,但我想了解为什么需要转换为 ToBase64String 而不是返回字节数组。
    【解决方案2】:

    您也可以在 Angular 10 中使用它。

    Service.ts

        getPdf():Observable<any> { 
            return this.http.get<any>(`${this.apiUrl}Controller/GetPdf`);
          }
    

    组件.ts

        this.service.getPdf().subscribe((resp) => {
          
              let response = this.base64ToArrayBuffer(resp);
              let file = new Blob([response], { type: 'application/pdf' });            
              var fileURL = URL.createObjectURL(file);
              window.open(fileURL);
            
          });
         }
    
    辅助方法
        base64ToArrayBuffer(base64:any):ArrayBuffer {
          var binary_string =  window.atob(base64);
          var len = binary_string.length;
          var bytes = new Uint8Array( len );
          for (var i = 0; i < len; i++)        {
              bytes[i] = binary_string.charCodeAt(i);
          }
          return bytes.buffer;
        }
    

    【讨论】:

      猜你喜欢
      • 2018-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-13
      相关资源
      最近更新 更多