首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在angular 7中将字符串Base64转换为pdf

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

Stack Overflow用户
提问于 2019-04-29 21:26:58
回答 1查看 29.1K关注 0票数 10

我已经使用REST成功地从Java后端向Angular发送了一个附件。

我有一个结果示例: JVBERi0xLjQKJeLjz9MKMyAwIG9iago8PC9Db2xvclNwYWNlL0

角度:

代码语言:javascript
复制
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);
          })
      })

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-04-29 21:46:13

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

代码语言:javascript
复制
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中显示pdf结果,请使用

。你知道怎么做吗?提前感谢

下面是一个如何实现这一点的示例:https://stackblitz.com/edit/angular-rwfdhr

备注:

  • Unfortunately我不能让ngx-extended-pdf-viewer在stackblitz.com上工作。也许你可以在你的环境中试一试。我没有在本地尝试过。取而代之的是,我使用了pdf-viewer,它开箱即用。但我看不出为什么它不能与其他库一起工作,因为工作流具有相同的principle.
  • My解决方案,这是基于我之前的答案。因为我不太了解您的代码库,所以我按照我对您的工作流程的理解来做事情:

代码语言:javascript
复制
- There is a service called `PdfService` (see pdf.service.ts) I created, which basically fetches and returns the base64 encoded PDF content from GitHub Gist that I just created. 
- In the class `AppComponent` (app.component.ts) the base64 content is decoded and converted to blob and that to a `DOMString` URL (via `URL.createObjectURL`).  
- In app.component.html this URL is simply passed to the library for further processing.

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

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

票数 19
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55904420

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档