Merge several PDFs into one
Takes an ordered array of File and returns the bytes of the merged PDF.
typescript
import { PDFDocument } from "pdf-lib";
export async function mergePdfs(files: File[]): Promise<Uint8Array> {
const merged = await PDFDocument.create();
for (const file of files) {
const source = await PDFDocument.load(await file.arrayBuffer(), { ignoreEncryption: true });
const pages = await merged.copyPages(source, source.getPageIndices());
pages.forEach((page) => merged.addPage(page));
}
return merged.save();
}Dependencias
pdf-libNotas de uso
- The order of the array is the final page order.
- To download, wrap the bytes in a Blob of type application/pdf and use URL.createObjectURL.
Limitaciones
- Needs at least two PDFs for it to make sense.
- An encrypted PDF may fail to load; ignoreEncryption only helps in some cases.
- It doesn't merge forms or digital signatures in any special way.