【发布时间】:2021-06-27 17:03:44
【问题描述】:
下面是我使用 Reportlab 库创建的表格,特别是来自 reportlab.platypus 的 SimpleDocTemplate:
# Data for this example
data = [
['Animal', 'Name', 'Color'],
['Dog', 'Fido', 'Brown'],
['Cat', 'Mittens', 'Black'],
['Fish', 'Bubbles', 'Orange']
]
fileName = 'pdfTable.pdf'
# Using a template to make the PDF
from reportlab.platypus import SimpleDocTemplate # With this, our table will automatically be centered in the document
from reportlab.lib.pagesizes import letter
pdf = SimpleDocTemplate (
fileName,
pagesize=letter
)
# Import table functionality and create table
from reportlab.platypus import Table
table = Table(data)
# Add style
from reportlab.platypus import TableStyle
from reportlab.lib import colors
style = TableStyle([
('BACKGROUND', (0,0), (3,0), colors.green),
('TEXTCOLOR', (0,0), (-1,0), colors.whitesmoke), # The negative one means "go to the last element"
('ALIGN', (0,0), (-1,-1), 'CENTER'),
('FONTNAME', (0,0), (-1,0), 'Courier-Bold'),
('FONTSIZE', (0,0), (-1,0), 14),
('BOTTOMPADDING', (0,0), (-1,0), 12), # 12 = 12 pixels
('BACKGROUND', (0,1), (-1,-1), colors.beige), # Background for the rest of the table (excluding the title row)
])
table.setStyle(style)
elems = []
elems.append(table)
pdf.build(elems)
在 PDF 中生成下表:
我想在文档的其他位置(表格之外)添加文本字符串。通常,我会使用 reportlab.pdfgen 中的“画布”:
from reportlab.pdfgen import canvas
pdf = canvas.Canvas('myFile.pdf')
pdf.drawCentredString(300, 770, 'Title')
但这不适用于 SimpleDocTemplate,我相信它只会创建一个新文档。如何结合表格创建独立的文本字符串?
【问题讨论】: