2 min read

PDF Merger Tool

This utility combines multiple PDF files into a single document. It accepts individual file paths or directories as input and merges them in the order provided.

Modules Used:

  • pypdf: To handle PDF reading and writing operations.
  • argparse: To handle command-line arguments for input files and output destination.
  • pathlib: For robust file path handling and directory iteration.

Installation

pip install pypdf

The Code

Save this as merge_pdfs.py.

import argparse
from pathlib import Path
from pypdf import PdfWriter
import sys

def merge_pdfs(inputs, output):
    merger = PdfWriter()
    count = 0

    print(f"Starting merge process...")

    for input_path in inputs:
        path = Path(input_path)
        files_to_add = []

        # Handle directories (add all PDFs inside)
        if path.is_dir():
            # Sort to ensure consistent order
            files_to_add = sorted(path.glob("*.pdf"))
        # Handle individual files
        elif path.is_file() and path.suffix.lower() == ".pdf":
            files_to_add = [path]
        else:
            print(f"Warning: Skipping '{input_path}' (not a PDF or directory)")
            continue

        # Append files to the merger
        for pdf in files_to_add:
            try:
                print(f"  + Adding: {pdf.name}")
                merger.append(pdf)
                count += 1
            except Exception as e:
                print(f"  ! Error adding {pdf.name}: {e}")

    if count == 0:
        print("No valid PDF files found to merge.")
        return

    # Write the final file
    try:
        merger.write(output)
        merger.close()
        print(f"\nSuccess! Merged {count} files into '{output}'")
    except Exception as e:
        print(f"Error writing output file: {e}")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="PDF Merger Utility")
    parser.add_argument("inputs", nargs="+", help="Input PDF files or directories")
    parser.add_argument("-o", "--output", default="merged_output.pdf", help="Output filename (default: merged_output.pdf)")

    args = parser.parse_args()
    merge_pdfs(args.inputs, args.output)

Usage

# Merge specific files
python merge_pdfs.py cover.pdf chapter1.pdf chapter2.pdf -o book.pdf

# Merge all PDFs in a directory
python merge_pdfs.py ./documents -o archive.pdf

# Mix files and directories
python merge_pdfs.py intro.pdf ./chapters appendix.pdf

programming/python/python