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.
- 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
- Language: Python
- Libraries:
PyPDF2==3.0.1
- Complexity: Beginner
# Install dependencies
pip install -r requirements.txt
# Run the program
python main.pypython main.pyFollow the menu prompts to:
- Merge all PDFs in current directory
- Merge all PDFs in specific directory
- Manually select specific PDF files
- Exit
==================================================
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
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
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
Scans directory and returns list of all PDF files.
Merges PDFs using PdfMerger class.
Merges PDFs using PdfWriter class.
Interactive function to manually select PDF files.
- Combine multiple reports into one
- Merge contract pages
- Consolidate invoices
- Combine research papers
- Merge assignment pages
- Consolidate study materials
- Merge presentation slides
- Combine financial reports
- Consolidate project documents
- Combine scanned documents
- Merge travel documents
- Consolidate receipts
pdf_files = get_pdf_files("./documents")Finds all .pdf files in specified directory.
pdf_files = get_user_pdf_files()Prompts user to enter file paths one by one.
- Checks if files exist
- Verifies PDF extension
- Handles corrupted files gracefully
Shows which file is being processed and total progress.
Displays:
- Number of files merged
- Total pages (Method 2)
- Output file size
- Output file path
- File not found errors
- Corrupted PDF handling
- Permission errors
- Invalid file format
- Disk space issues
- Keyboard interrupts
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)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)merger = PyPDF2.PdfMerger()
for pdf_file in pdf_files:
merger.append(pdf_file, bookmark=os.path.basename(pdf_file))
merger.write(output_file)page = reader.pages[0]
page.rotate(90) # Rotate 90 degrees clockwise
writer.add_page(page)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.pdfMerge 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'])- PDF file manipulation
- PyPDF2 library usage
- File I/O operations
- Directory scanning
- Error handling
- User input validation
- Cross-platform file operations
- CLI interface design
- 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
- PDF file is corrupted
- Try opening in PDF reader to verify
- Use PDF repair tool
- Output file is open in another program
- Close the file and try again
- Choose different output name
- Check file path is correct
- Use absolute paths if needed
- Verify file exists
- PDFs contain high-resolution images
- Use PDF compression tools
- Reduce image quality before merging
- Process files in batches for large sets
- Close file handles properly
- Use context managers (
withstatement) - Monitor memory usage for large PDFs
- Consider streaming for very large files
- pypdf (PyPDF2 successor)
- pdfrw (faster for some operations)
- PyMuPDF (fitz) (more features)
- pdfplumber (better text extraction)
This project is open source and available for educational purposes.