【问题标题】:jsPDF - include other pdfjsPDF - 包含其他 pdf
【发布时间】:2019-01-30 08:04:30
【问题描述】:

我正在尝试用 jsPDF 解决这样的问题:

我有存储在服务器上的 PDF 文件。我正在使用 jsPDF 生成另一个 pdf,并尝试将其附加到已经存在的 pdf 文件(如上所述)作为另一个页面。

我用谷歌搜索了它,但找不到任何帮助。我也在stackoverflow上发现了这个问题,但它是不同的场景 - Append Existing Pdf to Jspdf

我怎样才能使它工作? 或者是否有其他插件或其他东西可以做到这一点?

【问题讨论】:

    标签: javascript pdf merge append jspdf


    【解决方案1】:

    很遗憾,今天(2018 年)不支持 jsPDF。

    替代解决方案

    但您可以使用免费的 PHP 库(如 FPDI)来编辑服务器端。使用 FPDI 甚至可以编辑 PDF 文档、提取一些页面并将它们添加到新的 PDF 文档中。怎么做请看here

    您可以使用 AJAX 向您的服务器发送请求,服务器会执行此操作并返回一个新的 PDF。


    更新

    我们在 2020 年 7 月,jsPDF 不支持它。但是一些用户创建了pull request,关于从同一 PDF 文档的页面添加(复制)。在此链接之前,您可以找到如何使用他的功能的示例代码。但是它不能从另一个 PDF 中添加页面。他的函数代码你可以找到here

    使用 JavaScript PDF-lib 的替代解决方案

    您可以使用 JavaScript“PDF-lib”来实现。您可以在GitHub page 上找到源代码和其他信息。您可以在 project page 上找到该库中的许多 演示

    “PDF-lib”可以在任何 JavaScript 环境中创建和修改 PDF 文档。它旨在在任何现代 JavaScript 运行时中工作。在 Node.JS、浏览器、Deno 和 React Native 环境中测试。

    可在项目网站上获取 API 文档:
    https://pdf-lib.js.org/docs/api/

    “使用嵌入 PDF 页面创建 PDF”示例

    const { PDFDocument } = PDFLib;
    
    async function embedPdfPages()
    {
        // Fetch American flag PDF
        const flagUrl = 'https://pdf-lib.js.org/assets/american_flag.pdf',
            // Fetch U.S. constitution PDF
            constitutionUrl = 'https://pdf-lib.js.org/assets/us_constitution.pdf',
            flagPdfBytes = await fetch(flagUrl).then((res) => res.arrayBuffer()),
            constitutionPdfBytes = await fetch(constitutionUrl).then((res) => res.arrayBuffer()),
            // Create a new PDFDocument
            pdfDoc = await PDFDocument.create();
        
        // Add a blank page to the document
        var page = pdfDoc.addPage();
        
        // Embed the first page of the American flag PDF
        const [americanFlag] = await pdfDoc.embedPdf(flagPdfBytes),
            // Load the constitution PDF into a PDFDocument
            usConstitutionPdf = await PDFDocument.load(constitutionPdfBytes),
            // Embed the first page of the constitution
            firstPageOfConstitution = await pdfDoc.embedPage(usConstitutionPdf.getPages()[0]);
    
        // Draw the American flag page
        page.drawPage(americanFlag);
        
        //add a blank new page to the document
        page = pdfDoc.addPage();
        // Draw the first page of the constitution
         page.drawPage(firstPageOfConstitution);
        
        // Serialize the PDFDocument to bytes (a Uint8Array)
        const pdfBytes = await pdfDoc.save();
        // Trigger the browser to download the PDF document
        download(pdfBytes, "pdf-lib_pdf_page_embedding_example.pdf", "application/pdf");
    }
    body {
      width: 100vw;
      height: 100vh;
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
    }
    
    p {
      font-family: helvetica;
      font-size: 24px;
      text-align: center;
      margin: 25px;
    }
    
    .small {
      font-family: helvetica;
      font-size: 18px;
      text-align: center;
      margin: 25px;
    }
    
    button {
      background-color: #008CBA;
      border: none;
      color: white;
      padding: 15px 32px;
      text-align: center;
      font-size: 16px;
    }
    <script src="https://unpkg.com/pdf-lib@1.4.0"></script>
    <script src="https://unpkg.com/downloadjs@1.4.7"></script>
    <p>Click the button to embed PDF pages with <code>pdf-lib</code></p>
    <button onclick="embedPdfPages()">Create PDF</button>
    <p class="small">(Your browser will download the resulting file)</p>

    示例“使用 JPEG 和其他 PDF 作为附件创建 PDF”

    const { PDFDocument, rgb } = PDFLib
    
    async function addAttachments()
    {
        // Define attachment URLs
        const jpgUrl = 'https://pdf-lib.js.org/assets/cat_riding_unicorn.jpg',
            pdfUrl = 'https://pdf-lib.js.org/assets/us_constitution.pdf',
            // Fetch attachments
            jpgAttachmentBytes = await fetch(jpgUrl).then(res => res.arrayBuffer()),
            pdfAttachmentBytes = await fetch(pdfUrl).then(res => res.arrayBuffer()),
    
            pdfDoc = await PDFDocument.create();
    
        // Add the JPG attachment
        await pdfDoc.attach(jpgAttachmentBytes, 'cat_riding_unicorn.jpg',
        {
            mimeType: 'image/jpeg',
            description: 'Cool cat riding a unicorn!',
            creationDate: new Date('2019/12/01'),
            modificationDate: new Date('2020/04/19')
        });
        // Add the PDF attachment
        await pdfDoc.attach(pdfAttachmentBytes, 'us_constitution.pdf',
        {
            mimeType: 'application/pdf',
            description: 'Constitution of the United States',
            creationDate: new Date('1787/09/17'),
            modificationDate: new Date('1992/05/07')
        });
    
        // Add a page with some text
        const page = pdfDoc.addPage();
        page.drawText('This PDF has two attachments. Note that only some appropriated PDF readers can view attachments. For example the Adobe Reader.', {x: 135, y: 415});
    
        // Serialize the PDFDocument to bytes (a Uint8Array)
        const pdfBytes = await pdfDoc.save();
    
        // Trigger the browser to download the PDF document
        download(pdfBytes, "pdf-lib_add_attachments.pdf", "application/pdf");
    }
    body {
      width: 100vw;
      height: 100vh;
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
    }
    
    p {
      font-family: helvetica;
      font-size: 24px;
      text-align: center;
      margin: 25px;
    }
    
    .small {
      font-family: helvetica;
      font-size: 18px;
      text-align: center;
      margin: 25px;
    }
    
    button {
      background-color: #008CBA;
      border: none;
      color: white;
      padding: 15px 32px;
      text-align: center;
      font-size: 16px;
    }
    blockquote
    {
        background-color: rgba(255,229,100,.3);
        border-left: 8px solid #ffe564;
        padding: 15px 30px 15px 15px;
    }
    <script src="https://unpkg.com/pdf-lib@1.7.0"></script>
    <script src="https://unpkg.com/downloadjs@1.4.7"></script>
    <br><br><br>
    <p>Click the button below to create a document and attach a JPEG image and PDF file with <code>pdf-lib</code></p>
    <blockquote>Note that only some PDF readers can view attachments. This includes Adobe Reader, Foxit Reader, and Firefox.</blockquote>
    <button onclick="addAttachments()">Create PDF</button>
    <p class="small">(Your browser will download the resulting file)</p>

    有用的链接:

    【讨论】:

    • 请注意阅读/打开加密的 pdf,您需要获取 FPDI 的付费版本,这使得免费版本在添加到现有 pdf 时非常不切实际。
    • FPDI 不支持导入加密的 PDF 文档。毕竟这没有任何意义,因为生成的文档是一个全新的文档,可以重新加密也可以不重新加密。 FPDI_Protection class 可以加密生成的文档,它是免费 FPDF_Protection class 的增强版本(不是 FPDI_Protection 类)。在这堂课中,我们可以看到如何加密 PDF。
    【解决方案2】:

    jsPDF 不能这样做,但pdf-lib 可以。您可以将两者结合起来,或者单独使用pdf-lib。要在pdf-lib 中加载现有的 pdf,只需执行以下操作:

    async function loadPdf(){
      const response = await fetch('existing.pdf');
      const buffer = await response.arrayBuffer();
      const existingPdfDocBytes = new Uint8Array(buffer);
      const pdfDoc = PDFLib.PDFDocumentFactory.load(existingPdfDocBytes);
      return pdfDoc;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-27
      • 1970-01-01
      相关资源
      最近更新 更多