Skip to content

PdfWriter add_page adds (re)writes old page instead of new #135062

@DominiquePACCO

Description

@DominiquePACCO

Bug report

Bug description:

The purpose of the following code (as a simplification) is to add PDF pages alternatively from 2 different opencv images.
To make the sequence unique, a sequence number is written to each PDF page saved. The PDF is written every 2 images but this is not essential
Herewith I expect a resulting PDF file with 60 pages numbered #1, #2, #3, ... #59, #60.

However the resulting PDF file shows a sequence which in my case starts erratically from the 25th page:
#1, #2, #3, #4, #5, #6, #7, #8, #9, #10, #11, #12, #13, #14, #15, #16, #17, #18, #19, #20, #21, #22, #23, #24, #20, #22, #18, #19, #29, #30.
#31, #32, #33, #34, #35, #36, #37, #38, #39, #40, #36, #37, #34, #35, #32, #33, #30, #31, #19, #29, #21, #18, #24, #20, #55, #23, #57, #23, #59, #20

#25, #26, #27, #28 are missing an have been substituted by #20, #21, #18, #19.
Then everything is back on track to #40
In the remainder of the sequence #55, #57 and #59 are on the right page. The rest shows an 'older' page

The import of PyPDF2 is version 3.0.1

pythonSeq.pdf

    os.remove("pythonSeq.pdf")

pdf_writer = PdfWriter()

image1 = cv2.imread("Picture1.png")
image2 = cv2.imread("Picture2.png")
for seq in range(1,61,2):
    clone = image1.copy()
    cv2.putText(clone,f'Seq#{seq}', (200,30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 0), 3)
    cv2.imwrite("python.jpg",clone)
    pdf_image = Image.open("python.jpg")
    pdf_image.save("python.pdf", format="PDF")
    image_reader = PdfReader("python.pdf")
    pdf_writer.add_page(image_reader.pages[0])

    clone = image2.copy()
    cv2.putText(clone,f'Seq#{seq+1}', (200,30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 0), 3)
    cv2.imwrite("python.jpg",clone)
    pdf_image = Image.open("python.jpg")
    pdf_image.save("python.pdf", format="PDF")
    image_reader = PdfReader("python.pdf")
    pdf_writer.add_page(image_reader.pages[0])

[pythonSeq.pdf](https://github.com/user-attachments/files/20565446/pythonSeq.pdf)

    with open("pythonSeq.pdf", "wb") as pdf_file:
        pdf_writer.write(pdf_file)```


### CPython versions tested on:

3.13

### Operating systems tested on:

Windows

Metadata

Metadata

Assignees

No one assigned

    Labels

    type-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      pFad - Phonifier reborn

      Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

      Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


      Alternative Proxies:

      Alternative Proxy

      pFad Proxy

      pFad v3 Proxy

      pFad v4 Proxy