Recovering original documents from a concatenated PDF (especially scanned ones) is a common but challenging problem because PDFs don't inherently store "document boundaries" like a logical file system. You need a way to detect a separator or a distinctive start/end pattern between the original documents.
Here are the most common strategies, from simplest to most complex:
Strategies to Detect Document Boundaries:
- Blank Pages: If the concatenation process inserted a completely blank page between each original document, this is the easiest to detect.
- Specific Separator Pages: If there were pages with a specific text (e.g., "END OF DOCUMENT X", "NEW RECORD"), a specific barcode, or a specific image pattern.
- Metadata Changes (Less Likely for Scans): If the original documents were not scanned, they might have page-level metadata that changes at boundaries. Highly unlikely for scanned PDFs simply concatenated.
- Content Analysis (More Complex, Requires OCR for Scans):
- First Page Identification: Each original document might start with a specific title, logo, or standard header/footer.
- Page Count (Fixed): If you know each original document was exactly N pages long, you can split by N pages. (Rare for arbitrary scanned documents).
- Visual Differences: A sudden change in page orientation, size, or general "look and feel" might indicate a new document. (Hard to automate reliably).
Recommended Python Libraries:
- PyMuPDF (fitz): Excellent for fast PDF processing, page rendering to images, text extraction (if OCR'd), and creating new PDFs. It's often the go-to for performance and versatility.
- Pillow (PIL): For image processing (e.g., analyzing rendered pages for blankness).
- Tesseract OCR (
pytesseract): If you need to perform OCR on scanned pages to detect text patterns (e.g., "Invoice #", "Document Start").
Solution Implementation (Focus on Blank Page Detection)
This is the most common and generally reliable method if your concatenated PDF has blank pages separating the documents.
Assumptions:
- There's at least one blank page between each original document.
- The first document starts on page 0 (or page 1 if you prefer 1-based indexing).
- A "blank" page has very few non-white pixels.
Steps:
- Open the large PDF.
- Iterate through each page.
- For each page, render it to an image.
- Analyze the image to determine if it's "blank" (or a separator).
- If a blank page is detected, it signifies the end of the previous document and the start of a new one. Save the accumulated pages.
- Accumulate pages into temporary lists until a separator is found.
- Save the last document after the loop finishes.
import fitz # PyMuPDF
from PIL import Image
import os
import numpy as np
def is_blank_page(page, pix_threshold=100, variance_threshold=50):
"""
Checks if a PDF page is likely blank.
Renders the page to an image and analyzes pixel data.
Args:
page (fitz.Page): The PyMuPDF page object.
pix_threshold (int): Maximum number of non-white pixels allowed for a page to be considered blank.
(Adjust this based on your scans - sometimes tiny dust specs appear).
variance_threshold (int): Maximum variance in pixel values allowed.
A truly blank page will have very low variance.
Returns:
bool: True if the page is considered blank, False otherwise.
"""
try:
# Render page to a pixmap (image)
# Use a lower DPI for faster processing if high resolution isn't needed for blank detection
pix = page.get_pixmap(matrix=fitz.Matrix(1, 1)) # Low resolution for quick check
# Convert pixmap to PIL Image
img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
# Convert to grayscale for simpler analysis
gray_img = img.convert('L')
# Convert to numpy array
np_img = np.array(gray_img)
# Check for near-white pixels (assuming white is 255 in grayscale)
# Count pixels that are significantly darker than white (e.g., < 240)
non_white_pixels = np.sum(np_img < 240) # Adjust 240 based on what you consider "non-white"
# Calculate variance to check for uniformity (a truly blank page is uniform)
# Skip variance calculation if there are many non-white pixels (not blank anyway)
variance = np.var(np_img) if non_white_pixels < pix_threshold else float('inf')
# Criteria for blank page
# 1. Very few non-white pixels
# 2. Very low pixel variance (uniformity)
return non_white_pixels < pix_threshold and variance < variance_threshold
except Exception as e:
print(f"Error checking page {page.number} for blankness: {e}")
return False # Assume not blank if an error occurs
def recover_documents(input_pdf_path, output_dir="recovered_docs",
blank_page_check_params=None,
start_doc_keywords=None,
start_doc_page_size_threshold=None):
"""
Recovers original documents from a concatenated PDF.
Args:
input_pdf_path (str): Path to the large concatenated PDF file.
output_dir (str): Directory to save the recovered documents.
blank_page_check_params (dict): Parameters for blank page detection
(e.g., {'pix_threshold': 100, 'variance_threshold': 50}).
If None, blank page detection is skipped.
start_doc_keywords (list): List of keywords/phrases that indicate the start of a new document.
(Requires OCR for scanned PDFs).
If None, keyword detection is skipped.
start_doc_page_size_threshold (tuple): (width_diff_threshold, height_diff_threshold).
If the current page size differs from the previous
document's common page size by more than these thresholds,
it suggests a new document. (e.g., (10, 10) in points).
Only effective if blank/keyword detection is off.
"""
if blank_page_check_params is None:
blank_page_check_params = {'pix_threshold': 100, 'variance_threshold': 50}
if not os.path.exists(output_dir):
os.makedirs(output_dir)
try:
doc = fitz.open(input_pdf_path)
except Exception as e:
print(f"Error opening PDF {input_pdf_path}: {e}")
return
current_document_pages = []
document_count = 0
# Store the average page size of the current document for size change detection
current_doc_avg_page_size = None
print(f"Starting document recovery from {input_pdf_path}...")
for page_num in range(doc.page_count):
page = doc[page_num]
is_separator = False
# --- Strategy 1: Blank Page Detection ---
if blank_page_check_params and is_blank_page(page, **blank_page_check_params):
is_separator = True
print(f" Page {page_num + 1} detected as BLANK/SEPARATOR.")
# --- Strategy 2: Keyword Detection (requires OCR for scanned PDFs) ---
# This part is more complex for scanned PDFs as it requires OCR first.
# For demonstration, we'll show how you'd use extracted text.
# You'd need to integrate a library like pytesseract here.
# For simplicity, if text is directly extractable, it's faster.
if start_doc_keywords and not is_separator:
try:
# If it's a scanned PDF, you'd need to OCR the page image here.
# text = pytesseract.image_to_string(Image.frombytes("RGB", [page.get_pixmap().width, page.get_pixmap().height], page.get_pixmap().samples))
# For non-scanned PDFs, you can directly extract text:
text = page.get_text("text")
if any(keyword.lower() in text.lower() for keyword in start_doc_keywords):
is_separator = True
print(f" Page {page_num + 1} detected as START OF NEW DOCUMENT by KEYWORD.")
except Exception as e:
print(f" Error during keyword detection on page {page_num + 1}: {e}")
# --- Strategy 3: Page Size Change Detection ---
if start_doc_page_size_threshold and not is_separator:
current_page_rect = page.rect
current_page_width = current_page_rect.width
current_page_height = current_page_rect.height
if current_doc_avg_page_size:
avg_width, avg_height = current_doc_avg_page_size
width_diff = abs(current_page_width - avg_width)
height_diff = abs(current_page_height - avg_height)
if width_diff > start_doc_page_size_threshold[0] or \
height_diff > start_doc_page_size_threshold[1]:
is_separator = True
print(f" Page {page_num + 1} detected as START OF NEW DOCUMENT by PAGE SIZE CHANGE.")
# Update average page size for the current document
# This is a simplification; a more robust solution might track all pages in a document
# and recalculate avg, or only set after a few pages are accumulated.
if not current_doc_avg_page_size or not is_separator:
current_doc_avg_page_size = (current_page_width, current_page_height)
else: # If it's a separator, reset for the next document
current_doc_avg_page_size = (current_page_width, current_page_height)
# --- Logic for splitting documents ---
if is_separator and current_document_pages:
# If we found a separator and have pages accumulated for the previous document
document_count += 1
output_pdf_path = os.path.join(output_dir, f"document_{document_count:03d}.pdf")
new_doc = fitz.open()
for p_idx in current_document_pages:
new_doc.insert_pdf(doc, from_page=p_idx, to_page=p_idx)
try:
new_doc.save(output_pdf_path)
print(f" Saved document {document_count} with {len(current_document_pages)} pages to {output_pdf_path}")
except Exception as save_e:
print(f" Error saving document {document_count}: {save_e}")
finally:
new_doc.close() # Important to close to release memory
current_document_pages = [] # Reset for the next document
# If the separator page itself is part of the *next* document (e.g., a "cover page" for the next document),
# add it to the new document's pages.
# Otherwise, if the separator is truly just a divider, skip adding it.
# For blank pages, we usually skip them. For keyword pages, you might include them.
if not blank_page_check_params or not is_blank_page(page, **blank_page_check_params): # If not a blank page
current_document_pages.append(page_num) # Add the current page (which was the separator) to the new doc
# If blank pages are the separators, we skip adding them to any document
# and the first page of the new document will be the one *after* the blank page.
else:
# Add the current page to the list of pages for the current document
current_document_pages.append(page_num)
# Save the last accumulated document (after the loop finishes)
if current_document_pages:
document_count += 1
output_pdf_path = os.path.join(output_dir, f"document_{document_count:03d}.pdf")
new_doc = fitz.open()
for p_idx in current_document_pages:
new_doc.insert_pdf(doc, from_page=p_idx, to_page=p_idx)
try:
new_doc.save(output_pdf_path)
print(f" Saved document {document_count} with {len(current_document_pages)} pages to {output_pdf_path}")
except Exception as save_e:
print(f" Error saving final document {document_count}: {save_e}")
finally:
new_doc.close()
doc.close()
print("Document recovery complete.")
# --- Example Usage ---
if __name__ == "__main__":
# Create a dummy large PDF for testing (replace with your actual file)
# This example creates a PDF with 3 documents separated by blank pages.
# Doc1 (2 pages) -> Blank -> Doc2 (3 pages) -> Blank -> Doc3 (1 page)
dummy_input_pdf = "large_concatenated_scanned_docs.pdf"
# Create a dummy PDF with PyMuPDF
dummy_doc = fitz.open()
dummy_doc.new_page(width=612, height=792) # Page 1: Doc 1
dummy_doc.new_page(width=612, height=792) # Page 2: Doc 1
dummy_doc.new_page(width=612, height=792) # Page 3: Blank separator (will be empty)
dummy_doc.new_page(width=612, height=792) # Page 4: Doc 2
dummy_doc.new_page(width=612, height=792) # Page 5: Doc 2
dummy_doc.new_page(width=612, height=792) # Page 6: Doc 2
dummy_doc.new_page(width=612, height=792) # Page 7: Blank separator
dummy_doc.new_page(width=612, height=792) # Page 8: Doc 3
# Add some text to make them "documents" (optional)
dummy_doc[0].insert_text((50, 50), "Document 1 - Page 1", fontname="helv", fontsize=20)
dummy_doc[1].insert_text((50, 50), "Document 1 - Page 2", fontname="helv", fontsize=20)
dummy_doc[3].insert_text((50, 50), "Document 2 - Page 1", fontname="helv", fontsize=20)
dummy_doc[4].insert_text((50, 50), "Document 2 - Page 2", fontname="helv", fontsize=20)
dummy_doc[5].insert_text((50, 50), "Document 2 - Page 3", fontname="helv", fontsize=20)
dummy_doc[7].insert_text((50, 50), "Document 3 - Page 1", fontname="helv", fontsize=20)
# Simulate a "scanned" document by adding a small, nearly invisible speck on the blank pages
# This is to test the robustness of `is_blank_page` with `pix_threshold`
# You might need to adjust pix_threshold based on your actual scanned blanks
dummy_doc[2].insert_text((10, 10), ".", fontname="helv", fontsize=1) # Tiny dot
dummy_doc[6].insert_text((10, 10), ".", fontname="helv", fontsize=1) # Tiny dot
dummy_doc.save(dummy_input_pdf)
dummy_doc.close()
print(f"Created dummy PDF: {dummy_input_pdf}")
# --- Run the recovery using blank page detection ---
print("\n--- Running with Blank Page Detection ---")
recover_documents(
dummy_input_pdf,
output_dir="recovered_docs_by_blank_page",
blank_page_check_params={'pix_threshold': 20, 'variance_threshold': 10} # Adjust these thresholds!
# Lower pix_threshold for purer blanks
# Higher for slightly imperfect blanks
# Lower variance for very uniform blanks
)
# --- Example with Keyword Detection (if pages were searchable or OCR'd) ---
# For a real scanned PDF, you'd need to install and configure Tesseract OCR
# and use `pytesseract.image_to_string()`
# from PIL import Image
# import pytesseract
# You'd modify the `recover_documents` function to perform OCR
# print("\n--- Running with Keyword Detection (requires OCR for scans) ---")
# recover_documents(
# dummy_input_pdf,
# output_dir="recovered_docs_by_keyword",
# blank_page_check_params=None, # Disable blank page detection for this test
# start_doc_keywords=["Document 1", "Document 2", "Document 3"]
# )
# --- Example with Page Size Change (less common for concatenated scans) ---
# print("\n--- Running with Page Size Change Detection ---")
# You would need a PDF with varying page sizes for this to work.
# recover_documents(
# dummy_input_pdf, # This dummy PDF won't trigger size changes
# output_dir="recovered_docs_by_size_change",
# blank_page_check_params=None,
# start_doc_page_size_threshold=(5, 5) # 5 points difference in width/height
# )
# Clean up dummy PDF
# os.remove(dummy_input_pdf)
Explanation and Refinements:
is_blank_page(page, pix_threshold, variance_threshold):
- This is the core of the blank page detection.
- It renders the PDF page to a
pixmap (PyMuPDF's image object).
- Converts it to a
Pillow image, then to a NumPy array for efficient pixel manipulation.
non_white_pixels = np.sum(np_img < 240): Counts pixels that are significantly darker than pure white (255). You might need to adjust 240 based on how "clean" your scanned blanks are. A value like 250 means only very dark pixels are counted.
variance = np.var(np_img): Calculates the statistical variance of the pixel values. A truly blank page will have a variance very close to 0. A higher variance means more visual "noise" or content.
- The
pix_threshold and variance_threshold are crucial. You'll need to experiment with these values for your specific scanned documents. Too low, and a slightly dusty blank page might not be detected. Too high, and a page with minimal content might be considered blank.
recover_documents() Function:
- Iterates through each page of the input PDF.
- Maintains
current_document_pages to accumulate page numbers belonging to the same logical document.
- When
is_separator is True and current_document_pages is not empty, it means a document has ended. A new PDF is created using fitz.open() and insert_pdf() to add the accumulated pages.
- The separator page itself is usually not included in the output document.
- Handles saving the very last document after the loop finishes.
- Strategies beyond Blank Pages (Commented in code):
- Keyword Detection: For scanned PDFs, this requires a full OCR step (
pytesseract.image_to_string()). This adds significant processing time and can be error-prone, but it's an option if no blank pages are present.
- Page Size Change: Less common for scanned documents that are simply concatenated, but useful if different original documents had different dimensions (e.g., invoices mixed with letter-sized reports).
Performance Considerations for Large Files:
- Memory: Rendering each page to an image (
get_pixmap()) can consume a lot of memory, especially for high-resolution scans.
fitz.Matrix(1, 1): Reduces the resolution for blank page detection, saving memory and speeding up get_pixmap(). Adjust if your blank pages have very subtle marks that high-res is needed to detect.
new_doc.insert_pdf(doc, from_page=p_idx, to_page=p_idx): PyMuPDF is generally memory-efficient when inserting pages like this, as it copies them rather than re-rendering.
- Speed: Iterating through thousands of pages and rendering each to an image will take time.
- Threshold Tuning: Accurate
pix_threshold and variance_threshold can reduce false positives/negatives, minimizing manual intervention.
- External Tools for Initial Split: For extremely large PDFs (multi-GB), sometimes it's faster to use command-line tools like
qpdf or cpdf to pre-split into smaller chunks, then run your Python script on each chunk.
- Multiprocessing: If your machine has multiple cores, you could potentially process different sections of the large PDF in parallel, though managing shared state (like the master PDF document) can be tricky. For this specific task, it might be easier to pre-split and then run multiple processes on the smaller files.
Remember to install the necessary libraries:
pip install PyMuPDF Pillow numpy pytesseract (if using OCR)