Skip to content

Instantly share code, notes, and snippets.

@lossurdo
Created February 6, 2024 16:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lossurdo/8b926f5afe8470e37e660cba3845881a to your computer and use it in GitHub Desktop.
Save lossurdo/8b926f5afe8470e37e660cba3845881a to your computer and use it in GitHub Desktop.
This Python script merges multiple PDF files into a single PDF file
"""
This script merges multiple PDF files into a single PDF file.
The script takes a folder path as input, which should contain the PDF files to be merged.
It uses the PyPDF2 library to perform the merging operation.
The algorithm works as follows:
1. Import the necessary modules: os for file operations and PdfMerger from PyPDF2 for merging PDFs.
2. Specify the folder path containing the PDF files.
3. Create a PdfMerger object.
4. Iterate over all files in the folder.
a. Check if the file has a .pdf extension.
b. Get the full file path.
c. Append the file to the PdfMerger object.
5. Specify the output file path.
6. Write the merged PDF to the output file.
7. Close the PdfMerger object.
Example usage:
python merge_pdf_files.py
Note: Make sure to install the PyPDF2 library before running this script (pip install PyPDF2).
"""
import os
from PyPDF2 import PdfMerger
# Specify the folder path containing the PDF files
folder_path = '/path/to/pdf/files'
# Create a PdfMerger object
merger = PdfMerger()
# Iterate over all files in the folder
for filename in os.listdir(folder_path):
if filename.endswith('.pdf'):
file_path = os.path.join(folder_path, filename)
merger.append(file_path)
# Specify the output file path
output_path = os.path.join(folder_path, 'merged.pdf')
# Write the merged PDF to the output file
merger.write(output_path)
# Close the PdfMerger object
merger.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment