DEV Community

Ryoma
Ryoma

Posted on

How to Merge and Split PDFs 100% Client-Side in JavaScript with pdf-lib

Handling PDF files on the web used to require spinning up a backend server with Python, Ghostscript, or headless Chrome. That meant paying for compute, handling temporary file cleanup, and asking users to upload sensitive documents—like contracts or bank statements—to an external server.

With modern browser APIs and pdf-lib, you can read, merge, split, and generate PDF binary arrays completely inside the user's browser with zero backend infrastructure.

In this tutorial, we will walk through how pdf-lib works under the hood and build a working client-side PDF merger in vanilla JavaScript.


Why pdf-lib Works So Well in the Browser

Unlike older libraries that only create new PDFs from scratch, pdf-lib parses and modifies existing PDF document structures directly in JavaScript using Uint8Array and ArrayBuffer objects.

Because it relies purely on standard JavaScript typed arrays:

  1. Zero Server Uploads: Files are read via file.arrayBuffer() directly in local memory.
  2. Instant Execution: There is no network latency waiting for large files to upload and download.
  3. Complete Privacy: Closing the browser tab wipes the binary buffers from RAM.

Step 1: Installing or Importing pdf-lib

If you are using a bundler like Vite or Next.js, install it via npm:

npm install pdf-lib
Enter fullscreen mode Exit fullscreen mode

Or import it directly via ES modules in a standalone HTML file:

import { PDFDocument } from 'https://jsdelivr.net';
Enter fullscreen mode Exit fullscreen mode

Step 2: Merging Multiple PDFs in Browser Memory

To merge multiple user-selected PDF files, we create an empty target PDFDocument, loop through each uploaded File object, load its ArrayBuffer, copy its pages over, and serialize the final bytes.

import { PDFDocument } from 'pdf-lib';

async function mergePdfFiles(fileList) {
  // 1. Create a brand-new empty PDF document
  const mergedPdf = await PDFDocument.create();

  for (const file of fileList) {
    // 2. Read the local file into an ArrayBuffer (no server upload)
    const arrayBuffer = await file.arrayBuffer();

    // 3. Load the source PDF
    const sourcePdf = await PDFDocument.load(arrayBuffer);

    // 4. Copy all page indices from the source into the target PDF
    const pageIndices = sourcePdf.getPageIndices();
    const copiedPages = await mergedPdf.copyPages(sourcePdf, pageIndices);

    copiedPages.forEach((page) => {
      mergedPdf.addPage(page);
    });
  }

  // 5. Serialize the merged document into a Uint8Array
  const mergedPdfBytes = await mergedPdf.save();
  return mergedPdfBytes;
}
Enter fullscreen mode Exit fullscreen mode

Step 3: Triggering a Local File Download

Once you have mergedPdfBytes, wrap it in a Blob and trigger a browser download using URL.createObjectURL():

function downloadPdf(pdfBytes, filename = 'merged.pdf') {
  const blob = new Blob([pdfBytes], { type: 'application/pdf' });
  const url = URL.createObjectURL(blob);

  const link = document.createElement('a');
  link.href = url;
  link.download = filename;
  document.body.appendChild(link);
  link.click();

  // Clean up memory immediately
  document.body.removeChild(link);
  URL.revokeObjectURL(url);
}
Enter fullscreen mode Exit fullscreen mode

If you want to see how this exact PDFDocument pipeline behaves in production with drag-and-drop file ordering, you can test a live implementation on Unir PDF.


Bonus: Extracting Specific Pages (Splitting a PDF)

The exact same copyPages() method makes splitting or extracting specific pages trivial. Instead of passing sourcePdf.getPageIndices(), pass an array of zero-based page numbers (for example, [0, 2] to extract pages 1 and 3):

async function extractPages(file, zeroBasedPageNumbers) {
  const arrayBuffer = await file.arrayBuffer();
  const sourcePdf = await PDFDocument.load(arrayBuffer);

  const outputPdf = await PDFDocument.create();
  const copiedPages = await outputPdf.copyPages(sourcePdf, zeroBasedPageNumbers);

  copiedPages.forEach((page) => outputPdf.addPage(page));

  const outputBytes = await outputPdf.save();
  downloadPdf(outputBytes, 'extracted-pages.pdf');
}
Enter fullscreen mode Exit fullscreen mode

Performance Tips for Production Apps

  • Handle Encrypted PDFs Gracefully: By default, PDFDocument.load() throws an error if a user drops a password-protected PDF. Wrap load() in a try/catch block and show a clear message asking the user to unlock the file first.
  • Revoke Object URLs: Always call URL.revokeObjectURL(url) after triggering the download so large PDF blobs do not linger in browser memory.
  • Pair with pdf.js for Thumbnails: Since pdf-lib focuses on binary structure rather than visual rendering, pair it with Mozilla's pdf.js if you want to draw page previews onto <canvas> elements—an approach used in browser utilities like Compressor de PDF and multi-tool suites on Liora Tools.

Have you replaced any backend file-processing endpoints with client-side JavaScript or WebAssembly recently? Share what libraries worked best for you in the comments!

Top comments (0)