将从pdfkit生成的PDF作为输入提供给PDF库以进行合并



我正在尝试将一个pdfkit生成的pdf文件作为输入发送到pdflib以进行合并。我正在使用异步函数。我的项目正在使用sails Js版本进行开发:^1.2.3"节点":"12.16";,我的pdf工具包版本是:^0.11.0〃"pdf库":"1.9.0〃;,这是代码:

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

我得到的错误是:

未处理的PromiseRejection警告:错误:无法分析PDF文档(行:0列:0偏移量=0(:找不到PDF标头

请帮我解决这个问题。

您真的不需要这一行。

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

最新更新