Python 3 – Merge Multiple PDFs Into One PDF

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 thoughts on “Python 3 – Merge Multiple PDFs Into One PDF

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.