'Merging multiple PDFs at specified pages
I am trying to use Python to merge multiple PDFs at specific pages I want. So for instance, let's say we have 3 pdfs and I want to merge the second one at page 2 and the third one at page 22 of the first one.
This answer gave me something to work with and this is actually good if there are only two pdfs; however for more than 2 I couldn't make it work.
from PyPDF2 import PdfFileMerger
pdfs = ['sample1.pdf',
'sample2.pdf',
'sample3.pdf']
merger = PdfFileMerger( )
for pdf in pdfs:
merger.merge(3, pdf)
merger.write("result.pdf")
merger.close()
This will add sample2 after page 3 and then sample3 after page 3, which results in shifting sample2. I looked at the documentation of PdfFileMerger as well but could not find the elegant solution I wanted. I know I might be able to make it work with multiple tries(for instance, multiple for-loops), but I am hopeful there is a simple solution that does everything at one go.
Solution 1:[1]
The main idea is you start merging the pdfs in reverse order so that the pdf is merged at last which will not affect ordering.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Deepak Chauhan |