DEV Community

How to Delete Pages from a PDF in the Browser with pdf-lib (No Upload)

Many online PDF tools send your file to a server before they remove a page. If the document is private (a contract, a bank statement, a scan of an ID), that is a bad trade.

You can remove pages entirely inside the browser, and the file never leaves the device. This post shows how to delete pages from a PDF with the open source library pdf-lib, and where the common mistakes are.

The idea

A PDF is a list of page objects. Deleting a page means removing one entry from that list and saving the file again. pdf-lib does this in memory, so nothing is uploaded.

Minimal example

import { PDFDocument } from "pdf-lib";

async function deletePages(arrayBuffer, pagesToDelete) {
  const pdf = await PDFDocument.load(arrayBuffer);
  // pdf-lib pages are 0-indexed. Delete from the end so indexes stay valid.
  const indexes = pagesToDelete.map(n => n - 1).sort((a, b) => b - a);
  for (const i of indexes) {
    if (i >= 0 && i < pdf.getPageCount()) pdf.removePage(i);
  }
  return await pdf.save(); // Uint8Array
}

Common mistakes

  • Deleting in ascending order. After you remove page 2, the old page 3 becomes page 2. Sort the indexes from highest to lowest, as above.
  • Off-by-one errors. Users think "page 1", pdf-lib thinks index 0.
  • Forgetting an empty result. A PDF must keep at least one page. Check pdf.getPageCount() before you save.
  • Large files. Loading a 200 MB file into memory can freeze a phone. Warn the user, or read it in a worker.

Wiring it to a file input

const input = document.querySelector("#file");
input.addEventListener("change", async () => {
  const file = input.files[0];
  const bytes = await deletePages(await file.arrayBuffer(), [2, 5]);
  const url = URL.createObjectURL(new Blob([bytes], { type: "application/pdf" }));
  const a = Object.assign(document.createElement("a"), { href: url, download: "edited.pdf" });
  a.click();
  URL.revokeObjectURL(url);
});

Always open the saved file and check the page order before you delete the original.

If you just want the result I keep a free tool built this way: you can delete pages from a PDF in your browser, choosing the pages to remove and saving a new file. (Disclosure: this tool is one of my own projects.)

Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.