Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
For Loop, over even index
#1
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)
Reply
#2
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
Reply
#3
One more that looks promising: https://github.com/mstamy2/PyPDF2/issues/265
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Replace for loop to search index position illmattic 5 1,272 Sep-03-2022, 04:04 PM
Last Post: illmattic
  For loop index out of bounds armitron121 2 2,671 Feb-08-2022, 04:23 PM
Last Post: armitron121
  Get all values of for loop with an index BollerwagenIng 2 2,491 Aug-09-2019, 07:58 AM
Last Post: BollerwagenIng
  Index error using pop in nested loop PerksPlus 3 3,382 Mar-28-2019, 03:11 PM
Last Post: ichabod801
  newbie while loop error: IndexError: list assignment index out of range msa969 3 75,049 Mar-31-2017, 12:24 PM
Last Post: msa969

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020