How to Remove Pages from a PDF in JavaScript (pdf-lib Tutorial)
To remove pages from pdf javascript developers can build 100% client-side web applications using the MIT-licensed pdf-lib package. By loading the binary buffer into a PDFDocument, sorting the target indices in descending order, and calling pdfDoc.removePage(index), you can manipulate documents directly inside the user’s browser without transmitting a single byte over the network.
Step 1: Install the Dependency
Step 2: TypeScript Production Implementation
Below is the exact core logic pattern employed inside PageRemover:
import { PDFDocument } from 'pdf-lib';
export async function removePagesFromPdf(
pdfBytes: Uint8Array,
pagesToRemove0Based: number[]
): Promise<Uint8Array> {
// 1. Load the binary document into memory
const pdfDoc = await PDFDocument.load(pdfBytes, { ignoreEncryption: true });
const totalPages = pdfDoc.getPageCount();
// 2. Validate that user is not attempting to delete all pages
if (pagesToRemove0Based.length >= totalPages) {
throw new Error('Cannot delete all pages from the document.');
}
// 3. CRITICAL: Sort indices in descending order!
// Removing page 2 shifts old page 4 into index 3.
// Descending order prevents index corruption.
const sortedDescending = [...new Set(pagesToRemove0Based)].sort((a, b) => b - a);
for (const index of sortedDescending) {
if (index >= 0 && index < totalPages) {
pdfDoc.removePage(index);
}
}
// 4. Save and return modified binary bytes
return await pdfDoc.save();
}The Descending Index Gotcha (Why Order Matters)
The most common rookie mistake when pruning pages in a loop is deleting in ascending order:
Suppose you want to remove Page 1 (index 0) and Page 3 (index 2) from a 5-page document. If you delete index 0 first, all subsequent pages shift to the left: what was originally Page 3 now occupies index 1! If you then delete index 2, you accidentally delete what was originally Page 4!
By sorting your deletion targets in descending order (highest index to lowest), the indices of earlier pages remain completely unchanged as deletions occur.
Related Developer & Automation Guides
Explore tested document manipulation tutorials across other runtimes and tools:
Remove Pages via Python (pypdf Guide)
Learn how to automate PDF page deletion in Python using pypdf with in-memory BytesIO handling.
Remove Pages via Command Line (QPDF & Poppler)
Lightning-fast headless batch processing scripts for Linux and macOS server administration.
Empirical PDF Benchmark Study
Original latency and memory metrics comparing pure Python against client-side Web Workers and native C++.
Core PDF Page Remover (Tool)
Our primary client-side web utility for removing arbitrary pages from PDF files with visual thumbnails.
Frequently Asked Questions
Why is pdf-lib the premier choice for in-browser JavaScript PDF manipulation?
pdf-lib is written in pure TypeScript with zero native C++ or canvas dependencies, allowing it to execute seamlessly inside browser main threads, Web Workers, or Node.js without compilation overhead.
How do you delete a page using the PDFDocument API in pdf-lib?
Load the document using PDFDocument.load(bytes), call pdfDoc.removePage(pageIndex) where pageIndex is a 0-based integer, and call await pdfDoc.save() to generate the modified Uint8Array.
Why is moving pdf-lib operations into a Web Worker critical for frontend web apps?
Parsing multi-megabyte PDFs on the main browser thread causes JavaScript execution to block UI repaints, resulting in unresponsive scroll events and janky animations. Web Workers offload processing to a background thread.
What is the crucial indexing rule when removing multiple pages in a loop with pdf-lib?
When removing multiple pages, you must remove them in descending order (highest index first). If you remove lower indices first, subsequent page numbers shift left, causing your script to delete the wrong pages.
See this JavaScript engine in action
Experience the speed of our in-browser WebAssembly and Web Worker architecture on your own files.