Python program to Merge PDF

By | December 17, 2018

Python pdf merge

To merge PDF there are numerous tools available the internet. But all the tools come with some limitations. Some add watermarks and some limits the number of pages to merge.

So I wrote a simple python program to merge multiple single page PDF files in a folder to a single merged PDF.

This program takes the directory with PDF files with names 1.pdf, 2.pdf till n.pdf and merges into a single file. This program was written in python 3 and you need to install a package called PyPDF2

 

To start with you can download PyPDF2 from https://pypi.org/project/PyPDF2/#files . You can also install using pip command.

pip install PyPDF2

 

Steps to merge the PDF file.

  1. Create a merger Object and declare the number of pages(equal to n.pdf files the folder).
  2. Iterate the folder for n files with appending the PDF files.
  3. Write the file into the target folder with the desired name.

 

from PyPDF2 import PdfFileMerger, PdfFileReader

#1.create Merger
merger = PdfFileMerger(strict=False)
no_of_pages=129

#2.Iterate the Files and Merge
for i in range(1,no_of_pages):
    merger.append(PdfFileReader(open("C:/Users/myName/Downloads/pdfFiles/"+str(i)+".pdf", 'rb')))
    print("Added"+str(i))

#3.Write the Mergefd File
merger.write("Merged.pdf")

 

You can also read the documentation of the package here https://pypi.org/project/PyPDF2.

If you have any other idea or ways to merge pdf please comment.

 

Leave a Reply

Your email address will not be published. Required fields are marked *