我正在使用 reportlab 库,我对使用 SimpleDocTemplate 添加图像有疑问。
我有动态内容,我不知道它占用了多少空间。发生的事情是我想在页面底部添加一个徽标(总是在同一个地方)。我这样做的方式是将内容添加到列表中:例如[文本、间隔、表格、间隔、徽标],然后构建它。徽标的位置取决于其他变量。
你能帮我完成这个行为吗?
我知道这可以使用绝对定位来完成(例如在画布类中使用 drawImage),但我不知道如何将我的操作方式与此结合起来。
提前致谢
您可能希望将图像放在页脚中(更接近 axel_ande 的答案)。这样,图像将在每个页面上出现在相同的位置,但只定义一次。
如果要将图像放在页面底部而不是页脚中,则可以尝试TopPadder
wrapper 对象:
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.
我在查看代码时偶然发现了这一点,我能找到的唯一文档是在发行说明中。在我的示例中,我简单地包装了一个表格,因此示例代码是独立的。
希望这可以帮助!
我得到了我生成的报告的标题,就像这段代码一样(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)