Merge Multiple PDF Files into One Document in Python
Combines multiple PDF files into a single PDF document using the PyPDF2 library's PdfMerger class.
pip install PyPDF2
Python code
13 linesimport PyPDF2
def merge_pdfs(input_paths, output_path):
merger = PyPDF2.PdfMerger()
for path in input_paths:
merger.append(path)
merger.write(output_path)
merger.close()
print(f"Merged {len(input_paths)} PDFs into '{output_path}'.")
if __name__ == "__main__":
files = ["file1.pdf", "file2.pdf", "file3.pdf"]
merge_pdfs(files, "merged_output.pdf")
Output
Merged 3 PDFs into 'merged_output.pdf'.
How it works
The PdfMerger object collects pages from each input PDF by calling .append(). After all files are added, .write() saves the combined document to the specified output path. Closing the merger with .close() ensures all file handles are released and resources are cleaned up. This approach works with any number of PDFs and preserves the original page order.
Common mistakes
- Using `PyPDF2.PdfFileMerger` which is the old, deprecated class name in recent versions.
- Forgetting to close the merger object after writing, which can leave file handles open.
- Passing non-existent or corrupted PDF file paths without error handling.
Variations
- Use `pypdf` (the successor of PyPDF2) with `from pypdf import PdfMerger` for continued support.
- Add page range selection with `merger.append(path, pages=(0, 10))` to merge only specific pages.
Real-world use cases
- Combining scanned invoice PDFs into a single bundle before sending to accounting.
- Aggregating chapter PDFs into a full e-book or report for distribution.
- Merging multiple form submissions received as separate PDFs into one archive.
Sponsored
More from Files & data
- Build a Command-Line To-Do List Application with Data Persistence in Python easy
- Build a Python Script That Detects and Deletes Empty Files Across Folders easy
- Compare Two Folder Structures and Find Differences in Python easy
- Compress and Extract ZIP Files Programmatically in Python easy
- Convert CSV Files to JSON in Python easy
- Convert Image to ASCII Art in Python medium
Keep learning
Related tutorials and quizzes for this topic.