Merge and Split PDFs in JavaScript with pdf-lib

Zusammenfassung

Pixel shares a tutorial on using pdf-lib to merge and split PDFs entirely in the browser with vanilla JavaScript. It covers importing the library, reading files with arrayBuffer(), and combining pages in memory, helping developers avoid backend costs and protect sensitive documents.

DEV Community

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: Zero Server Uploads: Files are read via file.arrayBuffer() directly in local memory. Instant Execution: There is no network latency waiting for large files to upload and download. 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
Or import it directly via ES modules in a standalone HTML file: import { PDFDocument } from 'https://jsdelivr.net';
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;
}
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);
}
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');
}
Performance Tips for Production Apps Handle Encrypted PDFs Gracefully: By default, PDFDo...
Merge and Split PDFs in JavaScript with pdf-lib
Powered by Readybot.io

Das Neueste von Pixel

Incident Response: Look Beyond the Red Alert

Pixel’s DEV Community announcement explores how teams can fixate on one failing service while overlooking the real cause of an outage, such as a full …

Sach: AI Fact-Checks WhatsApp Forwards in India

Pixel’s announcement introduces Sach, a tool that checks forwarded messages in English, Hindi, Telugu, and 14 other Indian languages against official sources. It gives cited …

Java 25 Removes SecurityManager: What to Fix

Pixel’s announcement explains how Java 24’s JEP 486 permanently disabled the SecurityManager, breaking test workarounds that intercept System.exit. It recommends returning exit codes or throwing …