【问题标题】:How do I add strings of text to a Reportlab PDF table document?如何将文本字符串添加到 Reportlab PDF 表格文档?
【发布时间】: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,我相信它只会创建一个新文档。如何结合表格创建独立的文本字符串?

【问题讨论】:

    标签: python reportlab


    【解决方案1】:

    reportlab.platypus.SimpleDocTemplate 从 flowables 创建文档。 Flowable 是一块占据一些垂直空间的内容。如果要在表格之前添加标题,只需创建具有标题样式的段落并将其放在表格之前的列表中,如果要在表格之后添加文本,请将其放在之后。如果您想要任意放置的文本,请创建一个函数并将其作为 onFirstPage 参数传递给 SimpleDocTemplate.build

    from reportlab.platypus import Paragraph, Spacer
    from reportlab.lib.styles import getSampleStyleSheet
    from reportlab.lib.units import cm
    
    styles = getSampleStyleSheet()
    
    flowables = [
        Paragraph('Title', styles['Title']),
        table,
        Spacer(1 * cm, 1 * cm),
        Paragraph('text after spacer')
    ]
    
    def onFirstPage(canvas, document):
        canvas.drawCentredString(100, 100, 'Text drawn with onFirstPage')
    
    pdf.build(flowables, onFirstPage=onFirstPage)
    

    【讨论】:

      猜你喜欢
      • 2021-09-13
      • 2017-11-25
      • 2020-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-03
      • 2013-04-04
      相关资源
      最近更新 更多