#!/usr/bin/env python3
"""
PDF Merger Script
Merges multiple PDF files into a single output PDF.
Requirements:
- pip install pypdf
Usage:
python merge_pdfs.py input1.pdf input2.pdf ... -o output.pdf
# Example:
# python merge_pdfs.py file1.pdf file2.pdf file3.pdf -o merged.pdf
"""
import argparse
from pathlib import Path
from pypdf import PdfMerger
def merge_pdfs(input_paths: list[Path], output_path: Path) -> None:
"""
Merges the given PDF files into a single output file.
Args:
input_paths: List of paths to input PDF files.
output_path: Path to the output merged PDF file.
Raises:
FileNotFoundError: If any input file doesn't exist.
ValueError: If no input files provided or output path is invalid.
"""
if not input_paths:
raise ValueError("No input PDF files provided.")
merger = PdfMerger()
try:
for pdf_path in input_paths:
if not pdf_path.exists():
raise FileNotFoundError(f"Input file not found: {pdf_path}")
print(f"Adding: {pdf_path.name}")
merger.append(pdf_path)
merger.write(output_path)
print(f"Successfully merged {len(input_paths)} PDFs into: {output_path}")
finally:
merger.close()
def main():
parser = argparse.ArgumentParser(description="Merge multiple PDFs into one file.")
parser.add_argument(
"inputs",
nargs="+",
type=Path,
help="Input PDF files to merge (in order)."
)
parser.add_argument(
"-o",
"--output",
type=Path,
required=True,
help="Output path for the merged PDF (required)."
)
args = parser.parse_args()
try:
merge_pdfs(args.inputs, args.output)
except Exception as e:
print(f"Error: {e}", file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
import sys
main()
How to Use:
-
Install the dependency:
pip install pypdf
-
Save the script as merge_pdfs.py.
-
Run it:
python merge_pdfs.py document1.pdf document2.pdf -o combined.pdf
Features:
- Command-line interface with
argparse for easy usage.
- Error handling: Checks for file existence and provides clear messages.
- Preserves order: PDFs are merged in the order provided.
- Progress feedback: Prints which files are being added.
- Cross-platform: Uses
pathlib.Path for path handling.
- Safe cleanup: Always closes the merger object.
This script is efficient for most use cases, including large files, as pypdf is optimized for PDF manipulation. If you need bookmarks, page ranges, or advanced features, let me know!