首页 > 解决方案 > 如何在角度 9 中使用 print.js 打印多个 PDF

问题描述

我曾尝试使用print.js库打印 PDF,它适用于单个 PDF 打印。现在,当我尝试打印多个 PDF 时,它会引发错误:错误多项选择。. 另外,我尝试过使用纯 JS,但它会多次提示多个文档。

下面是我们正在使用的代码。

printJS({ 
         printable: ['dummy.pdf', 'dummy1.pdf'], 
         type:'pdf'
        });

请找到附件。

在此处输入图像描述 任何帮助非常感谢!

标签: javascriptangulartypescriptangular9printjs

解决方案


最后,在花费 1 周后,我可以使用 angular 9 中的 print.js 打印多个 PDF。以下是打印多个 pdf 的以下步骤:

  1. 安装 npm 模块:PDF-lib

    npm i pdf-lib

  2. 在角度文件中导入 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);
     }
    }
    
  3. 调用打印函数(app.component.html)

    <button (click)="printPDFS()">print pdfs</button>

参考:pdf-lib


推荐阅读