Skip to content

Latest commit

 

History

History
196 lines (133 loc) · 4.57 KB

File metadata and controls

196 lines (133 loc) · 4.57 KB

Replace Page

A Python utility to replace a page in a PDF file with an image. The image is automatically scaled to fit the dimensions of the page being replaced while maintaining its aspect ratio.

Features

  • Replace any page in a PDF with an image
  • Automatically scales images to match page dimensions
  • Maintains image aspect ratio
  • Preserves all other pages in the PDF
  • Supports various image formats (PNG, JPEG, BMP, etc.)
  • CLI interface with progress logging
  • Comprehensive error handling

Installation

  1. Ensure your Python virtual environment is activated:
.\.venv\Scripts\Activate.ps1  # On Windows PowerShell
source .venv/bin/activate     # On Linux/macOS
  1. Install the required dependencies:
pip install -r requirements.txt

The required packages are:

  • PyPDF2 - For PDF manipulation
  • Pillow - For image processing

Usage

Basic Usage

Replace the first page (default) of a PDF with an image:

python replace_page.py input.pdf image.png

This creates a new file named input_replaced.pdf.

Replace a Specific Page

Replace page 3 of a PDF:

python replace_page.py input.pdf image.png --page 3

Specify Output File

Save the result to a specific file:

python replace_page.py input.pdf image.png --output modified.pdf

Overwrite Output

Replace an existing output file without prompting:

python replace_page.py input.pdf image.png --output existing.pdf --overwrite

Logging Options

Suppress informational messages:

python replace_page.py input.pdf image.png --quiet

Set logging level:

python replace_page.py input.pdf image.png --log-level DEBUG

Examples

Example 1: Replace the cover page

python replace_page.py document.pdf new_cover.png --page 1 --output document_updated.pdf --overwrite

Example 2: Replace a specific page with detailed logging

python replace_page.py report.pdf page_5_image.png --page 5 --log-level DEBUG

Example 3: Batch replace pages using a script

$pages = @(
    @{page=1; image="cover.png"},
    @{page=3; image="diagram.jpg"},
    @{page=5; image="chart.png"}
)

foreach ($item in $pages) {
    python replace_page.py original.pdf $item.image --page $item.page --overwrite
}

Command-Line Options

  • pdf - Path to the input PDF file (required)
  • image - Path to the image file to use as replacement (required)
  • -p, --page PAGE - Page number to replace (1-indexed, default: 1)
  • -o, --output OUTPUT - Path to the output PDF file (defaults to <input>_replaced.pdf)
  • --overwrite - Overwrite the output file if it exists
  • --quiet - Suppress informational logging
  • --log-level LOG_LEVEL - Set logging level (DEBUG, INFO, WARNING, ERROR)
  • --version - Show version information
  • -h, --help - Show help message

Image Handling

Image Scaling

The script automatically scales images to fit the page dimensions while preserving the aspect ratio:

  • If the image is wider, it's scaled to the page width
  • If the image is taller, it's scaled to the page height
  • The scaled image is centered on a white background

Supported Image Formats

  • PNG
  • JPEG
  • BMP
  • GIF
  • TIFF
  • And other formats supported by PIL

RGBA Images

PNG images with transparency (RGBA) are automatically converted to RGB format with a white background.

Error Handling

The script provides clear error messages for common issues:

  • FileNotFoundError - Input PDF or image file not found
  • ValueError - Output file already exists and --overwrite not specified
  • PdfPageError - Page number is invalid or exceeds total pages
  • ImageToPdfError - Image conversion failed

Testing

Run the included tests to verify functionality:

python -m pytest tests/test_replace_page.py -v

Test Coverage

  • Successfully replacing a page with an image
  • Error handling for missing files
  • Error handling for invalid page numbers
  • Error handling when output file exists
  • Replacing different pages in multi-page PDFs

Performance

  • Memory-efficient: The entire PDF is read into memory once
  • Image scaling uses high-quality LANCZOS resampling
  • Suitable for PDFs of all sizes

Limitations

  • Currently replaces entire pages (not partial page regions)
  • Output is always in standard PDF format
  • Cannot merge multiple images into a single page
  • Original PDF form fields and annotations are not preserved

Dependencies

  • Python 3.7+
  • PyPDF2 >= 4.0
  • Pillow >= 10.0

License

This utility is part of the pdf-tools project.

See Also