How to overlay text hyperlink on top of an image using reportlab?

2.4k Views Asked by At

I am trying to create a pdf document with many pages. Each page contains an image on top of which are displayed texts with hyperlinks to other pages.

I have managed to do this using reportlab.pdfgen and rectangle links, unfortunately the reader used (an e-reader) does not recognize this type of links.

Instead of it, I managed to create text embedded hyperlinks (using How to add a link to the word using reportlab?) which are recognizes by my e-reader but I didn't manage to overlay them on an image.

I tried to use the solution provided in this post (reportlab: add background image by using platypus) to use an image as background but it doesn't work. When I set the document's pagesize to the size of the image, the paragraph isn't shown. When I set it to a bigger size than the size of the image, the paragraph is shown above the image not overlaying it.

Here's my code:

from reportlab.lib.styles import getSampleStyleSheet
from reportlab.platypus import BaseDocTemplate, PageTemplate, Frame, Paragraph


def draw_static(canvas, doc):
    # Save the current settings
    canvas.saveState()

    # Draw the image
    canvas.drawImage(r'path\to\the\image.png', 0, 0, width=500, height=500)

    # Restore setting to before function call
    canvas.restoreState()


# Set up a basic template
doc = BaseDocTemplate('test.pdf', pagesize=(500, 500))

# Create a Frame for the Flowables (Paragraphs and such)
frame = Frame(doc.leftMargin, doc.bottomMargin, 500, 500, id='normal')

# Add the Frame to the template and tell the template to call draw_static for each page
template = PageTemplate(id='test', frames=[frame], onPage=draw_static)

# Add the template to the doc
doc.addPageTemplates([template])

# All the default stuff for generating a document
styles = getSampleStyleSheet()
story = []

link = '<link href="http://example.com">Text</link>'

P = Paragraph(link, styles["Normal"])

story.append(P)
doc.build(story)

PS: This code is not complete (doesn't create multiple pages, etc ...) but is just a minimal example for trying to overlay text embedded hyperlinks on an image.

1

There are 1 best solutions below

0
On BEST ANSWER

I finally found a simpler solution to my problem only using frames from platypus, mixed with pdfgen tools.

Solution:

from reportlab.pdfgen import canvas
from reportlab.platypus import Paragraph, Frame
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.units import inch

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

styles = getSampleStyleSheet()
style = styles['Title']

items = []
link = '<link href="http://example.com">Text</link>'
items.append(Paragraph(link, style))

# Drawing the image
c.drawInlineImage(r'path\to\image', 0, 0)

# Create a Frame for the paragraph
f = Frame(inch, inch, inch, inch, showBoundary=1)
f.addFromList(items, c)

c.save()