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

Merge PDF files in the browser with pdf-lib (no server needed)

Job and bank forms often ask for all your documents in one PDF. You can merge PDF files directly in the browser with the open source library pdf-lib, so the files never have to be uploaded to a server. This post shows th

Job and bank forms often ask for all your documents in one PDF. You can merge PDF files directly in the browser with the open source library pdf-lib, so the files never have to be uploaded to a server. This post shows the core idea.

Install

npm install pdf-lib

Merge several PDFs

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

  return await merged.save(); // Uint8Array
}

The order of the files array decides the order of the pages, so sort it before you call the function.

Download the result

function download(bytes, name) {
  const blob = new Blob([bytes], { type: "application/pdf" });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = name;
  a.click();
  URL.revokeObjectURL(url);
}

Things to watch

  • Encrypted PDFs: a file protected by a password cannot be loaded as is. Ask the user to unlock it first.
  • Memory: every file is read fully into memory, so a merge of very large files can be slow on a phone. Show a progress message.
  • File size: merging does not shrink anything. If a form has a size limit, compress the scans before you merge them, for example by scanning at a lower DPI.
  • Order: let people reorder files before merging. A wrong page order is the most common complaint.

Disclosure: I work on PixelKaro, a set of free browser-based image and PDF tools (https://pixelkaro.com) that process files on your device. The code above is a simplified example of the general approach.

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