Skip to content

Document Automation

4. File Processing & Document Automation

This section covers how to read, create, split, and watermark PDF documents automatically without using a point-and-click software application.

Tools & Libraries

  • pypdf (formerly PyPDF2): The industry-standard library used to read, manipulate, split, merge, and encrypt PDF files.
  • pathlib: A modern, object-oriented tool used to manage file paths across Windows, Mac, and Linux without worrying about backslashes vs. forward slashes.
  • os: A built-in module that allows your Python script to perform operating system tasks like deleting files, checking environment variables, or creating folders.

Core Methods & Code Example

  • Path.cwd() / Path.glob('*.pdf'): Finds the exact folder your script is running in and searches through it to gather all available PDF files automatically.
  • PdfReader('file.pdf') & PdfWriter(): Opens an existing PDF document to read its pages, and sets up a blank digital canvas to write new files into your computer's memory.
  • PdfWriter.add_page(page): Separates a single page from an input PDF file and drops it into a brand-new PDF output stream.
  • PageObject.merge_page(watermark_page): Overlays a background graphic layer (like a "Confidential" stamp) perfectly on top of a text page.
from pathlib import Path
from pypdf import PdfReader, PdfWriter

# 1. Pathlib Example: Discover files automatically
# Instead of typing "C:/Users/Documents/...", Path.cwd() finds where you are.
current_folder = Path.cwd()
pdf_files = list(current_folder.glob('*.pdf'))

if pdf_files:
    # 2. pypdf Example: Extracting a page
    reader = PdfReader(pdf_files[0]) # Open the first PDF found
    writer = PdfWriter()             # Create a "blank" PDF in memory

    # Grab the first page and add it to our new blank document
    first_page = reader.pages[0]
    writer.add_page(first_page)

    # 3. OS/File Example: Saving to disk
    # 'wb' stands for "Write Binary" — required for PDF files.
    with open('extracted_page.pdf', 'wb') as output_file:
        writer.write(output_file)