🚀 Remove Blank Pages from PDF with Python (2026) ⚡
Learn how to remove blank pages from PDF with Python using Spire.PDF for Python + Pillow. Automate cleanup with reliable page detection—get the script!

How to Remove Blank Pages from a PDF with Python Without Losing Content
Blank pages are easy to miss in a long PDF, and removing them by hand quickly turns into a tedious routine. They often show up after duplex scanning (the scanner captures empty backs of sheets) or when a document export inserts an extra page.
Python can automate the cleanup - but the tricky part is deciding what "blank" really means. A page that looks empty may still have an invisible text layer, a white image, scan noise, or a small page number. If you remove every page that doesn't show obvious text, you can accidentally delete something you meant to keep.
This guide uses Spire.PDF for Python to inspect and remove pages, with Pillow as a second check on rendered page images. You'll get a complete script, a clear explanation of why it processes pages in reverse, and an honest look at what strict "white pixel" detection catches - and what it misses. The goal is a repeatable workflow, not a black box that silently changes important documents.
How should a script decide whether a PDF page is blank?
A PDF page can be "empty" in a few different ways. It might have no meaningful page objects, or it might contain objects that don't produce visible output. It can also look blank to a person while still holding information that matters later in the workflow. The right definition depends on what you're doing.
Structural blankness and visual blankness
A PDF can include text, vector shapes, images, annotations, links, and other elements. Some of those may be invisible or effectively "white on white." A structural check can flag pages the PDF library considers blank, but it won't catch every page that renders as empty.
A visual check asks a different question: what does the page actually look like when rendered? In this guide, the script renders the page and checks whether every pixel is pure white. This helps catch pages that contain PDF objects but still look empty in the rendered output.
Neither definition is universally "correct." If you're cleaning scanned handouts for printing, a page that renders as solid white is often safe to remove. If you're preserving legal, financial, or archival records, hidden text, annotations, or links can matter even when the page looks empty. So the removal rule should match the document's purpose.
Why use two checks?
The script starts with Spire.PDF's IsBlank() method. If it returns True, the page is removed immediately - no rendering needed.
For pages that pass that check, the script renders the page and then uses Pillow to examine the pixel data. This second step adds coverage for cases where the PDF library doesn't classify the page as blank, but the rendered result is still effectively empty.
The pixel rule is intentionally strict: every pixel must be exactly (255, 255, 255). One gray pixel - scan noise, a thin line, a page number - is enough to keep the page. That's easy to reason about, but it also means many real scans (especially duplex scans with tiny imperfections) won't qualify as blank.
Before you run this on a large set, test it on representative PDFs. Include pages with faint marks, colored backgrounds, page numbers, and any hidden or interactive content you've seen in your source files. Decide what the script is allowed to remove before you decide how aggressive to be.
How do you remove blank PDF pages with Python?
This example uses Spire.PDF for Python to load, inspect, render, and edit the PDF. Pillow reads the rendered images. Install both packages:
pip install Spire.PDF Pillow
Put a test file named Sample.pdf in the script's working directory (or update input_path). Use a separate output filename so you can compare against the original. A good test PDF should include normal content pages, truly empty pages, and "borderline" pages you expect to be tricky in production.
Complete script
import io
from spire.pdf import PdfDocument
from PIL import Image
def is_blank_image(image):
"""Return True only when every rendered pixel is pure white."""
with image.convert("RGB") as rgb_image:
white_pixel = (255, 255, 255)
return all(
pixel == white_pixel
for pixel in rgb_image.getdata()
)
input_path = "Sample.pdf"
output_path = "RemoveBlankPages.pdf"
pdf = PdfDocument()
pdf.LoadFromFile(input_path)
original_page_count = pdf.Pages.Count
removed_page_numbers = []
# Iterate backward so removing a page does not shift pending indices.
for i in range(original_page_count - 1, -1, -1):
page = pdf.Pages.get_Item(i)
if page.IsBlank():
pdf.Pages.RemoveAt(i)
removed_page_numbers.append(i + 1)
continue
with pdf.SaveAsImage(i) as image_data:
image_bytes = image_data.ToArray()
with io.BytesIO(image_bytes) as image_stream:
with Image.open(image_stream) as image:
if is_blank_image(image):
pdf.Pages.RemoveAt(i)
removed_page_numbers.append(i + 1)
remaining_page_count = pdf.Pages.Count
if remaining_page_count > 0:
pdf.SaveToFile(output_path)
pdf.Close()
removed_page_numbers.sort()
print(f"Original page count: {original_page_count}")
print(f"Pages removed: {len(removed_page_numbers)}")
print(f"Original page numbers removed: {removed_page_numbers}")
if remaining_page_count > 0:
print(f"Result saved to: {output_path}")
else:
print("No pages remain. The output file was not saved.")
The printed page numbers are one-based (matching what most PDF viewers show). The index used internally by the PDF library is zero-based.
The script also skips saving if everything got removed. That prevents an attempt to write an output PDF with zero pages. And it leaves the original file untouched because it writes to a different path. In a real workflow, keep that separation until you're confident in the output.
What the script does not do
This script doesn't convert kept PDF pages into images. It uses rendering only to detect blanks. The remaining pages stay as real PDF pages, and the final result is saved as a PDF - so you keep things like searchable text when it exists in the original.
It's a practical starting point, not a full "PDF cleanup service." If you're running this over a folder or in a user-facing app, add the surrounding pieces you need: input validation, error handling, logging, and a clear policy for what happens when a file can't be opened or saved. Also make sure you test the library version and any licensing/evaluation constraints in your environment.
Why does the script render pages and delete them in reverse?
There are two details here that prevent common mistakes: it renders only when the structural check isn't decisive, and it deletes pages starting from the end of the document. Together, they keep the behavior predictable.
Why remove pages from the end first?
PDF page indices start at zero. If you remove a page while iterating forward, everything after that page shifts down by one index. That can make the loop skip a page or check the wrong one.
For example, imagine pages at indices 1 and 2 are blank. If you remove index 1 first, the original page at index 2 slides into index 1. If your loop then moves on to index 2, it might never examine that shifted page.
Iterating backward avoids this. Deleting a later page doesn't affect the indices of earlier pages that you haven't checked yet.
The loop starts at original_page_count - 1 and counts down to zero. It records i + 1 for display so you can review original page numbers, not positions in the shortened PDF.
How does the pixel check work?
is_blank_image() converts the rendered image to RGB, then checks each pixel against (255, 255, 255). Python's all() returns True only if every pixel matches. It also stops as soon as it finds a non-white pixel, so pages with visible content can fail quickly. A "perfectly white" result requires inspecting every pixel.
This strictness is useful because it doesn't make guesses about whether faint marks are meaningful. But it also doesn't interpret content. A single stray pixel keeps the page, even if it's just dust or noise. And a page that looks blank to you could still carry hidden PDF information that the image-based check won't see.
What happens to retained pages?
The rendered image is used only for inspection. When a page is removed, it's removed from the PDF document's page collection and the remaining document is saved.
So while the script does render images, it doesn't intentionally "flatten" the retained pages into bitmaps. Still, don't treat a successful save as proof the output is correct for your use case. Check the remaining page count, open the PDF, and inspect pages around each removal. If your workflow depends on annotations, forms, bookmarks, or accessibility features, verify those too.
What are the limits of automatic blank-page removal?
Pure-white detection works best when blank pages are truly clean. Real scans are rarely that tidy. Paper texture, gray backgrounds, dust, compression artifacts, or a tiny mark can cause a page to fail the exact pixel test. The script will keep that page - even if a human would call it blank.
Should you use a near-white threshold?
You can make the image check more tolerant by treating pixels "close to white" as white, then removing a page only when the share of non-white pixels stays under a chosen limit. That can help with scanner noise and slightly gray backgrounds.
But it introduces a trade-off: faint ink, thin lines, low-contrast text, or a subtle signature could fall inside the tolerance and get removed.
There's no universally safe threshold. The best approach is to gather real sample PDFs, label the pages that should be kept, and test candidate thresholds against those examples. When results are borderline, keep them for human review rather than silently widening the rule until the output looks clean "in general."
If you do tune detection, treat it like a classification policy - not a cosmetic change. Record the threshold and the test set you used, and rerun the checks when the input source or rendering settings change. A rule that works for one batch of office scans may behave differently on mixed documents.
Can a page look blank but still contain useful information?
Yes. A page can render as white while still containing hidden text, links, annotations, or interactive elements. Removing it based only on what it looks like can drop information you can't see in a typical viewer.
This matters most when PDFs are records, evidence, forms, or documents that other systems process. In those cases, "visually blank" usually shouldn't be the only signal. If losing information is high risk, generate a candidate list for review or use a more conservative approach that removes only pages you can confidently verify with your trusted checks.
How much does rendering cost?
Rendering and inspecting images adds time. The script avoids that cost for pages where IsBlank() already returns True, but it still renders every page that makes it past the first check.
On large PDFs, or PDFs where each page renders at high resolution, this can take longer and use more memory. If runtime matters, test the script on representative files before running it at scale. Track per-file counts and durations so you can spot unusually slow inputs. And don't loosen detection rules just to speed things up unless you've confirmed the script still separates real blank pages from faint content.
Key takeaways
- Check blankness at the PDF level first, then render remaining pages for a visual check.
- Remove a page only when
IsBlank()returnsTrueor every rendered pixel is pure white. - Iterate backward to avoid page-index shifts, and report original page numbers for review.
- Exact white-pixel detection can miss noisy "blank" pages; tolerance changes can also remove faint content.
- Keep the original file, inspect the output, and choose a removal policy based on what the document is for.
Conclusion
Python can remove blank PDF pages in a repeatable way, but the result depends on how you define "blank." Using Spire.PDF's page-level check plus Pillow's strict rendered-image check catches more cases than either method alone, and deleting pages in reverse avoids index mistakes.
The pure-white rule is conservative for noisy scans - and risky for visually blank pages that still contain hidden information. Keep the original file, test on representative documents, and review borderline results. For unattended processing, automate only what your policy can classify with confidence, and route everything else to review.