DEV Community

toolnestlabs-create
toolnestlabs-create

Posted on

Merge and Split PDFs in JavaScript with pdf-lib

Merging and splitting PDFs is a common need, and you can do it in the browser or in Node with the open-source pdf-lib package. Here is a minimal approach.

Install

npm install pdf-lib
Enter fullscreen mode Exit fullscreen mode

Merge two PDFs

import { PDFDocument } from 'pdf-lib';

async function merge(bytesA, bytesB) {
  const out = await PDFDocument.create();
  for (const bytes of [bytesA, bytesB]) {
    const src = await PDFDocument.load(bytes);
    const pages = await out.copyPages(src, src.getPageIndices());
    pages.forEach(p => out.addPage(p));
  }
  return out.save();
}
Enter fullscreen mode Exit fullscreen mode

Extract pages (split)

async function extract(bytes, indices) {
  const src = await PDFDocument.load(bytes);
  const out = await PDFDocument.create();
  const pages = await out.copyPages(src, indices);
  pages.forEach(p => out.addPage(p));
  return out.save();
}
// extract(bytes, [0, 2, 3]) keeps pages 1, 3 and 4
Enter fullscreen mode Exit fullscreen mode

Things to watch

  • Page indices are zero-based.
  • Encrypted PDFs need ignoreEncryption or the password before they can be loaded.
  • Large files are processed in memory, so very big PDFs can be slow in a browser tab.

If you only need to do this once and do not want to write code, my PDF tools handle merging, splitting and converting in the browser.

Top comments (0)