首页 > 解决方案 > 在 Typescript/Angular8 中将 base64 字符串转换为 uint8Array 或 Blob

问题描述

我对使用 Base64 编码的字符串/uint8Array 或 Blob 还是很陌生。我正在为我们的 Angular 8 webapp使用来自这个 repo https://github.com/intbot/ng2-pdfjs-viewer的 pdf 查看器库。我正在发送一个相当大的 Base64 字符串(550KB 到 UI(包含 34 页文本),由 pdf 查看器呈现。

主要问题是它在查看器中仅显示 19 页。但是,当我使用查看器下载文档时,它包含所有 34 页(通过 MacOS 上的 Preview 应用程序确认)。我不确定问题出在 pdf 查看器库还是从 Base64 到 uint8Array/Blob 的转换。

这是 UI 中转换 Base64 字符串的代码

dostuff(b64Data){
    const byteCharacters = atob(b64Data);
    const byteNumbers = new Array(byteCharacters.length);
    for (let i = 0; i < byteCharacters.length; i++) {
      byteNumbers[i] = byteCharacters.charCodeAt(i);
    }
    const byteArray = new Uint8Array(byteNumbers);
    //const blob = new Blob([byteArray], {type: 'application/pdf'});
    //console.log(blob)
    return byteArray
  }

任何帮助将不胜感激。使用浏览器:Chrome

标签: angulartypescriptbase64pdfjsng2-pdfjs-viewer

解决方案


这已解决。问题在于后端 API 将 PDF 合并在一起。使用 Apache PDFBox 的 pdf 合并实用程序,该实用程序接受输入流并且合并的 pdf 文档由 ng2-pdfjs-viewer 库成功呈现。上面的 JS 代码没有问题。


推荐阅读