Combine PDFs via Python

The problem of Combine PDFs via Python

We will learn how to combine PDFs via Python Programming Language. We not only learn to combine pdf in python but will also try to do the same in a looping statement for doing this procedure again and again in a directory. At last, we will also learn how to add a new pdf in the above-created folder if a similar pdf is not added before the head. 

 

 

Solution

To accomplish this activity we will use the file concatenation property of the python programming language. We will use the append command to do the same. The code for the same is shown below:

from PyPDF2 import PdfMerger

pdfs = ['file1.pdf', 'file2.pdf', 'file3.pdf', 'file4.pdf']

merger = PdfMerger()

for pdf in pdfs:
    merger.append(pdf)

merger.write("result.pdf")
merger.close()

 

Output:

 

One can also pass file paths instead of file names as well. There is a merging technique of the PdfMerger that allows one to define an insertion point in the output file, meaning you can place the pages anywhere in the file, for more precise merging control. The add method can be compared to a merge when the file’s end serves as the insertion point. The function for the merging of pages is given below:

 

merger.merge(2, pdf)

 

One can also set the page limit as well while merging them. By giving a tuple with the values (start, stop[, step]), the user can specify which pages from a given file are appended by using the pages keyword parameter of append and merge (like the regular range function). The exemplary code for the same is shown below:

 

merger.append(pdf, pages=(0, 3)) # first 3

pages
merger.append(pdf, pages=(0, 6, 2)) # pages 1,3, 5

 

 

Also Read: What are Runtime Errors and Their Causes?

 

 

Share this post

2 thoughts on “Combine PDFs via Python

Leave a Reply

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