Python Forum

Full Version: For Loop, over even index
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I've created a code to combine pages of a pdf. The code will combine every two pages together. The issue is when the index is odd, it will not display the last page.

Any tips on how to fix this?

from PyPDF2 import PdfFileReader, PdfFileWriter

output = PdfFileWriter()

file_name = 'test odd.pdf' # ----> Change this to your file you want to combine.
file = PdfFileReader(open(file_name, 'rb'))


for i in range(1, file.getNumPages(), 2):
    page = file.getPage(i-1)
    height = page.mediaBox.getUpperRight_y()
    page_step = file.getPage(i)
    page.mergeTranslatedPage(page_step, 0, -height, expand=True)
    output.addPage(page)


outfile = 'testing odd.pdf' # ----> Change this to the name you want for the outfile.

with open(outfile, 'wb') as file:
    output.write(file)
I'm guessing there is still data in the buffer.
With a normal file you can use flush.
I found this that may apply (addBlankPage), or is related: https://pythonhosted.org/PyPDF2/PdfFileWriter.html
One more that looks promising: https://github.com/mstamy2/PyPDF2/issues/265