const { PDFDocument } = require("pdf-lib");
const fs = require("fs");
async function mergePdfs(inputPaths, outputPath) {
const merged = await PDFDocument.create();
for (const path of inputPaths) {
const src = await PDFDocument.load(fs.readFileSync(path));
const pages = await merged.copyPages(src, src.getPageIndices());
pages.forEach((page) => merged.addPage(page));
}
fs.writeFileSync(outputPath, await merged.save());
}
module.exports = { mergePdfs };Install the package with npm install pdf-lib, then call mergePdfs(["a.pdf", "b.pdf"], "out.pdf"). Pages appear in the order you list the files.
How it works
PDFDocument.create makes an empty document. For each input, PDFDocument.load parses the file, getPageIndices returns the index of every page, and copyPages copies those pages into the merged document. copyPages returns the copied pages, and addPage appends each one to the end. Finally save serializes the merged document to bytes.
Tested with a 2-page and a 3-page PDF, the function produced a 5-page file.
Caveats
To merge only some pages, pass your own array of page indices to copyPages instead of getPageIndices, for example [0, 2].
The loop loads every input into memory as it goes and builds the whole output in memory, so very large batches may need splitting into smaller merges. Always check the merged output against your real files, especially anything with form fields, since you may need to confirm how they carry over.
Back to All Questions