node.js - 将从 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 标题
请帮我解决这个问题。
解决方案
你真的不需要这条线。
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);
推荐阅读
- javascript - 循环开始时,我的函数不会重新触发动画。红绿灯闪烁信号一次工作
- android-layout - 内部空心形状矩形可绘制/画布形状
- html - Bootstrap - 在页面顶部放置导航栏,然后将表单居中
- java - java spring boot oracle cdc debezium
- python - 无法更改 Youtube-dl 下载文件夹
- sql-server - 返回 SQL 中返回空值的行?显示它们不是空白值
- python - Python 请求等待重定向
- c++ - 程序从数组中输出不正确的数字
- google-sheets-formula - 使用公式删除谷歌表中的空白行
- java - 什么是用于 SAML 1.x 浏览器配置文件支持的 BrowserProfileProvider 和 SAMLBrowserProfile(opensaml1) 的 Opensaml V4 替代品