在 ReportLab 中向画布元素添加超链接的最简单方法是什么?

问题描述 投票:0回答:3

我正在使用 ReportLab 使用 Python 制作 pdf。我想向画布添加一个形状,并让该形状充当超链接。使以下示例中的矩形链接到 google.com 的最简单方法是什么?

from reportlab.pdfgen import canvas
from reportlab.lib.units import inch

c = canvas.Canvas("hello.pdf")

# move the origin up and to the left, draw square
c.translate(inch,9*inch)
# How do I make this rectangle link to google.com?
c.rect(inch,inch,1*inch,1*inch, fill=1)

c.showPage()
c.save()
python canvas hyperlink reportlab
3个回答
13
投票

在画布上调用

linkURL

c.linkURL('http://google.com', (inch, inch, 2*inch, 2*inch), relative=1)

矩形是可点击区域,因此您必须将其与绘制的矩形相匹配。参数是两个坐标,两次

x, y
分别代表左下角和右上角。

请参阅此博文中的更多示例:http://www.hoboes.com/Mimsy/hacks/adding-links-to-pdf/


0
投票

为了补充 Martijn 的答案,linkURL 使用“默认”坐标系(即bottom+up/left+right)绘制一个矩形。由于默认画布使用自上而下的坐标,我建议您根据画布高度进行快速修复。


0
投票

为了完整起见...您可以使用

canvas.linkURL()
,但请记住,
rect
中预期的
linkURL
坐标与 canvas.rect() 中的
 不同。

tl:dr; 如果你想在之前绘制的 linkURL

 上使用 
rect
,它会像这样:

c.rect(x, y, w, h) # rect uses width and height c.linkURL(url, (x, y, x+w, y+h)) # linkURL uses the end point's x and y
我对此感到非常困惑,直到我意识到(我到处都有奇怪的重叠和大的链接区域)。

© www.soinside.com 2019 - 2024. All rights reserved.