Reputation: 1780
I am using ReportLab to make a pdf using Python. I want to add a shape to the canvas, and have that shape act as a hyperlink. What is the simplest way to make the rectangle in the following example link to 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()
Upvotes: 9
Views: 7566
Reputation: 612
Just for completeness... you can use canvas.linkURL()
, but keep in mind that the rect
coordinates expected in linkURL
are not like the ones in canvas.rect()
.
So, if you want to use linkURL
over a previously drawn rect
, it'll be like this:
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
I got quite confused at this until I realized (I was getting weird overlaps and big linked areas everywhere).
Upvotes: 0
Reputation: 93
To complement the Martijn answer, the linkURL draw a rectangle using the "default" coordinate system, i.e., bottom+up/left+right. Since the default canvas use the top down coord, i suggest you to make a quick fix basing on your canvas height.
Upvotes: 0
Reputation: 1122252
Call linkURL
on the Canvas:
c.linkURL('http://google.com', (inch, inch, 2*inch, 2*inch), relative=1)
The rectangle is the clickable area, so you'd have to match that to the drawn rectangle. The arguments are two coordinates, twice x, y
for the bottom-left and top-right corner.
See more examples in this blog post: http://www.hoboes.com/Mimsy/hacks/adding-links-to-pdf/
Upvotes: 15