Skip to content

All topics  /  Python

How to Merge PDF File using Python?

Python

Development teams using “How to Merge PDF File using Python?” in client or internal work can use the product resource to document project effort and hand-offs, then assess the record against delivered functionality, tests and agreed outcomes.

Validate current syntax, security guidance and supported versions through Python.org before using the example in production.

Mar 14, 2022

Hi Guys,

I am going to show you how to merge pdf files using python. We will talk about merging multiple pdfs into a single pdf using a python script.

Have you ever had multiple pdf files that you need to merge into one single document? It is easier than you might think to merge or combine two or more pdf into one single file in python.

PyPDF2 is a python library used to work with PDF files. You can use it to extract document information, split document page by page, merge multiple pages, encrypt and decrypt, etc. In this tutorial, you will learn how to merge multiple files using this module.

Step 1 :


You first need to install the package using pip:

pip install PyPDF2

Step 2 : Python Script

merge_pdf.py

#import PyPDF2 Package
import PyPDF2
try:
    # Open the files that have to be merged one by one
    pdf1File = open('/var/www/samplepdf1.pdf', 'rb')
    pdf2File = open('/var/www/samplepdf2.pdf', 'rb')
    # Read the files that you have opened
    pdf1Reader = PyPDF2.PdfFileReader(pdf1File,strict=False)
    pdf2Reader = PyPDF2.PdfFileReader(pdf2File,strict=False)
    # Create a new PdfFileWriter object which represents a blank PDF document
    pdfWriter = PyPDF2.PdfFileWriter()

    
    # Loop through all the pagenumbers for the first document
    for pageNum in range(pdf1Reader.numPages):
        pageObj = pdf1Reader.getPage(pageNum)
        pdfWriter.addPage(pageObj)
    # Loop through all the pagenumbers for the second document
    for pageNum in range(pdf2Reader.numPages):
        pageObj = pdf2Reader.getPage(pageNum)
        pdfWriter.addPage(pageObj) 
    # Now that you have copied all the pages in both the documents, write them into the a new document
    pdfOutputFile = open('var/www/mergeSample.pdf', 'wb')
    pdfWriter.write(pdfOutputFile) 
    # Close all the files - Created as well as opened
    pdfOutputFile.close()
    pdf1File.close()
    pdf2File.close()
except Exception as e: 
    print(e)
else:
  print("success")

Run Example

python merge_pdf.py

It will help you....

how to merge pdf using python, how to combine pdf files using python, merge pdf using python, python script to merge pdf files, merge two pdf file in single file using python, python merge pdf files into one