使用 JavaScript 将 ArrayBuffer 转换为 PDF 文件

问题描述

我将数组缓冲区作为数据,并希望将其转换为 pdf 文件并在浏览器(最好)中在线查看或下载。 我的数据是这种格式:[{37,80,68,70,45,49,46,55,10,52,32,48,111,98,106,40,73,100,101,110,116,105,146,53,65,41,100}]

我首先将其转换为 blob,然后将其转换为 URL ...

这是我当前的代码,它不起作用:( 我得到:“无法加载 PDF 文档。”

.html

<html lang="en">
    <head>
        <link rel="preconnect" href="https://fonts.gstatic.com">
        <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@200;300&display=swap" rel="stylesheet">
        <Meta charset="utf-8">
        <title>All Products</title>
        <style>
            *{
                font-family: 'Poppins';
            }
            .products{
                background-color: aqua;
                margin-bottom: 10px;
                border-radius: 20px;
                padding: 10px 0px 10px 20px;
            }
            p{
                line-height: 16px;
                margin: 0%;
            }
            button{
                height: 30px;
                width: 50px;
            }
        </style>
    </head>
    <body>
        <div id="allpdf"></div>
    </body>
    <script src="index.js"></script>
</html>

.js

function fetchData() {
    fetch('http://localhost:3000/pdffiles')
        .then(response => {
            return response.json();
        })
        .then(data => {
            console.log(data);
            const html = data.map(pdffile => {
                return `
           <div class="products">
           <p><button (click)="getPdfFile(${pdffile.File.data})">${pdffile.ID}</button></p>
                <p style="margin-top:10px">Bill_ID: ${pdffile.BILL_ID}</p>
                <p>Customer: ${pdffile.Customer_ID}</p>
           </div>
           `;
            })
                .join("");
            console.log(html);
            document
                .querySelector('#allpdf')
                .insertAdjacentHTML("afterbegin",html);
        })
        .catch(error => {
            console.log(error);
        })
}
function getPdfFile(item){  
    let array = new Uint8Array(item);
    let blob = new Blob([array],{ type: 'application/pdf' });
    let url = URL.createObjectURL(blob);
    let fileName = new Date().toLocaleDateString();
    try {
      const link = document.createElement('a');
      if (link.download !== undefined) { 
        link.setAttribute('href',url);
        link.setAttribute('download',fileName);
        link.style.visibility = 'hidden';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      }
    } catch (e) {
      console.error('BlobToSaveAs error',e);
    }
  }

fetchData();

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)