Python reportLab platypus:底部图片

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

我正在使用reportlab库,我怀疑使用SimpleDocTemplate添加图像。

我有动态内容,我不知道它占用了多少空间。会发生什么是我想在页面底部添加一个徽标(总是在同一个地方)。我这样做的方法是将内容添加到列表中:例如[text,spacer,table,spacer,logo]然后构建它。徽标的位置取决于其他变量。

你能帮我完成这个行为吗?

我知道这可以使用绝对定位(例如在画布类中使用drawImage)来完成,但我不知道如何结合我使用它的方式。

提前致谢

python reportlab platypus
2个回答
0
投票

我得到了一个生成报告的标题,我生成的代码就像这个代码一样(PageTemplate为每个文件生成标题。

from reportlab.platypus import Table, TableStyle, Paragraph
from reportlab.platypus.frames import Frame
from reportlab.platypus.doctemplate import PageTemplate, BaseDocTemplate

class MyDocTemplate(BaseDocTemplate):
    def __init__(self, filename, tr, param1, param2, plugin_dir, **kw):
        self.allowSplitting = 0
        BaseDocTemplate.__init__(self, filename, **kw)
        self.tr = tr
        self.plugin_dir = plugin_dir
        frame = Frame(self.leftMargin, self.bottomMargin, self.width, self.height - 2 * cm, id='normal')
        template = PageTemplate(id='test', frames=frame, onPage=partial(self.header, param1=param1, param2=param2))
        self.addPageTemplates(template)

    def header(self, canvas, doc, param1, param2):
        canvas.saveState()
        canvas.drawString(30, 750, self.tr('Simple report from GeoDataFarm'))
        canvas.drawString(30, 733, self.tr('For the growing season of ') + str(param1))
        canvas.drawImage(self.plugin_dir + '\\img\\icon.png', 500, 765, width=50, height=50)
        canvas.drawString(500, 750, 'Generated:')
        canvas.drawString(500, 733, param2)
        canvas.line(30, 723, 580, 723)
        #w, h = content.wrap(doc.width, doc.topMargin)
        #content.drawOn(canvas, doc.leftMargin, doc.height + doc.topMargin - h)
        canvas.restoreState()

doc = MyDocTemplate(report_name, self.tr, self.plugin_dir, '2018', '2018-09-21')
story = []
data_tbl = [['col1', 'col2'],[1, 2],[3, 4]]
table = Table(data_tbl, repeatRows=1, hAlign='LEFT', colWidths=[380/l_heading] * l_heading)
table.setStyle(TableStyle([('FONTSIZE', (0, 0), (l_heading, 0), 16)]))
story.append(table)
doc.build(story)

0
投票

您可能希望将图像放在页脚中(更接近axel_ande的答案)。这样,图像将在每个页面上的相同位置,但只定义一次。

如果要将图像放在页面底部而不是页脚中,可以尝试使用TopPadder包装器对象:

from reportlab.platypus.doctemplate import SimpleDocTemplate
from reportlab.platypus.flowables import TopPadder
from reportlab.platypus import Table, Paragraph

from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib import colors

import numpy as np


document = SimpleDocTemplate('padding_test.pdf')

table = Table(np.random.rand(2,2).tolist(),
              style=[('GRID', (0, 0), (-1, -1), 0.5, colors.black)])
styles = getSampleStyleSheet()
paragraph = Paragraph('Some paragraphs', style=styles['Normal'])

document.build([
    paragraph,
    TopPadder(table),
])

# This should generate a single pdf page with text at the top and a table at the bottom.

当我查看the code时,我偶然发现了这一点,我能找到的唯一文件是在release notes。在我的示例中,我简单地包装了一个表,因此示例代码是独立的。

希望这可以帮助!

© www.soinside.com 2019 - 2024. All rights reserved.