如何使用reportlab在图像顶部叠加文本超链接?



我正在尝试创建一个包含许多页面的pdf文档。每个页面都包含一个图像,其顶部显示文本,其中包含指向其他页面的超链接。

我已经设法使用reportlab.pdfgen和矩形链接来做到这一点,不幸的是,使用的阅读器(电子阅读器(无法识别这种类型的链接。

取而代之的是,我设法创建了嵌入文本的超链接(使用如何使用reportlab添加单词的链接?(,这些超链接被我的电子阅读器识别,但我没有设法将它们覆盖在图像上。

我尝试使用这篇文章中提供的解决方案(reportlab:使用鸭嘴兽添加背景图像(使用图像作为背景,但它不起作用。当我将文档的页面大小设置为图像大小时,不会显示该段落。当我将其设置为比图像大小更大的尺寸时,该段落显示在图像上方而不是覆盖它。

这是我的代码:

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'pathtotheimage.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:此代码不完整(不会创建多个页面等(,而只是尝试在图像上覆盖嵌入文本超链接的最小示例。

我终于找到了一个更简单的解决方案,只使用鸭嘴兽的框架,混合了pdfgen工具。

溶液:

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'pathtoimage', 0, 0)
# Create a Frame for the paragraph
f = Frame(inch, inch, inch, inch, showBoundary=1)
f.addFromList(items, c)
c.save()

最新更新