A scanned PDF often has blank pages. Duplex scanners add them when the back of a sheet is empty. Checking for blank pages by hand is slow, and a page with no text is not always blank. This is how to detect them in code.
Two checks, not one
A digital PDF has a text layer. If a page has no text, it may be blank. But a scan has no text layer at all, because every page is a picture. A page with no text could be a photo, a stamp or a signature page.
So use two checks:
- Does the page have any text?
- If not, does the rendered page differ from white paper?
Python with PyMuPDF
import fitz # pip install pymupdf
def blank_pages(path, ink_limit=0.002):
doc = fitz.open(path)
blanks = []
for i, page in enumerate(doc):
if page.get_text().strip():
continue # has text, keep it
pix = page.get_pixmap(matrix=fitz.Matrix(0.5, 0.5),
colorspace=fitz.csGRAY)
px = pix.samples # one byte per pixel
dark = sum(1 for b in px if b < 200)
if dark / len(px) < ink_limit:
blanks.append(i)
return blanks
def remove(path, out):
doc = fitz.open(path)
blanks = set(blank_pages(path))
keep = [i for i in range(len(doc)) if i not in blanks]
doc.select(keep)
doc.save(out)
print(blank_pages("scan.pdf"))
Some details are worth knowing.
Render small. A half-size render is enough to tell a page with content from an empty one. It is much faster than full resolution.
Use grayscale. One byte per pixel makes the count simple.
Allow some noise. A scanned blank sheet is never pure white. It has dust, grain and a shadow near the edge. That is why the limit is a fraction (0.2% of pixels here) and not zero. If your scanner is noisy, raise the limit. If you lose pages that have a single line of text in an image, lower it.
What the limit trades off
A strict limit only catches pages that are truly empty. A loose limit also catches pages with a faint page number or a small mark. Start strict, print the page numbers it found, and look at them before you save a new file. Never overwrite the original.
Pages that look blank but are not
Dark pages are the usual trap. If a page is a solid black scan of the back of a dark cover, "differs from white" is true, so it is kept. The reverse case is a page with a very pale watermark. It can count as blank, which is often what you want.
If you do not want to write code
I run PDF Workshop, a free tool site. Its Remove Blank Pages tool does the same job. You upload the PDF and click Detect Blank Pages to see the page numbers. Then you click Remove Blank Pages and download a cleaned copy. It has a strictness setting, and you can see the list before anything is deleted. The file is sent to the server to be processed, so for private documents the script above, which runs locally, is the better choice.
Top comments (0)