
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 content. It may include a solid white image or invisible text. This article combines Spire.PDF for Python with Pillow to check whether PDF pages are blank, perform an additional check on rendered page images, and remove pages that meet the criteria.
1. Install the Dependencies and Prepare a File
This example uses two libraries:
- Spire.PDF for Python: Loads PDFs, detects blank pages, renders pages, and removes and saves pages.
- Pillow: Reads the rendered page images and examines their pixels.
Run the following command in your terminal:
pip install Spire.PDF Pillow
Prepare a file named Sample.pdf and place it in your Python script's working directory. To observe the results, you can include regular content pages, blank pages, and pages containing only a solid white image in the test file.
2. How Blank Page Detection Works
This example uses two levels of detection:
- Call the page's
IsBlank()method. If it returnsTrue, remove the page directly. - For pages not identified as blank, use
SaveAsImage()to render each page as an image. Then use Pillow to check whether every pixel is pure white. If so, remove that page as well.
This combined approach is also used in Spire.PDF's official blank page removal example. It can help identify some pages that contain page objects but appear entirely white when rendered.
One distinction is essential: the image check requires every pixel to be pure white; it does not detect pages that are merely “almost blank.” If the rendered image contains even one pixel that is not pure white, the image check will not classify the page as blank. Pages with gray backgrounds, scanning noise, or page numbers will therefore generally be retained.
3. Complete Code: Detect and Remove Blank Pages
The following code keeps both levels of detection and places the input and output paths together so you can easily change the files.
import io
from spire.pdf import PdfDocument
from PIL import Image
# Check whether every pixel in the image is pure white
def is_blank_image(image):
with image.convert("RGB") as rgb_image:
white_pixel = (255, 255, 255)
return all(
pixel == white_pixel
for pixel in rgb_image.getdata()
)
# 1. Set the input and output files
input_path = "Sample.pdf"
output_path = "RemoveBlankPages.pdf"
# 2. Load the PDF document
pdf = PdfDocument()
pdf.LoadFromFile(input_path)
original_page_count = pdf.Pages.Count
removed_page_numbers = []
# 3. Detect and remove blank pages, starting from the last page
for i in range(original_page_count - 1, -1, -1):
page = pdf.Pages.get_Item(i)
# First, use the PDF page's blank detection method
if page.IsBlank():
pdf.Pages.RemoveAt(i)
removed_page_numbers.append(i + 1)
continue
# For the remaining pages, render an image and check its pixels
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)
# 4. Save the result and close the document
remaining_page_count = pdf.Pages.Count
if remaining_page_count > 0:
pdf.SaveToFile(output_path)
pdf.Close()
# 5. Print processing information
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.")
If every page is removed, the code skips saving to avoid attempting to create a PDF with no pages. Using different filenames for the input and output also preserves the original document for comparison.
4. Understanding the Key Parts of the Code
4.1. Check for Pure White Using RGB Pixels
The is_blank_image() function first converts the image to RGB mode, then checks whether each pixel equals (255, 255, 255).
all() returns True only when every pixel meets this condition. It stops checking as soon as it encounters a non-white pixel. As a result, a pure white page requires checking every pixel, while a page containing visible content may finish the check earlier.
4.2. Why Remove Pages in Reverse Order?
PDF page indices start at 0. When a page is removed, the indices of subsequent pages shift down. If you iterate from the first page and delete pages as you go, you may skip the page immediately following a deleted page.
The code processes pages backward, starting from the last page:
for i in range(original_page_count - 1, -1, -1):
This ensures that removing the current page does not change the indices of earlier pages that have yet to be processed. It also makes it straightforward to record each removed page's original page number.
4.3. Does Rendering Affect the Pages That Are Retained?
The images in this example are used only for detection and are not written back into the PDF. The program removes blank pages directly from the original document's page collection and saves the remaining pages. It does not rebuild the entire document as an image-based PDF.
5. Scope and Considerations
Pure white detection works best for clean blank pages. Scanned “blank” pages often still contain gray backgrounds, paper texture, or dark specks, all of which cause the pixel check to return False. To handle these scans, you can introduce a near-white color threshold and a limit on the proportion of non-white pixels. However, these settings need to be tested with real samples to avoid misclassifying faint text or thin lines as blank.
A visually blank page may still contain useful data. Some pages may include hidden text, links, or interactive elements. Even if the rendered result is white, the page may still be worth retaining. When using visual detection, decide whether to remove such pages based on the document's intended use.
Rendering adds processing time. Pages for which IsBlank() returns True are removed directly; only the remaining pages undergo image detection. For PDFs with many pages or large page dimensions, rendering and pixel-by-pixel checking may take considerable time.
After running the script, check the output page count and the list of removed pages, paying particular attention to pages with faint content. If your environment has evaluation restrictions or evaluation watermarks, also verify whether they affect page rendering and detection results.
6. Conclusion
With Spire.PDF for Python and Pillow, you can remove blank PDF pages by combining page-level blank detection with a pure white check on rendered page images. Reverse iteration avoids index changes during deletion, while the strict pure white criterion clearly defines the scope of detection. Scanned blank pages containing noise require additional tolerance rules and testing to check for unintended deletions.
Top comments (0)