如何在ReportLab中制作简单的表格

18

我该如何在ReportLab中制作简单的表格?我需要制作一个简单的2x20表格并输入一些数据。有人能给我指一个例子吗?

2个回答

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

这将创建一个2x2的表格,并填充数字1、2、3、4。然后您可以创建文件文档。在我的情况下,我创建了HttpResponse,它与文件差不多。


对我来说,它创建了一个完美的表格,但是表格的填充方式有点相反,所以表格看起来是第一行:3 4 第二行:1 2。 - sjjk001

1

对于radtek和Pol的回答,有一个额外的补充:

您可以将SimpleDocTemplate()的response参数替换为像io.BytesIO()这样的缓冲区对象,如下所示:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接