如何在ReportLab中创建简单表格

18 投票
2 回答
33350 浏览
提问于 2025-04-16 02:04

我想知道怎么在ReportLab里制作一个简单的表格。我需要做一个2列20行的表格,并且填入一些数据。有没有人能给我一个例子呢?

2 个回答

1

这是对radtek和Pol回答的补充:

你可以用像io.BytesIO()这样的缓冲对象来替代SimpleDocTemplate()中的response参数,像这样:

from reportlab.platypus import SimpleDocTemplate
from reportlab.platypus.tables import Table
import io

cm = 2.54
buffer = io.BytesIO()
doc = SimpleDocTemplate(buffer, rightMargin=0, leftMargin=6.5 * cm, topMargin=0.3 * cm, bottomMargin=0)
... # To be continued below

这样做在你想把PDF对象转换成字节,然后再转成字节字符串以便以JSON格式发送时会很有用:

... # Continuation from above code
buffer.seek(0)
buffer_decoded = io.TextIOWrapper(buffer, encoding='utf-8', errors='ignore').read()

return JsonResponse({
    "pdf_bytes": buffer_decoded,
})

摘自文档(https://www.reportlab.com/docs/reportlab-userguide.pdf):

The required filename can be a string, the name of a file to receive the created PDF document; alternatively it can be an object which has a write method such as aBytesIO or file or socket
22

最简单的表格函数:

table = Table(data, colWidths=270, rowHeights=79)

表格的列数和结束行数取决于数据的元组。我们所有的表格函数看起来都像这样:

from reportlab.platypus import SimpleDocTemplate
from reportlab.platypus.tables import Table
cm = 2.54

def print_pdf(modeladmin, request, queryset):
    response = HttpResponse(mimetype='application/pdf')
    response['Content-Disposition'] = 'attachment; filename=somefilename.pdf'

    elements = []

    doc = SimpleDocTemplate(response, rightMargin=0, leftMargin=6.5 * cm, topMargin=0.3 * cm, bottomMargin=0)

    data=[(1,2),(3,4)]
    table = Table(data, colWidths=270, rowHeights=79)
    elements.append(table)
    doc.build(elements) 
    return response

这段代码会生成一个2行2列的表格,并用数字1、2、3、4填充它。然后你可以创建一个文件文档。在我的例子中,我生成了一个HttpResponse,这和文件差不多。

撰写回答