【问题标题】:How to overlay text hyperlink on top of an image using reportlab?如何使用reportlab在图像顶部覆盖文本超链接?
【发布时间】:2018-09-17 11:31:27
【问题描述】:

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

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

我设法创建了嵌入文本的超链接(使用How to add a link to the word using reportlab?),我的电子阅读器可以识别这些超链接,但我没有设法将它们覆盖在图像上。

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

这是我的代码:

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】:

    我终于找到了一个更简单的解决方案,只使用来自鸭嘴兽的框架,并与 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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多