0

Here is the code block that is causing the issue. The loop will append the new file each time, which is not what I am trying to accomplish. For example, outputfile1 is input1.pdf, outputfile2 is input1.pdf + input2.pdf...

I am trying to merge file 1x.pdf with files 1a.pdf + 1b.pdf + 1c.pdf into the output file1.pdf and then loop through and do the same thing for 2, 3, and 4. The end result should be 4 separate files. What am I missing? Clear as mud? Thanks in advance for any assistance.

i = 1

while i < 5:
    # files to be merged

    input1 = open(Path1+str(i)+"x.PDF", "rb")
    input2 = open(Path2+str(i)+"a.PDF", "rb")
    input3 = open(Path2+str(i)+"b.PDF", "rb")
    input4 = open(Path2+str(i)+"c.PDF", "rb")

    # output files
    output_file = open("/NewFile"+str(i)+".pdf", "wb")

    # add input1 document to output
    merger.append(fileobj = input1, pages = (0, 3, 2), import_bookmarks = False)

    # insert the pages of input2 into the output beginning after the second page
    merger.append(input2)

    # insert the pages of input3 into the output beginning after the second page
    merger.append(input3)

    # insert the pages of input4 into the output beginning after the second page
    merger.append(input4)

    # Write to an output PDF document
    merger.write(output_file)
    output_file.close()

    i += 1
Martin Thoma
  • 124,992
  • 159
  • 614
  • 958
user3482598
  • 1
  • 1
  • 3
  • Your problem is unclear, but I strongly recommend looking at `pdftk` for concatenating PDF files. See http://stackoverflow.com/a/2507825/145400 – Dr. Jan-Philip Gehrcke Feb 28 '15 at 16:00
  • Yea, it is difficult to articulate. The short of it is that if I manually change the iterator variable, it works great. If I write a loop, it doesn't. Almost like running the program discretely (each time) clears the memory or something. I will check out the library you referenced. Thanks. – user3482598 Feb 28 '15 at 18:06

1 Answers1

1

Resurrecting a super old question but ran into this and wanted to answer to hopefully prevent others from pasting your partial code above and running into the same problem.

Without seeing the rest I'm only guessing, but your loop doesn't create a new merger, it just keeps appending and appending and appending, which is what you're reporting as the issue. I expect if you bring your merger initialization code into the loop (so that it gets re-setup each iteration) you'll have what you're looking for.