1

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.

Rob
  • 241
  • 1
  • 14
  • 1
    You could try adding the page number at which to merge to the list. So the list becomes like `pdfs = [('one.pdf', 0), ('two.pdf', 2), ('three.pdf', 22)]`. Then pass the number to merge also. Bear in mind though that previous merges might bump up the page number. So if two.pdf adds 10 pages then page 22 will be 10 less than you had expected. [Heres](https://ideone.com/SF9gSH) some example code. It time consuming for me to test it now (plus I'm at work). If it works ok let me know otherwise I'll try to fix it later. – Paul Rooney Jul 31 '19 at 06:40
  • Thanks Paul! It does exactly what I wanted! – Rob Jul 31 '19 at 07:36

1 Answers1

0

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.

Deepak Chauhan
  • 782
  • 7
  • 10