Skip to content

Latest commit

 

History

History
 
 

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 

README.md

Merge PDFs

Description

A Python application that combines multiple PDF files into a single PDF document. Supports automatic directory scanning, manual file selection, and two different merging methods for flexibility.

Features

  • Merge all PDFs in a directory
  • Manual file selection
  • Two merging methods (PdfMerger and PdfWriter)
  • Preserve page order and formatting
  • Progress tracking during merge
  • File size reporting
  • Automatic file opening after merge
  • Error handling for corrupted PDFs
  • Cross-platform support
  • Interactive CLI interface

Stack

  • Language: Python
  • Libraries:
    • PyPDF2==3.0.1
  • Complexity: Beginner

Installation

# Install dependencies
pip install -r requirements.txt

# Run the program
python main.py

Usage

Interactive Mode

python main.py

Follow the menu prompts to:

  1. Merge all PDFs in current directory
  2. Merge all PDFs in specific directory
  3. Manually select specific PDF files
  4. Exit

Example Session

==================================================
           PDF MERGER
==================================================

Combine multiple PDF files into one document
==================================================

Options:
  1. Merge all PDFs in current directory
  2. Merge all PDFs in specific directory
  3. Merge specific PDF files (manual selection)
  4. Exit

Enter your choice (1-4): 1

Searching for PDFs in current directory...

Found 3 PDF files:
  1. document1.pdf
  2. document2.pdf
  3. document3.pdf

Enter output file name (default: merged_output.pdf): combined.pdf

Merge methods:
  1. PdfMerger (recommended)
  2. PdfWriter (alternative)

Choose method (1-2, default: 1): 1

Merging PDFs using PdfMerger...
==================================================
Adding file 1/3: document1.pdf
Adding file 2/3: document2.pdf
Adding file 3/3: document3.pdf

Writing merged PDF to: combined.pdf
✓ Successfully merged 3 PDFs!
  Output file: combined.pdf
  File size: 1234.56 KB
==================================================

Open merged PDF? (y/n): y

How It Works

Method 1: PdfMerger (Recommended)

merger = PyPDF2.PdfMerger()
for pdf_file in pdf_files:
    merger.append(pdf_file)
merger.write(output_file)
merger.close()

Advantages:

  • Simpler and cleaner code
  • Automatic metadata handling
  • Better memory management
  • Recommended by PyPDF2

Method 2: PdfWriter (Alternative)

writer = PyPDF2.PdfWriter()
for pdf_file in pdf_files:
    reader = PyPDF2.PdfReader(open(pdf_file, 'rb'))
    for page in reader.pages:
        writer.add_page(page)
with open(output_file, 'wb') as output:
    writer.write(output)

Advantages:

  • More control over individual pages
  • Can modify pages before adding
  • Useful for advanced operations

Functions

get_pdf_files(directory)

Scans directory and returns list of all PDF files.

merge_pdfs_method1(pdf_files, output_file)

Merges PDFs using PdfMerger class.

merge_pdfs_method2(pdf_files, output_file)

Merges PDFs using PdfWriter class.

get_user_pdf_files()

Interactive function to manually select PDF files.

Use Cases

Document Management

  • Combine multiple reports into one
  • Merge contract pages
  • Consolidate invoices

Academic

  • Combine research papers
  • Merge assignment pages
  • Consolidate study materials

Business

  • Merge presentation slides
  • Combine financial reports
  • Consolidate project documents

Personal

  • Combine scanned documents
  • Merge travel documents
  • Consolidate receipts

Features Explained

Automatic Directory Scanning

pdf_files = get_pdf_files("./documents")

Finds all .pdf files in specified directory.

Manual Selection

pdf_files = get_user_pdf_files()

Prompts user to enter file paths one by one.

File Validation

  • Checks if files exist
  • Verifies PDF extension
  • Handles corrupted files gracefully

Progress Tracking

Shows which file is being processed and total progress.

File Information

Displays:

  • Number of files merged
  • Total pages (Method 2)
  • Output file size
  • Output file path

