One of the issues I’ve seen in the real world is end users having multiple PDFs and wanting to merge them into one PDF without paying for expensive PDF software or using freeware from unknown sources.

The below is a Python script to try and resolve that issue (Python 3, PyPDF2 and OS modules would be needed):


#geektechstuff
#Python script to merge multiple PDF files into one PDF

#Requires the “PyPDF2” and “OS” modules to be imported
import os, PyPDF2

#Ask user where the PDFs are
userpdflocation=input(‘Folder path to PDFs that need merging:’)

#Sets the scripts working directory to the location of the PDFs
os.chdir(userpdflocation)

#Ask user for the name to save the file as
userfilename=input(‘What should I call the file?’)

#Get all the PDF filenames
pdf2merge = []
for filename in os.listdir(‘.’):
if filename.endswith(‘.pdf’):
pdf2merge.append(filename)

pdfWriter = PyPDF2.PdfFileWriter()

#loop through all PDFs
for filename in pdf2merge:
#rb for read binary
pdfFileObj = open(filename,’rb’)
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
#Opening each page of the PDF
for pageNum in range(pdfReader.numPages):
pageObj = pdfReader.getPage(pageNum)
pdfWriter.addPage(pageObj)
#save PDF to file, wb for write binary
pdfOutput = open(userfilename+’.pdf’, ‘wb’)
#Outputting the PDF
pdfWriter.write(pdfOutput)
#Closing the PDF writer
pdfOutput.close()

pdfmerge

3 responses to “Python 3 – Merge Multiple PDFs Into One PDF”

  1. File Browser V1 (Python) – Geek Tech Stuff Avatar

    […] and seeing if any of my recent Python learning could be used to make them better. Possibly make the PDF merge idea better with some GUI driven fun rather than command line, and building on my previous GUI […]

    Like

  2. PDF Merge – With GUI (Python) – Geek Tech Stuff Avatar

    […] the tkinter module of Python to create a file browser GUI , and it has inspired me to relook at the PDF Merge program I did a while […]

    Like

  3. PDF Merge Website (Python) – Geek Tech Stuff Avatar

    […] fortune on a tool to do the merging. I first looked at this problem with an early Python project (https://geektechstuff.com/2018/02/17/python-3-merge-multiple-pdfs-into-one-pdf/) and later improved on that project by adding a simple GUI […]

    Like

Welcome to GeekTechStuff

my home away from home and where I will be sharing my adventures in the world of technology and all things geek.

The technology subjects have varied over the years from Python code to handle ciphers and Pig Latin, to IoT sensors in Azure and Python handling Bluetooth, to Ansible and Terraform and material around DevOps.

Let’s connect