如何使用reportlab覆盖图像顶部的文本超链接?

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

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

我设法使用reportlab.pdfgen和矩形链接这样做,遗憾的是使用的阅读器(电子阅读器)无法识别这种类型的链接。

而不是它,我设法创建文本嵌入式超链接(使用How to add a link to the word using reportlab?),我的电子阅读器识别,但我没有设法将它们叠加在图像上。

我试图使用这篇文章中提供的解决方案(reportlab: add background image by using platypus)将图像用作背景,但它不起作用。当我将文档的pagesize设置为图像的大小时,不显示段落。当我将其设置为比图像大小更大的尺寸时,段落显示在图像上方而不是覆盖它。

这是我的代码:

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:此代码不完整(不会创建多个页面等等),但这只是尝试在图像上叠加文本嵌入式超链接的最小示例。

python pdf reportlab platypus
1个回答
0
投票

我终于找到了一个更简单的解决方案来解决我的问题,只使用platypus的框架,混合了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'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()
© www.soinside.com 2019 - 2024. All rights reserved.