首页 > 解决方案 > 将从 pdfkit 生成的 PDF 作为输入提供给 pdf-lib 以进行合并

问题描述

我正在尝试将 pdfkit 生成的 pdf 文件作为输入发送到 pdflib 以进行合并。我正在使用异步功能。我的项目正在使用sails Js版本开发:“^1.2.3”,“node”:“^12.16”,我的pdf-kit版本是:“^0.11.0”,“pdf-lib”:“^1.9。 0",这是代码:

const textbytes=fs.readFileSync(textfile);
var bytes1 = new Uint8Array(textbytes);
const textdoc = await PDFDocumentFactory.load(bytes1)

我得到的错误是:

UnhandledPromiseRejectionWarning:错误:无法解析 PDF 文档(行:0 col:0 offset=0):未找到 PDF 标题

请帮我解决这个问题。

标签: node.jssails.jspdfkitpdflibnode-pdfkit

解决方案


你真的不需要这条线。

var bytes1 = new Uint8Array(textbytes);

只需读取文件并发送textbytes参数就足够了。

我使用此函数合并一组 pdfBytes 以制作一个大 PDF 文件:

async function mergePdfs(pdfsToMerge) 
{
    const mergedPdf = await pdf.PDFDocument.create();
    for (const pdfCopyDoc of pdfsToMerge)
    {
        const pdfDoc = await pdf.PDFDocument.load(pdfCopyDoc);
        const copiedPages = await mergedPdf.copyPages(pdfDoc, pdfDoc.getPageIndices());
        copiedPages.forEach((page) => {
            mergedPdf.addPage(page);
        });
    }
    const mergedPdfFile = await mergedPdf.save();
    return mergedPdfFile;
};

所以基本上在你添加函数之后mergePdfs(pdfsToMerge) 你可以像这样使用它:

const textbytes = fs.readFileSync(textfile);
const textdoc = await PDFDocumentFactory.load(bytes1)
let finalPdf = await mergePdfs(textdoc);

推荐阅读