javascript - 如何在角度 9 中使用 print.js 打印多个 PDF
问题描述
我曾尝试使用print.js库打印 PDF,它适用于单个 PDF 打印。现在,当我尝试打印多个 PDF 时,它会引发错误:错误多项选择。. 另外,我尝试过使用纯 JS,但它会多次提示多个文档。
下面是我们正在使用的代码。
printJS({
printable: ['dummy.pdf', 'dummy1.pdf'],
type:'pdf'
});
请找到附件。
解决方案
最后,在花费 1 周后,我可以使用 angular 9 中的 print.js 打印多个 PDF。以下是打印多个 pdf 的以下步骤:
安装 npm 模块:PDF-lib
npm i pdf-lib
在角度文件中导入 npm 模块并使用以下代码将多个 pdf 合并为单个 pdf(例如 app.components.ts)
import { PDFDocument } from 'pdf-lib' @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent { title = 'print-multiple-pdfs'; /* Convert the merged pdf array buffer to blob url for print or open in browser.*/ downloadFile(data) { const blob = new Blob([data], { type: 'application/pdf' }); const url= window.URL.createObjectURL(blob); //window.open(url); printJS({ printable: url, type: 'pdf', }) } async printPDFS() { /* Array of pdf urls */ let pdfsToMerge = ['https://cors-anywhere.herokuapp.com/https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf', 'https://cors-anywhere.herokuapp.com/http://africau.edu/images/default/sample.pdf', 'https://cors-anywhere.herokuapp.com/https://www.hq.nasa.gov/alsj/a17/A17_FlightPlan.pdf'] const mergedPdf = await PDFDocument.create(); for (const pdfCopyDoc of pdfsToMerge) { const pdfBytes = await fetch(pdfCopyDoc).then(res => res.arrayBuffer()) //const pdfBytes = fs.readFileSync(pdfCopyDoc); const pdf = await PDFDocument.load(pdfBytes); const copiedPages = await mergedPdf.copyPages(pdf, pdf.getPageIndices()); copiedPages.forEach((page) => { mergedPdf.addPage(page); }); } const mergedPdfFile = await mergedPdf.save(); this.downloadFile(mergedPdfFile); } }
调用打印函数(app.component.html)
<button (click)="printPDFS()">print pdfs</button>
参考:pdf-lib
推荐阅读
- c++ - D2D 坐标与屏幕坐标不匹配
- html - 全屏大小的 div 的 CSS 技巧将我的列表项向右推
- html - 如何在悬停和单击时切换 HTML/CSS 动画
- google-apps-script - Googlesheet 脚本复制范围,但在源数据加载时不复制
- scheme - 在Scheme中定义一个返回表达式运算符的宏?
- twitter-bootstrap-3 - 网格行为 Bootstrap4 与 Bootstrap3
- jquery - jQuery forEach() 和 change() 函数隐藏一个
- angular - 在 Angular 中的 ViewChild 上添加和删除元素类
- android - 如何在我的 Flutter 应用中为多个组织设置 Firebase 身份验证?
- java - Java:通过分隔符反转字符串