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

Merging PDFs in the browser: no server, no upload

Merging PDFs sounds like server work, but the PDF format is just a structured binary file — and libraries like pdf-lib can read and write it entirely in JavaScript. So the merge can happen in the tab, with your documents

Merging PDFs sounds like server work, but the PDF format is just a structured binary file — and libraries like pdf-lib can read and write it entirely in JavaScript. So the merge can happen in the tab, with your documents never uploaded anywhere.

The whole trick

import { PDFDocument } from 'pdf-lib';

async function mergePDFs(files) {
  const merged = await PDFDocument.create();
  for (const file of files) {
    const pdf = await PDFDocument.load(await file.arrayBuffer());
    const pages = await merged.copyPages(pdf, pdf.getPageIndices());
    pages.forEach(page => merged.addPage(page));
  }
  const bytes = await merged.save();
  return new Blob([bytes], { type: 'application/pdf' });
}

That's genuinely it: load each file into memory, copy its pages into a fresh document, save. copyPages preserves vector content, fonts, and images — the output isn't a rasterized screenshot, it's a real PDF.

The gotchas

  • Encrypted PDFs: pdf-lib can't open password-protected files silently. Pass the password via the load options, or handle the failure gracefully and tell the user why.
  • Memory: everything lives in RAM. Fine for typical documents; on mobile, warn before merging hundred-page scans.
  • Forms and annotations come along with copyPages. If you need a flat, uneditable result, flatten form fields before saving.
  • Page sizes: mixed source sizes are preserved per page, which is usually what you want — don't "normalize" unless the user asks.

Why client-side wins here

PDFs are often sensitive — contracts, invoices, ID scans. The privacy argument writes itself: no upload means no transit interception, no server retention policy to trust, and it works offline once the page loads.

The same approach powers the Merge PDF and Compress PDF tools on ToolVero — free, no signup, files never leave your browser.

📰 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.