PDF Merger in Python
About the project: This is a single-file Python project that can merge multiple PDF files into one. This script is built using the popular PyPDF2 library, which makes it very simple to combine documents.
Prerequisites
Before you run the code, you'll need to install the PyPDF2 library. You can do this easily using pip from your terminal or command prompt:
pip install PyPDF2
This script in code snippet below is designed to be simple and easy to use. Just save it, make sure the PDFs you want to merge are in the same folder as the script, and then run it from your terminal.
Project Level: Intermediate
You can directly copy the below snippet code with the help of green copy button, paste it and run it in any Python editor you have.
Steps: Follow these stepsStep 1: Copy below code using green 'copy' button.
Step 2: Paste the code on your chosen editor.
Step 3: Save the code with filename and .py extention.
Step 4: Run (Press F5 if using python IDLE).
# pdf_merger.py
import os
from PyPDF2 import PdfMerger
def merge_pdfs():
"""
Merges multiple PDF files into a single output file.
It prompts the user for the list of files to merge and the output filename.
"""
print("PDF Merger Tool")
print("----------------")
# Get the list of PDF files to merge from the user.
# The files should be in the same directory as this script.
input_files_str = input("Enter the names of the PDF files to merge (e.g., file1.pdf file2.pdf): ")
input_files = input_files_str.split()
# Get the desired name for the output file.
output_filename = input("Enter the name for the merged output file (e.g., merged.pdf): ")
if not output_filename.lower().endswith(".pdf"):
output_filename += ".pdf"
# Create an instance of PdfMerger.
merger = PdfMerger()
# A flag to check if any valid files were added.
files_found = False
# Loop through the list of input files and append them to the merger.
for filename in input_files:
if os.path.exists(filename) and filename.lower().endswith(".pdf"):
try:
# Appends the content of a PDF file to the merger object.
merger.append(filename)
print(f"Successfully added '{filename}' to the merger.")
files_found = True
except Exception as e:
print(f"Error adding '{filename}': {e}. Skipping this file.")
else:
print(f"Error: '{filename}' not found or is not a PDF. Skipping.")
if not files_found:
print("No valid PDF files were found to merge. Exiting.")
return
try:
# Write the merged PDF to the output file.
merger.write(output_filename)
print("\n----------------")
print(f"Success! All specified PDF files have been merged into '{output_filename}'.")
print("----------------")
except Exception as e:
print(f"An error occurred while writing the output file: {e}")
finally:
# Close the merger to free up resources.
merger.close()
if __name__ == "__main__":
merge_pdfs()
← Back to Projects