Error Handling

  • File not found errors
  • Corrupted PDF handling
  • Permission errors
  • Invalid file format
  • Disk space issues
  • Keyboard interrupts

Customization

Add Page Numbers

from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter

def add_page_numbers(input_pdf, output_pdf):
    reader = PyPDF2.PdfReader(input_pdf)
    writer = PyPDF2.PdfWriter()
    
    for page_num, page in enumerate(reader.pages, 1):
        # Create page number overlay
        packet = io.BytesIO()
        can = canvas.Canvas(packet, pagesize=letter)
        can.drawString(500, 20, f"Page {page_num}")
        can.save()
        
        # Merge overlay with page
        packet.seek(0)
        overlay = PyPDF2.PdfReader(packet)
        page.merge_page(overlay.pages[0])
        writer.add_page(page)
    
    with open(output_pdf, 'wb') as output:
        writer.write(output)

Merge Specific Pages

def merge_specific_pages(pdf_file, pages, output_file):
    reader = PyPDF2.PdfReader(pdf_file)
    writer = PyPDF2.PdfWriter()
    
    for page_num in pages:
        writer.add_page(reader.pages[page_num])
    
    with open(output_file, 'wb') as output:
        writer.write(output)

Add Bookmarks

merger = PyPDF2.PdfMerger()
for pdf_file in pdf_files:
    merger.append(pdf_file, bookmark=os.path.basename(pdf_file))
merger.write(output_file)

Rotate Pages

page = reader.pages[0]
page.rotate(90)  # Rotate 90 degrees clockwise
writer.add_page(page)

Command-Line Version

Create a CLI version with arguments:

import argparse

parser = argparse.ArgumentParser(description='Merge PDF files')
parser.add_argument('files', nargs='+', help='PDF files to merge')
parser.add_argument('-o', '--output', default='merged.pdf', help='Output file')
args = parser.parse_args()

merge_pdfs_method1(args.files, args.output)

Usage:

python main.py file1.pdf file2.pdf file3.pdf -o output.pdf

Batch Processing

Merge multiple sets of PDFs:

merge_configs = [
    {
        'files': ['doc1.pdf', 'doc2.pdf'],
        'output': 'set1.pdf'
    },
    {
        'files': ['doc3.pdf', 'doc4.pdf'],
        'output': 'set2.pdf'
    }
]

for config in merge_configs:
    merge_pdfs_method1(config['files'], config['output'])

Learning Outcomes

  • PDF file manipulation
  • PyPDF2 library usage
  • File I/O operations
  • Directory scanning
  • Error handling
  • User input validation
  • Cross-platform file operations
  • CLI interface design

Future Enhancements

  • GUI interface with drag-and-drop
  • PDF preview before merging
  • Reorder files before merging
  • Remove specific pages
  • Add watermarks
  • Compress output PDF
  • Encrypt/decrypt PDFs
  • Split PDFs
  • Extract specific pages
  • Batch processing
  • Progress bar for large files
  • PDF metadata editing
  • OCR integration
  • Cloud storage integration

Common Issues

"PdfReadError: EOF marker not found"

  • PDF file is corrupted
  • Try opening in PDF reader to verify
  • Use PDF repair tool

"PermissionError: [Errno 13]"

  • Output file is open in another program
  • Close the file and try again
  • Choose different output name

"FileNotFoundError"

  • Check file path is correct
  • Use absolute paths if needed
  • Verify file exists

Large File Size

  • PDFs contain high-resolution images
  • Use PDF compression tools
  • Reduce image quality before merging

Performance Tips

  • Process files in batches for large sets
  • Close file handles properly
  • Use context managers (with statement)
  • Monitor memory usage for large PDFs
  • Consider streaming for very large files

Alternative Libraries

  • pypdf (PyPDF2 successor)
  • pdfrw (faster for some operations)
  • PyMuPDF (fitz) (more features)
  • pdfplumber (better text extraction)

License

This project is open source and available for educational purposes.