I have a lot of large scanned PDF files (each page is an image). Each one is a…
- User
I have a lot of large scanned PDF files (each page is an image). Each one is a concatenation of multiple PDF. How can I recover the small files using Python code
Assistant
You can split large scanned PDFs into smaller files using Python. Here's a comprehensive approach using PyPDF2 or pdf2image with PIL:
Method 1: Using PyPDF2 (for simple page-based splitting)
import PyPDF2 import os def split_pdf_by_pages(input_pdf, pages_per_file, output_dir): """Split PDF into smaller files with fixed number of pages""" # Create output directory if it doesn't exist os.makedirs(output_dir, exist_ok=True) # Open the PDF with open(input_pdf, 'rb') as file: pdf_reader = PyPDF2.PdfReader(file) total_pages = len(pdf_reader.pages) # Split into chunks for i in range(0, total_pages, pages_per_file): pdf_writer = PyPDF2.PdfWriter() # Add pages to the new PDF for j in range(i, min(i + pages_per_file, total_pages)): pdf_writer.add_page(pdf_reader.pages[j]) # Save the new PDF output_filename = f"{output_dir}/split_{i//pages_per_file + 1}.pdf" with open(output_filename, 'wb') as output_file: pdf_writer.write(output_file) print(f"Created: {output_filename}") # Usage split_pdf_by_pages('large_scan.pdf', pages_per_file=10, output_dir='output_pdfs')Method 2: Detecting document boundaries automatically
For automatically detecting where one document ends and another begins, you can analyze the content of each page:
import pdf2image import numpy as np from PIL import Image import PyPDF2 import os def is_blank_page(image, threshold=0.95): """Check if a page is mostly blank (potential document separator)""" # Convert to grayscale gray = image.convert('L') # Convert to numpy array arr = np.array(gray) # Calculate percentage of white pixels white_pixels = np.sum(arr > 250) total_pixels = arr.size white_ratio = white_pixels / total_pixels return white_ratio > threshold def split_pdf_by_blank_pages(input_pdf, output_dir, dpi=150): """Split PDF at blank pages""" os.makedirs(output_dir, exist_ok=True) # Convert PDF to images print("Converting PDF to images...") images = pdf2image.convert_from_path(input_pdf, dpi=dpi) # Find blank pages blank_pages = [] for i, img in enumerate(images): if is_blank_page(img): blank_pages.append(i) print(f"Found blank page at position {i}") # Add start and end markers split_points = [0] + blank_pages + [len(images)] # Open the original PDF with open(input_pdf, 'rb') as file: pdf_reader = PyPDF2.PdfReader(file) # Create separate PDFs for i in range(len(split_points) - 1): start = split_points[i] end = split_points[i + 1] # Skip if this would create an empty PDF if start == end or (i > 0 and start + 1 == end): continue pdf_writer = PyPDF2.PdfWriter() # Adjust start if it's a blank page (except for the first document) if i > 0 and start in blank_pages: start += 1 # Add pages for j in range(start, end): if j < len(pdf_reader.pages) and j not in blank_pages: pdf_writer.add_page(pdf_reader.pages[j]) # Save if not empty if len(pdf_writer.pages) > 0: output_filename = f"{output_dir}/document_{i + 1}.pdf" with open(output_filename, 'wb') as output_file: pdf_writer.write(output_file) print(f"Created: {output_filename} ({len(pdf_writer.pages)} pages)") # Usage split_pdf_by_blank_pages('large_scan.pdf', 'output_documents')Method 3: Using OCR to detect document boundaries
For more sophisticated splitting based on content:
import pytesseract import pdf2image import PyPDF2 import re import os def extract_text_from_page(image): """Extract text from a page image using OCR""" return pytesseract.image_to_string(image) def is_document_start(text, patterns=None): """Check if the page text indicates a new document start""" if patterns is None: # Common patterns for document starts patterns = [ r'^(page\s+1|1\s+of\s+\d+)', # Page numbering r'^(chapter|section)\s+\d+', # Chapter/section markers r'^(invoice|report|memo|letter)', # Document types # Add your specific patterns here ] text_lower = text.lower().strip() for pattern in patterns: if re.search(pattern, text_lower, re.MULTILINE | re.IGNORECASE): return True return False def split_pdf_by_content(input_pdf, output_dir, dpi=150): """Split PDF based on content analysis""" os.makedirs(output_dir, exist_ok=True) print("Converting PDF to images and analyzing content...") images = pdf2image.convert_from_path(input_pdf, dpi=dpi) # Find document boundaries doc_starts = [0] # First page is always a start for i, img in enumerate(images[1:], 1): # Skip first page text = extract_text_from_page(img) if is_document_start(text): doc_starts.append(i) print(f"Found document start at page {i + 1}") doc_starts.append(len(images)) # Add end marker # Split the PDF with open(input_pdf, 'rb') as file: pdf_reader = PyPDF2.PdfReader(file) for i in range(len(doc_starts) - 1): start = doc_starts[i] end = doc_starts[i + 1] pdf_writer = PyPDF2.PdfWriter() for j in range(start, end): pdf_writer.add_page(pdf_reader.pages[j]) output_filename = f"{output_dir}/document_{i + 1}.pdf" with open(output_filename, 'wb') as output_file: pdf_writer.write(output_file) print(f"Created: {output_filename} ({end - start} pages)") # Usage split_pdf_by_content('large_scan.pdf', 'output_documents')Installation Requirements
Install the required packages:
pip install PyPDF2 pdf2image pillow numpy pytesseractFor pdf2image to work, you'll also need to install poppler:
- Ubuntu/Debian:
sudo apt-get install poppler-utils - macOS:
brew install poppler - Windows: Download from poppler website
For OCR functionality, install Tesseract:
- Ubuntu/Debian:
sudo apt-get install tesseract-ocr - macOS:
brew install tesseract - Windows: Download from GitHub
Choose the method that best fits your needs:
- Method 1: Simple fixed-size splitting
- Method 2: Automatic detection based on blank pages
- Method 3: Content-based splitting using OCR
You can also combine these approaches or modify them based on your specific PDF structure and requirements.
- Ubuntu/Debian:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.