最近出差開了好多發(fā)票,寫了一個(gè)pdf合并網(wǎng)站,用于把多張發(fā)票pdf合并成一張,方便打印
使用pdf-lib這個(gè)庫實(shí)現(xiàn)的pdf合并功能,預(yù)覽使用的是瀏覽器自身查看pdf功能
源碼文章來源:http://www.zghlxwxcb.cn/news/detail-515080.html
網(wǎng)頁地址 https://zqy233.github.io/PDF-merge/文章來源地址http://www.zghlxwxcb.cn/news/detail-515080.html
<!DOCTYPE html>
<html>
<head>
<title>PDF合并</title>
<script src="https://cdn.jsdelivr.net/npm/pdf-lib@1.17.1/dist/pdf-lib.min.js"></script>
</head>
<body>
<input type="file" id="fileInput" multiple />
<button onclick="previewMergePDF()">預(yù)覽合并的PDF</button>
<button onclick="downloadMergePDF()">下載合并的PDF</button>
<script>
async function previewMergePDF() {
const fileInput = document.getElementById("fileInput");
const files = fileInput.files;
if (files.length < 2) {
alert("請(qǐng)至少選擇兩個(gè)PDF文件進(jìn)行合并!");
return;
}
// 創(chuàng)建一個(gè)新的PDF文檔
const mergedPdf = await PDFLib.PDFDocument.create();
// 遍歷選擇的每個(gè)文件
for (let i = 0; i < files.length; i++) {
const file = files[i];
const reader = new FileReader();
// 讀取文件內(nèi)容
const fileContents = await new Promise((resolve, reject) => {
reader.onload = function (event) {
resolve(event.target.result);
};
reader.onerror = function (event) {
reject(new Error("文件讀取錯(cuò)誤。"));
};
reader.readAsArrayBuffer(file);
});
// 將PDF文件添加到合并的PDF文檔中
const pdf = await PDFLib.PDFDocument.load(fileContents);
const copiedPages = await mergedPdf.copyPages(
pdf,
pdf.getPageIndices()
);
copiedPages.forEach((page) => {
mergedPdf.addPage(page);
});
}
// 使用瀏覽器自帶預(yù)覽功能,預(yù)覽合并后的PDF
const mergedPdfBytes = await mergedPdf.save();
const mergedPdfBlob = new Blob([mergedPdfBytes], {
type: "application/pdf",
});
const fileURL = URL.createObjectURL(mergedPdfBlob);
window.open(fileURL);
}
async function downloadMergePDF() {
const fileInput = document.getElementById("fileInput");
const files = fileInput.files;
if (files.length < 2) {
alert("請(qǐng)至少選擇兩個(gè)PDF文件進(jìn)行合并!");
return;
}
const mergedPdf = await PDFLib.PDFDocument.create();
for (let i = 0; i < files.length; i++) {
const file = files[i];
const reader = new FileReader();
const fileContents = await new Promise((resolve, reject) => {
reader.onload = function (event) {
resolve(event.target.result);
};
reader.onerror = function (event) {
reject(new Error("文件讀取錯(cuò)誤。"));
};
reader.readAsArrayBuffer(file);
});
const pdf = await PDFLib.PDFDocument.load(fileContents);
const copiedPages = await mergedPdf.copyPages(
pdf,
pdf.getPageIndices()
);
copiedPages.forEach((page) => {
mergedPdf.addPage(page);
});
}
const mergedPdfFile = await mergedPdf.saveAsBase64();
const downloadLink = document.createElement("a");
downloadLink.href = "data:application/pdf;base64," + mergedPdfFile;
downloadLink.download = "merged.pdf";
downloadLink.click();
}
</script>
</body>
</html>
到了這里,關(guān)于前端使用pdf-lib庫實(shí)現(xiàn)pdf合并,window.open預(yù)覽合并后的pdf的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!