Understanding How to Link to a PDF Using PyPDF2

Asked 2 years ago, Updated 2 years ago, 41 views

Python is trying to implement linking to an existing PDF with a page number in the lower right corner.
I want to jump to the first page when I click on the page number in the lower right corner of a multi-page PDF, but I want to keep the PDF size unchanged after I move it.

I was able to link with the code below, but after jumping, the PDF size is optimized."If I select ""/XYZ"" and adjust zoomArgs, I think the PDF size will not change, but I don't know how to set the argument."If anyone knows, could you tell me?What I wrote is the code below.


from PyPDF2 import PdfFileWriter, PdfFileReader
importio
from reportlab.pdfgen import canvas
from reportlab.lib.pagesize import letter


existing_pdf = PdfFileReader(open(r"C:\test.pdf", "rb")))
output = PdfFileWriter()

pageNum=existing_pdf.getNumPages()


for i in range (pageNum):
    if i == 0:
        packet=io.BytesIO()

        can=canvas.Canvas (packet, pagesize=letter)
        can.drawString (523, 45, "")
        can.save()

        packet.seek(0)
        new_pdf = PdfFileReader(packet)

        # add the "watermark" (which is the new pdf) on the existing page
        page=existing_pdf.getPage(i)
        new_pdf = PdfFileReader(packet)
        page2 = new_pdf.getPage(0)
        page.mergePage(page2)
        output.addPage(page)
    else:
        packet=io.BytesIO()

        can=canvas.Canvas (packet, pagesize=letter)
        can.drawString (523,45, "{}".format(i+1))
        can.save()

        packet.seek(0)
        new_pdf = PdfFileReader(packet)

        # add the "watermark" (which is the new pdf) on the existing page
        page=existing_pdf.getPage(i)
        new_pdf = PdfFileReader(packet)
        page2 = new_pdf.getPage(0)
        page.mergePage(page2)
        output.addPage(page)
        output.addLink (pagenum=i, pagedest=0, rect=[500, 30, 550, 60], border=[0, 0, 0], fit="/XYZ")
# finally, write "output" to a real file

outputStream=open(r"C:\test_new.pdf", "wb")
output.write(outputStream)
outputStream.close()

Thank you for your cooperation.

python python3

2022-09-30 21:42

1 Answers

I did the following and it worked.

output.addLink(i, 0, [500, 30, 550, 60], [0, 0, 0], "/XYZ", 0, 1)

Please refer to the link below.

https://stackoverflow.com/questions/57448075/how-to-write-the-argument-of-fit-in-addlink-pypdf2


2022-09-30 21:42

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.