gpt4 book ai didi

python - 如何在 ReportLab platypus 中使用 BaseDocTemplate 呈现多个页面?

转载 作者:行者123 更新时间:2023-11-28 22:53:48 24 4
gpt4 key购买 nike

我是 ReportLab 的新手,正在尝试使用 Platypus 生成 PDF,其中每个部分都有不同的页面模板(以及不同的页眉和页脚)。如何在不使用 SimpleDocTemplate 的情况下使用 BaseDocTemplate 执行此操作?

我正在尝试下面的代码,但我无法显示框架的内容,除了我直接在 Canvas 上绘制的第一页。为了简洁起见,我删除了每个 PageTemplate 的额外格式以及页眉和页脚代码。

from reportlab.platypus import (BaseDocTemplate, Paragraph, Spacer,
PageBreak, Frame, PageTemplate, NextPageTemplate)
from reportlab.pdfgen import canvas
from reportlab.lib import pagesizes, units, styles, enums

class Report(object):
def __init__(self, stream, sections):
self.stream = stream
self.sections = sections
w, h = pagesizes.A4
self._width = w
self._height = h
self._story = []
self._doc = None
self._canvas = canvas.Canvas(self.stream)
self._stylesheet = styles.getSampleStyleSheet()

def generate(self):
'''Generate the report'''
self._doc = BaseDocTemplate(self.stream,
pagesize=(self._width, self._height),
showBoundary=True
)
# Start with the coverpage, then create a new page for each section.
self.coverpage()
for i, p in enumerate(self.sections):
self.render_section(i, p)
self._doc.build(self._story)
self._canvas.save()

def coverpage(self):
'''Draw the cover page'''
frame = Frame(0, 0, self._width, self._height)
self._doc.addPageTemplates(PageTemplate(id='cover', frames=[frame]))
self._story.append(PageBreak())
# The cover page just has some drawing on the canvas.
self._canvas.saveState()
self._canvas.setFont('Helvetica', 16)
self._canvas.drawCentredString(self._width / 2.0, self._height - 108,
"This is the first page")
self._canvas.restoreState()

def render_section(self, num, text):
'''Put stuff on the canvas that belong to this section.'''
frame = Frame(0, 0, self._width, self._height, showBoundary=1)
self._doc.addPageTemplates(PageTemplate(id='section-%d' % num,
frames=[frame]))
h1 = self._stylesheet['Heading1']
h1.alignment = enums.TA_CENTER
frames = [NextPageTemplate('section-%d' % num),
Paragraph(self.sections[num], h1),
Spacer(1, units.inch * 0.2),
PageBreak()]
self._story.extend(frames)


if __name__ == '__main__':
Report('report.pdf', "Why is this not showing?".split(" ")).generate()

最佳答案

你的答案是here .给定链接上的示例代码非常清楚地说明了如何使用 BaseDocTemplate 显示多个框架。

关于python - 如何在 ReportLab platypus 中使用 BaseDocTemplate 呈现多个页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19002554/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com