How to Remove Pages from a PDF with Python (Tested pypdf Guide)
To remove pages from pdf python developers should use the modern pypdf library (the actively maintained successor to deprecated PyPDF2). By iterating over reader.pages and adding only desired indices to a PdfWriter instance, you can automate document sanitization in less than ten lines of clean, dependency-light code.
Step 1: Install the Maintained Library
Step 2: Production Python Script (File-Based)
Below is a tested, type-annotated Python script supporting individual indices and range exclusion:
from pypdf import PdfReader, PdfWriter
def remove_pages(input_path: str, output_path: str, pages_to_remove: list[int]):
"""
Removes specified 0-based page indices from a PDF file.
Example: remove_pages('contract.pdf', 'cleaned.pdf', [0, 2])
"""
reader = PdfReader(input_path)
writer = PdfWriter()
# Create a set for O(1) lookup
exclude_indices = set(pages_to_remove)
for idx, page in enumerate(reader.pages):
if idx not in exclude_indices:
writer.add_page(page)
with open(output_path, "wb") as output_file:
writer.write(output_file)
print(f"Successfully pruned {len(exclude_indices)} pages into {output_path}")
# Example execution: prune page 1 (idx 0) and page 4 (idx 3)
if __name__ == "__main__":
remove_pages("input.pdf", "output.pdf", [0, 3])Step 3: In-Memory Processing for Web APIs (FastAPI & Lambda)
In cloud microservices and serverless functions, writing to disk adds unnecessary disk latency and ephemeral storage limits. Use io.BytesIO for pure in-memory streaming:
import io
from pypdf import PdfReader, PdfWriter
def remove_pages_in_memory(pdf_bytes: bytes, pages_to_remove: list[int]) -> bytes:
"""
In-memory PDF page removal for web frameworks (FastAPI, Flask, AWS Lambda).
Accepts raw binary bytes, returns modified PDF bytes without disk I/O.
"""
reader = PdfReader(io.BytesIO(pdf_bytes))
writer = PdfWriter()
exclude = set(pages_to_remove)
for idx, page in enumerate(reader.pages):
if idx not in exclude:
writer.add_page(page)
output_stream = io.BytesIO()
writer.write(output_stream)
return output_stream.getvalue()Key Developer Gotchas in Python PDF Manipulation
- 0-Indexed Pages: Non-developers think in 1-based page counts. If your script exposes a CLI or web API, always subtract 1 from user input before filtering indices.
- Stream Lifetime: In Python,
PdfReaderlazy-loads binary objects. Do not close the underlying input file handle until afterwriter.write()finishes writing to disk. - Memory on Enormous Files: For multi-gigabyte engineering drawings, consider streaming via QPDF rather than pure Python parsing to avoid Python GIL memory overhead.
Related Developer & Automation Guides
Explore tested document manipulation tutorials across other runtimes and tools:
Remove Pages via JavaScript & Web Workers
In-browser zero-upload PDF manipulation using TypeScript and pdf-lib in modern WebAssembly browsers.
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 should developers use pypdf instead of PyPDF2 in modern Python projects?
The legacy PyPDF2 library was deprecated and officially merged back into pypdf (version 3.0+). The modern pypdf package offers major performance improvements, proper AES encryption support, and active bug fixes.
Are page indices in pypdf zero-based or one-based?
Like standard Python lists, pypdf uses 0-indexed page numbering. To delete the first physical page (Page 1), you target index 0. To delete page 5, you target index 4.
Does modifying a PDF with pypdf alter or re-encode embedded JPEG images?
No. pypdf performs object-level manipulation of the document catalog. Underlying image streams and vector fonts are copied directly to the new writer without transcoding or quality degradation.
How do I install pypdf in my Python virtual environment?
Run pip install pypdf in your terminal or add "pypdf>=4.0.0" to your requirements.txt or pyproject.toml configuration file.
Building in the browser with JavaScript instead?
Check out our tutorial on in-browser Web Worker PDF manipulation using TypeScript and pdf-lib.