如果您的表格可以与页眉分开,我将使用页面模板类来解决它,该类包含一个名为 onPage (BaseDocTemplate) 和 onFirstPage, 和 onLaterPages (SimpleDocTemplate) 的属性。其中一些在用户指南 3.5.36 版的第 70 页上有所提及
让它工作可能有点棘手,所以我在下面包含一些代码作为开始。
from reportlab.lib.units import cm
from reportlab.lib.pagesizes import A4, landscape
from reportlab.platypus import Table, TableStyle
from reportlab.platypus import SimpleDocTemplate
from reportlab.lib import colors
def func(canvas, doc):
canvas.saveState()
canvas.setFont("Helvetica", 12)
(width, height) = landscape(A4)
canvas.drawCentredString(width / 2.0, height - 1.2 * cm, "PAGE TITLE")
canvas.drawRightString(width - 1 * cm, height - 1.2 * cm, "01/01/2021")
canvas.restoreState()
return func
def create_pdf():
story = []
data = [['Data1', 'Data2', 'Data3', 'Data4', 'Data5', 'Data6', 'Data7', 'Data8', 'Data9', 'Data10'],
['0.2', '-0.1', '0', '0', '-0.5', '0.6','0.2', '-0.1', '0', '0']]*200
colwidths = (70)
rowheights = (12)
t = Table(data, colwidths, rowheights)
GRID_STYLE = TableStyle(
[('FONTSIZE', (0, 0), (-1, -1), 5),
('GRID', (0, 0), (-1, -1), 0.5, colors.black),
('ALIGN', (0, 0), (-1, -1), 'CENTER'),
('LEFTPADDING', (0, 0), (-1, -1), 0),
('RIGHTPADDING', (0, 0), (-1, -1), 0),
('TOPPADDING', (0, 0), (-1, -1), 0),
('BOTTOMPADDING', (0, 0), (-1, -1), 2),
('FONTNAME', (0, 0), (-1, -1), 'Helvetica'),
('SIZE', (0, 0), (-1, -1), 8),
('LEADING', (0, 0), (-1, -1), 8.2),
]
)
t.setStyle(GRID_STYLE)
story.append(t)
doc = SimpleDocTemplate('mydoc.pdf', pagesize=landscape(A4), topMargin=50)
doc.build(story, onFirstPage=func, onLaterPages=func)
# ----------------------------------------------------------------------
if __name__ == "__main__":
create_pdf() # Printing the pdf