如何在 Angular 7 中将字符串 Base64 转换为 pdf

问题描述 投票:0回答:2

我已使用 REST 成功将附件从 Java 后端发送到 Angular。

我有结果示例:JVBERi0xLjQKJeLjz9MKMyAwIG9iago8PC9Db2xvclNwYWNlL0

角度:

getImage() {
    this._invoiceCreationHttpService.getImage().subscribe((data: any) => {
      data.forEach(fileUploaded => {
        fetch(fileUploaded.content)
          .then(res => res.blob())
          .then(blob => {
            this.ConvertedBlob = new Blob([fileUploaded.content], {
              type: 'data:application/pdf;base64,'
            });

            console.log(this.ConvertedBlob);
          })
      })

我想在我的视图中显示 pdf (html)。但问题是在后端我将InputStream编码为Base64.getEncoder()。我想知道如何在前端将pdf显示为pdf缩略图。

angular
2个回答
25
投票

如果我没理解错的话,后端会发回base64编码的数据。因此,您必须首先解码响应数据。工作流程应如下所示:

fetch(fileUploaded.content) 
  .then(response => {
    // response.data -> response data base64 encoded
    // decoding the data via atob()
    const byteArray = new Uint8Array(atob(response.data).split('').map(char => char.charCodeAt(0)));
    return new Blob([byteArray], {type: 'application/pdf'});
  })
  .then(blob => {
    // Here is your URL you can use
    const url = window.URL.createObjectURL(blob);

    // i.e. display the PDF content via iframe
    document.querySelector("iframe").src = url;
  });

您可以进一步阅读


编辑:

如果我想使用 .html 在我的 html 中显示 pdf 结果。你知道怎么做吗?预先感谢

以下是如何实现此目的的示例:https://stackblitz.com/edit/angular-rwfdhr

备注:

  • 不幸的是我无法让

    ngx-extended-pdf-viewer
    在stackblitz.com上工作。也许您可以在您的环境中尝试一下。我没有在本地尝试过。相反,我使用了
    pdf-viewer
    ,它开箱即用。但我不明白为什么它不应该与另一个库一起使用,因为工作流程具有相同的原理。

  • 我的解决方案是基于我之前的答案。由于我不完全了解您的代码库,因此我按照我理解您的工作流程的方式完成了操作:

    • 我创建了一个名为

      PdfService
      的服务(请参阅 pdf.service.ts),它基本上从我刚刚创建的 GitHub Gist 获取并返回 base64 编码的 PDF 内容。

    • 在类

      AppComponent
      (app.component.ts) 中,base64 内容被解码并转换为 blob,然后转换为
      DOMString
      URL(通过
      URL.createObjectURL
      )。

    • 在 app.component.html 中,此 URL 只是传递到库以进行进一步处理。


编辑2:上面的例子并不完全适合Angular方式。您应该在服务中实现业务逻辑,并保持控制器尽可能精简。

这是一个演示:https://stackblitz.com/edit/angular-4k63jv


0
投票

感谢您将泰国的 Base64string 代码转换为 PDF

© www.soinside.com 2019 - 2024. All rights reserved.