Merging PDFs is one of the most common document tasks, and you can do it entirely client-side, so files never leave the user's device. Here is a minimal, working approach with pdf-lib.
Setup
npm install pdf-lib
The merge function
import { PDFDocument } from 'pdf-lib';
export async function mergePdfs(files) {
const merged = await PDFDocument.create();
for (const file of files) {
const bytes = await file.arrayBuffer();
const src = await PDFDocument.load(bytes, { ignoreEncryption: false });
const pages = await merged.copyPages(src, src.getPageIndices());
pages.forEach((p) => merged.addPage(p));
}
return merged.save(); // Uint8Array
}
Wiring it to a file input
const input = document.querySelector('#files');
input.addEventListener('change', async () => {
const out = await mergePdfs([...input.files]);
const url = URL.createObjectURL(new Blob([out], { type: 'application/pdf' }));
const a = Object.assign(document.createElement('a'), { href: url, download: 'merged.pdf' });
a.click();
URL.revokeObjectURL(url);
});
Gotchas
-
Encrypted PDFs.
PDFDocument.loadthrows on password-protected files. Catch the error and ask the user to unlock the file first. - Memory. Everything sits in RAM. Large scans (hundreds of MB) can crash a mobile tab, so warn users or fall back to server-side processing.
-
Order.
input.filesfollows the picker's order, not the user's intent. Add a drag-to-reorder list before merging. - Form fields. Copied pages keep their widgets, but field names can collide across documents. Flatten forms first if that matters.
When client-side isn't enough
Compression, OCR and Office conversions need heavier tooling (Ghostscript, Tesseract, LibreOffice) that is impractical in the browser. A hybrid works well: do lightweight operations like merge, split and rotate on the client, and send only the heavy jobs to a server.
If you just need the result rather than the code, HuntPDF's Merge PDF does this in the browser for free, alongside Split PDF and 50+ other tools.
Top comments (0)