Dev.to WebDev 🛠 Dev 👁 0 📖 3 min read

Merge PDFs entirely in the browser with pdf-lib (no server, ~30 lines)

A lot of "merge PDF" features get built the same way: upload the files, run a library on the server, send the result back. That works, but for contracts, payslips or medical forms it means sensitive documents leave the u

A lot of "merge PDF" features get built the same way: upload the files, run a library on the server, send the result back. That works, but for contracts, payslips or medical forms it means sensitive documents leave the user's machine for something the browser can do by itself.

Here is a small, dependency-light way to merge PDFs client-side with pdf-lib. Nothing is uploaded; the files are read, combined and downloaded inside the tab.

1. Install

npm install pdf-lib

(Or load it from a CDN as an ES module if you're prototyping in a single HTML file.)

2. A file input

<input id="files" type="file" accept="application/pdf" multiple />
<button id="merge">Merge</button>

The order of input.files is the order the user picked them in, which is not always what they want. In a real UI you'd let them drag to reorder; for this example we'll keep the selection order.

3. The merge itself

import { PDFDocument } from "pdf-lib";

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);
    const pages = await merged.copyPages(src, src.getPageIndices());
    pages.forEach((page) => merged.addPage(page));
  }

  return merged.save(); // Uint8Array
}

The key detail is copyPages: you can't just add a page object from one document to another, because pages reference fonts, images and other objects owned by their source document. copyPages copies those dependencies into the target document for you.

4. Download the result

document.getElementById("merge").addEventListener("click", async () => {
  const files = [...document.getElementById("files").files];
  if (files.length < 2) return alert("Pick at least two PDFs");

  const bytes = await mergePdfs(files);
  const blob = new Blob([bytes], { type: "application/pdf" });
  const url = URL.createObjectURL(blob);

  const a = document.createElement("a");
  a.href = url;
  a.download = "merged.pdf";
  a.click();

  URL.revokeObjectURL(url);
});

revokeObjectURL matters if users merge several times in one session; otherwise each blob stays in memory until the page is closed.

Gotchas I'd plan for

  • Encrypted PDFs. PDFDocument.load throws an EncryptedPDFError for password-protected files. There's an ignoreEncryption: true option, but it doesn't decrypt anything, so the output can be broken. Better to catch the error and tell the user which file is protected.
  • Big files. Everything lives in memory. A handful of scanned 50 MB PDFs can push a phone browser over its limit. Show progress per file and consider a soft size warning.
  • Form fields. Copying pages from several documents that have fields with the same name can produce clashes. If forms matter, flatten them first (pdfDoc.getForm().flatten()) before copying.
  • Bookmarks/outline. pdf-lib copies pages, not the source outline, so the merged file won't keep the original bookmarks.
  • Heavy work on the main thread. For large merges, move mergePdfs into a Web Worker so the UI doesn't freeze; File objects and ArrayBuffers can be posted to a worker.

Why bother doing it client-side?

  • Privacy: the documents never touch your server, which also means one less thing to secure, log-scrub or delete.
  • Cost: no compute or bandwidth for processing on your side.
  • It works offline once the page is loaded.

The trade-off is that you're limited by the user's device memory and you can't do things that need server-only tools (like full Ghostscript-level recompression). For merging, splitting, reordering and rotating pages, the browser is more than enough.

Disclosure: this article was written with AI assistance. I reviewed the code and the claims about pdf-lib's behaviour before publishing.

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.