'PyPDF4 doesn't want to merge pdf and reportlab Canvas. Giving an index error even though it shouldn't

In my code I am trying to overlay a reportlab canvas overtop of a pdf as I want to stamp text ontop of the pdf. The code works for when I want to do 1 page at a time. However I would like to do multiple pages at once as I need it for testing purposes.

Here is the code that breaks:

    with open(pdf_fname, 'rb') as pdf_fin:
        input_pdf = PdfFileReader(pdf_fin, strict=False)
        while pg <= 281:
            pdf_page, page_w, page_h = get_page_and_dimensions(input_pdf, pg - 1)

            doc_rot = input_pdf.getPage(pg - 1).get('/Rotate')

            page_loc_pdf = create_page_doc_and_number(pdf_fname, pg, doc_rot)
            pdf_page.mergePage(page_loc_pdf.getPage(pg-1))
            output_pdf.addPage(pdf_page)

            pg += 1

        with open(pdf_out_fname, "wb") as writefile:
            output_pdf.write(writefile)

The while for now is 281 as I am just trying to get the code to work I'll eventually make it work for any sized PDF.

page_loc_pdf is created like this:

def create_generic_canvas_text(text, font_size, color=None, alpha=1.0, left=None, top=None,rotation=None):  # PDF pixels.
    new_pdf = None
    packet = io.BytesIO()
    can = canvas.Canvas(packet, pagesize=letter)

    font_size = 5  # edited font_size

    can.setFont('Courier', font_size)
    if color:
        can.setFillColor(color, alpha=alpha)

    can.rotate(rotation)
    can.drawString(left, top, text)

    # EDIT

    count = 0
    incremental_Value = 10

    while count <= 612:  # width of pdf

        count2 = 0
        while count2 <= 792:  # height of pdf
            can.drawString(count, count2, str(count) + " " + str(count2))
            count2 += incremental_Value

        count += 50




    # END EDIT

    can.save()

    # move to the beginning of the StringIO buffer
    packet.seek(0)
    # create a new PDF with Reportlab
    new_pdf = PdfFileReader(packet)

    return new_pdf

This is the Traceback, I tried looking at pdf.py in PyPDF4 opensource but looking at line 1241 or using control f doesn't take me to that function so I don't know how to properly check it.

Traceback (most recent call last):
  File "C:\Users\User\Desktop\Projects\PDF\PDF.py", line 104, in <module>
    add_grid("test_4.pdf", 1, "test_out.pdf")
  File "C:\Users\User\Desktop\Projects\PDF\PDF.py", line 93, in add_grid
    pdf_page.mergePage(page_loc_pdf.getPage(pg))
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\PyPDF4\pdf.py", line 1241, in getPage
    return self.flattenedPages[pageNumber]
IndexError: list index out of range

All other answers for this question talk about encrypted PDF's my pdf is not encrypted and I have inputted the .isEncrypted() before but nothing changed.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source