我正在创建一个node.js应用程序,我想将pdf中的多个页面合并为单个页面,并创建一个新的最终输出pdf文件。我正在使用 pdf-lib 作为 Node js。
如何用这个pdf-lib实现解决方案或者是否有其他库可以提供帮助?
示例:ABC.pdf 包含 16 页,那么我需要输出文件 XYZ.pdf,该文件有 4 页,每页包含 ABC.pdf 中的 4 页。
你可以使用coherentpdf.js来做到这一点:
https://www.npmjs.com/package/coherentpdf
您可以使用函数“fromFile”加载文件,使用函数“impose”构建新的 PDF,使用函数“toFile”将文件写回。
对于那些来这里希望用 pdf-lib 解决这个问题的人来说,有一个使用 PDFPage.drawPage 的解决方案。
首先嵌入您想要用来在目标页面上绘制的页面到目标文档中。 (在复制/粘贴范例中,这是复制步骤。)您可以选择指定复制信息的边界框。
接下来,在目标页面上绘制嵌入页面,并指定应绘制嵌入页面的位置。 (粘贴步骤。)
最后将页面添加或插入到文档中。
以下示例演示如何将源文件读入 PDFDocument 对象,将页面复制到目标文档,将信息从一个页面复制到另一个页面,以及如何以新的顺序将页面页面写入目标文档:
const pdfFile = await readFile('./source.pdf')
const sourceDoc = await PDFDocument.load(pdfFile)
const destDoc = await PDFDocument.create()
// Copy the pages to the destination document
// The pages are not assigned page numbers at this time
const pages = await destDoc.copyPages(doc, Array.from({ length: 29 }, (el, idx) => idx))
// We are going to copy a box 230 units tall from page index 21, to page index 20
const cropHeight = 230
const copyPageIdx = 21
const pastePageIdx = 20
// This is the new order the pages will appear in
// Some pages have been removed
// Notice that copyPageIdx has been removed
const newPageOrder = [0, 1, 13, 14, 15, 16, 17, 18, 19, 20, 22, 23, 24, 25, 26, 27, 28, 11, 12, 4, 5, 6, 8, 9, 10, 2, 3]
// Embed the cropped information from copyPageIdx into the destination document
// In this case we are cropping the bottom section of the page
const croppedPage = await destDoc.embedPage(pages[copyPageIdx], {
left: 0,
right: pages[copyPageIdx].getWidth(),
bottom: 0,
top: cropHeight,
})
// Draw the embedded page over the destination page at the desired location
// In this example we are placing the cropped information in the bottom left-hand corner
pages[pastePageIdx].drawPage(croppedPage, {
x: 0,
y: 0,
})
// Add the pages to the destination document in the new page order
newPageOrder.forEach((pageNumber) => {
destDoc.addPage(pages[pageNumber])
})
const bytes = await destDoc.save()
const outfile = await open('./dest.pdf', 'w')
outfile.writeFile(bytes)
outfile.close()
可以通过删除目标文档中不可见的页面来改进此示例。一个更简单的示例可能使用单个文档。