如何在ReportLab中制作简单的表格?我需要制作一个简单的2x20表并输入一些数据。有人能指点我一个例子吗?
答案 0 :(得分:11)
最简单的表函数:
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,就像文件一样。
答案 1 :(得分:0)
只是对 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