Python Forum
For Loop, over even index - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: For Loop, over even index (/thread-4122.html)



For Loop, over even index - shaynehansen - Jul-24-2017

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)



RE: For Loop, over even index - Larz60+ - Jul-24-2017

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


RE: For Loop, over even index - Larz60+ - Jul-24-2017

One more that looks promising: https://github.com/mstamy2/PyPDF2/issues/265