How to Merge PDF File in Python?


0

We are going to show you how to merge pdf files in python?. We will talk about merger multiple pdfs into a single pdf using a python.

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

The python library PyPDF2 used to work with PDF files. You can use it to pull out document details, split document page by page, join multiple pages, encrypt and decrypt, etc. In this discuss, you will see how to merge multiple files in python using this module.

First step: You need to install the package by 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

This will help you….

How to merge pdf in python, how to join pdf files in python, merge pdf in python, python script to merge pdf files,.


Like it? Share with your friends!

0
Developer

0 Comments