如何解决使用 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 举报,一经查实,本站将立刻删除。