'How to write the argument of 'fit' in addLink(): PyPDF2
I want to add links to other pages to existing PDF by using PyPDF2. My code works when fit argument is '/Fit', however, I want to use the zoom option. After jump to the added link, pages should be displayed as the size maintained. When fit argument is '/XYZ', how should I supply additional arguments?
from PyPDF2 import PdfFileWriter, PdfFileReader
import io
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes 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)
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)
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",
0, 0, 1
)
outputStream = open(r"C:\test_new.pdf", "wb")
output.write(outputStream)
outputStream.close()
Error messages is below:
output.addLink(pagenum=i,pagedest=0,rect=[500,30,550,60],border = [0,0,0],fit="/XYZ",0,0,1)
^
SyntaxError: positional argument follows keyword argument
Solution 1:[1]
This is actually a Python usage issue, not a PyPDF issue.
You are writing
output.addLink(
pagenum=i,
pagedest=0,
rect=[500, 30, 550, 60],
border=[0, 0, 0],
fit="/XYZ",
0, 0, 1 # <---- here is the issue!
)
Hence the pattern function(foo=bar, 0)
. But Python requires that there are no positional arguments (the zero) after a keyword arguments (foo=bar).
Solution
Although it's not nice, you can make everything positional:
output.addLink(
i,
0,
[500, 30, 550, 60],
[0, 0, 0],
"/XYZ",
0, 0, 1
)
Solution 2:[2]
pdfWriter.addBookmark("Bookmark 1",1, None, None, False, False, '/FitH',1.3)
Please try this snippet, I had this issue too but it is now resolved.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | erukumk |