How to Remove Blank Pages from PDF with Python
Unwanted blank pages can appear when scanning, merging, or exporting PDFs. For example, duplex scanning may capture the empty backs of sheets, while document layouts can generate unnecessary blank pages. Finding and deleting these pages manually can be time-consuming. With Python, you can automate page detection and cleanup. However, a page that looks blank does not necessarily contain no…
Blank pages can occur during scanning, merging, or exporting PDFs. Manual removal is time-consuming. Python can automate detection and cleanup. However, a page that looks blank may still contain content like a white image or invisible text.
This article uses Spire.PDF for Python along with Pillow to check if PDF pages are blank and then remove them if they meet the criteria. The process involves installing the dependencies, preparing a test file with regular content, blank pages, and solid white pages, and then implementing the detection and removal steps.
Blank page detection works in two levels. First, the page's IsBlank() method checks for blankness. If it returns True, the page is removed directly. For pages not identified as blank, they are rendered as images using SaveAsImage() from Spire.PDF. Pillow then examines these images to see if every pixel is pure white. If so, the page is considered blank and removed.
The complete Python code loads a PDF file, detects and removes blank pages starting from the last page, and saves the result. Pages are removed in reverse order to avoid index shifting issues after each removal. If all pages are removed, the code skips saving to avoid creating a PDF with no pages.
The key parts of the code include checking for pure white pixels using RGB values in the is_blank_image() function, removing pages in reverse order, and handling cases where no pages remain. This automated approach helps efficiently clean up PDF documents containing unwanted blank pages.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.