【问题标题】:Feeding PDF generated from pdfkit as input to pdf-lib for merging将从 pdfkit 生成的 PDF 作为输入提供给 pdf-lib 以进行合并
【发布时间】:2020-08-07 15:42:01
【问题描述】:

我正在尝试将 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 标头

请帮我解决这个问题。

【问题讨论】:

  • 你可以尝试使用new ArrayBuffer(textbytes) 代替

标签: node.js sails.js pdfkit pdflib node-pdfkit


【解决方案1】:

你真的不需要这条线。

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);

【讨论】:

    猜你喜欢
    • 2017-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-14
    • 1970-01-01
    • 2011-08-15
    • 2011-07-03
    • 2021-11-14
    相关资源
    最近更新 更多