Merging Multiple PDF Files with Python
What is this program about?
This Python program helps us join multiple PDF files into a single PDF file.
For example, if you have file1.pdf and file2.pdf, this program will combine them into one new file called merged.pdf.
The Library Used: PyPDF2
PyPDF2is a Python library that helps us work with PDF files.- We can:
- Read PDFs
- Extract text
- Merge multiple PDFs
- Split pages
In this program, we are using a special tool from PyPDF2 called PdfMerger.
Step-by-Step Explanation of the Code
from PyPDF2 import PdfMerger
This line imports the PdfMerger tool from the PyPDF2 library.
def merge_pdfs(output_path, *input_paths):
"""Combine multiple PDFs into one"""
We create a function called merge_pdfs that:
- Takes a name for the output file (e.g.,
merged.pdf) - Takes the names of the PDF files we want to merge (like
file1.pdf,file2.pdf)
merger = PdfMerger()
Create a new PDF merger object. Think of it like an empty container where we will put our PDFs.
for path in input_paths:
merger.append(path)
Loop through each input file and add it to the container.
- Example: First add
file1.pdf, thenfile2.pdf.
merger.write(output_path)
merger.close()
Finally:
- Save the combined file into the new file name (e.g.,
merged.pdf). - Close the merger to finish the process.
print(f"Merged {len(input_paths)} PDFs into {output_path}")
Print a message telling us how many PDFs were merged and the name of the final file.
merge_pdfs("merged.pdf", "file1.pdf", "file2.pdf")
Here we call the function.
- It will take file1.pdf and file2.pdf
- Combine them into merged.pdf
Complete Code
from PyPDF2 import PdfMerger
def merge_pdfs(output_path, *input_paths):
"""Combine multiple PDFs into one"""
merger = 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}")
merge_pdfs("merged.pdf", "file1.pdf", "file2.pdf")
Output Example
If you have:
file1.pdf(5 pages)file2.pdf(3 pages)
The program will create:
merged.pdf(8 pages total 🎉)
Key Takeaways
- We used PyPDF2 library.
- The tool
PdfMergerhelps us combine PDFs. - Very useful for students, teachers, or office work when you need all your documents in one file.
Exercise Files
