Python Reportlab 分页

21 投票
1 回答
28346 浏览
提问于 2025-04-18 05:06

我正在尝试用Python的reportlab库生成一个PDF报告。

我的目标是让PDF的第一页只有一个简单的标题和一个没有实际内容的表格。真正的内容将从第二页开始。

在浏览了一些StackOverflow的帖子后,我发现可以使用afterPage()命令来换页。所以,我想出了这样的代码:

from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer,KeepTogether,tables
from reportlab.lib import colors
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.rl_config import defaultPageSize
from reportlab.lib.pagesizes import A4,landscape
from reportlab.lib.units import inch,cm,mm
from reportlab.pdfgen import canvas

PAGE_HEIGHT = defaultPageSize[1]
PAGE_WIDTH = defaultPageSize[0]
styles = getSampleStyleSheet()
style = styles["Normal"]

def myFirstPage(canvas, doc):
    canvas.saveState()
    canvas.setFont('Times-Bold',15)
    canvas.drawCentredString(PAGE_WIDTH/2.0, PAGE_HEIGHT-38, 'Title 1')
    canvas.drawCentredString(PAGE_WIDTH/2.0, PAGE_HEIGHT-58, 'Title 2')

    NormalStyle = tables.TableStyle([
        ('BOX',(0,0),(-1,-1),0.45,colors.blue),
        ('ALIGN',(0,0),(-1,-1),'LEFT'),
        ('BACKGROUND',(0,0),(-1,-1),colors.lightblue)
        ])

    mytable = tables.Table([('test','test'),('test2','test2'),('test3','test3')],
    colWidths = 1* inch,rowHeights= 0.25 *inch,style = NormalStyle)

    mytable.wrapOn(canvas,PAGE_WIDTH ,PAGE_HEIGHT)
    mytable.drawOn(canvas,(doc.width/2)-20,700)

    doc.afterPage()
    canvas.restoreState()

def myLaterPages(canvas, doc):
    canvas.saveState()
    canvas.setFont('Times-Roman', 9)
    canvas.restoreState()

doc = SimpleDocTemplate("myreport.pdf",
                        leftMargin = 0.75*inch,
                        rightMargin = 0.75*inch,
                        topMargin = 1*inch,
                        bottomMargin = 1*inch)

data = "".join(['this is a test' for i in range(200)])
mydata = Paragraph(data,style)
Story = [Spacer(2.5,0.75*inch)]
Story.append(mydata)

doc.build(Story, onFirstPage=myFirstPage, onLaterPages=myLaterPages)

但是,结果是我的标题、表格和内容都被画在了第一页,而afterPage()函数似乎对文档的内容没有任何实际效果。

我该如何修改我的代码,让内容(我代码中的data)从第二页开始呢?

1 个回答

47

你可以用 PageBreak() 来实现这个功能。只需要在你的代码里加上 Story.append(PageBreak()),并且从 reportlab.platypus 这个库里导入它就可以了。

撰写回答