DEV Community

Azqora Tech
Azqora Tech

Posted on

Split a PDF by page ranges in the browser with pdf-lib

Splitting a PDF does not need a server. With pdf-lib you can pull any pages out of a file, entirely in the browser, and hand the result back as a download. Here is a small version that accepts ranges like 1-3,5,8-10.

Step 1: turn a range string into page numbers

Users think in 1-based page numbers, so validate them before touching the PDF:

function parseRanges(text, pageCount) {
  const result = [];
  for (const part of text.split(',')) {
    const [startRaw, endRaw] = part.trim().split('-');
    const start = Number(startRaw);
    const end = endRaw === undefined ? start : Number(endRaw);

    if (
      !Number.isInteger(start) ||
      !Number.isInteger(end) ||
      start < 1 ||
      end < start ||
      end > pageCount
    ) {
      throw new Error(`Bad range: "${part.trim()}"`);
    }
    for (let n = start; n <= end; n++) result.push(n);
  }
  return result;
}
Enter fullscreen mode Exit fullscreen mode

Step 2: copy those pages into a new document

pdf-lib works by creating a new document and copying pages from the source into it:

import { PDFDocument } from 'pdf-lib';

async function extractPages(file, rangeText) {
  const bytes = await file.arrayBuffer();
  const src = await PDFDocument.load(bytes);

  const pageNumbers = parseRanges(rangeText, src.getPageCount());
  const out = await PDFDocument.create();

  // copyPages expects 0-based indices
  const copied = await out.copyPages(src, pageNumbers.map((n) => n - 1));
  copied.forEach((page) => out.addPage(page));

  return out.save(); // Uint8Array
}
Enter fullscreen mode Exit fullscreen mode

Step 3: offer the result as a download

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

// Usage with <input type="file" id="pdf"> and <input id="ranges">
document.getElementById('pdf').addEventListener('change', async (e) => {
  const file = e.target.files[0];
  const ranges = document.getElementById('ranges').value || '1';
  try {
    const bytes = await extractPages(file, ranges);
    download(bytes, 'split.pdf');
  } catch (err) {
    alert(err.message);
  }
});
Enter fullscreen mode Exit fullscreen mode

Things that will bite you

  • Encrypted PDFs. pdf-lib cannot decrypt a password-protected file, so PDFDocument.load throws. Catch it and tell the user the file needs to be unlocked first, instead of showing a raw stack trace.
  • You are building a new document. Page content comes across, but document-level extras such as bookmarks do not, so do not promise that a split file is identical to the original.
  • Large files use a lot of memory. The whole file is read into memory. For big PDFs, move the work into a Web Worker so the page does not freeze.
  • Repeated pages are allowed. Passing 1,1,1 copies page 1 three times. That is useful for some cases, so decide whether to deduplicate.
  • Validate before loading. Reject empty input and out-of-range pages with a clear message. Most "it did nothing" reports come from a silent bad range.

If you just need the result

I made PixelKaro, a set of free image and PDF tools that run in the browser, including splitting and merging PDFs, with no sign-up: https://pixelkaro.com

If you build your own, test with a few real files first: scanned PDFs, very large PDFs, and PDFs with form fields all behave differently.

Top comments (0)