Files
Snippets/src/js/print/index.html
2024-06-06 17:42:35 +08:00

56 lines
1.8 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<button onclick="handlePrint()">打印</button>
<script src="./node_modules/print-js/dist/print.js"></script>
<script src="./node_modules/pdf-lib/dist/pdf-lib.js"></script>
<script>
async function handlePrint() {
const pdfUrls = [
"./assets/test.pdf",
"./assets/test.pdf",
"./assets/test.pdf",
];
const url = await mergePDFs(pdfUrls);
// 调用打印功能,无需打开文件再手动打印
printJS(url);
}
// 批量打印与分页打印
async function mergePDFs(pdfUrls) {
// 创建一个新的空白PDF文档
const mergedPdfDoc = await PDFLib.PDFDocument.create();
for (const pdfUrl of pdfUrls) {
// 获取PDF文件的二进制数据
const pdfBytes = await fetch(pdfUrl).then((response) =>
response.arrayBuffer()
);
// 将获取到的PDF文件添加到新的文档中
const pdfDoc = await PDFLib.PDFDocument.load(pdfBytes);
// 如果单个PDF为多页则要一页一页往新建的PDF中添加
const copiedPages = await mergedPdfDoc.copyPages(
pdfDoc,
pdfDoc.getPageIndices()
);
copiedPages.forEach((page) => mergedPdfDoc.addPage(page));
}
// 将合并后的PDF保存为Blob对象
const mergedPdfBytes = await mergedPdfDoc.save();
const mergedPdfBlob = new Blob([mergedPdfBytes], {
type: "application/pdf",
});
return URL.createObjectURL(mergedPdfBlob);
}
</script>
</body>
</html>