我该如何在ReportLab中制作简单的表格?我需要制作一个简单的2x20表格并输入一些数据。有人能给我指一个例子吗?
我该如何在ReportLab中制作简单的表格?我需要制作一个简单的2x20表格并输入一些数据。有人能给我指一个例子吗?
最简单的表格函数:
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,它与文件差不多。
对于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
... # Continuation from above code
buffer.seek(0)
buffer_decoded = io.TextIOWrapper(buffer, encoding='utf-8', errors='ignore').read()
return JsonResponse({
"pdf_bytes": buffer_decoded,
})
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