How to make a simple table in ReportLab
How can I make simple table in ReportLab? I need to make a simple 2x20 t开发者_开发百科able and put in some data. Can someone point me to an example?
The simplest table function:
table = Table(data, colWidths=270, rowHeights=79)
How many columns & end rows depend from tuple of data. All our table functions looks like:
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
This will make table 2X2, and fill it with numbers 1,2,3,4. Then you can make file document. In my case i made HttpResponse what is pretty the same like file.
Just an add on to radtek and Pol's answer:
You can substitute the response
argument to SimpleDocTemplate() with a buffer object like io.BytesIO() like so:
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
This could be useful in cases when you want to convert the PDF object into bytes and then into byte-string to be sent in JSON format:
... # Continuation from above code
buffer.seek(0)
buffer_decoded = io.TextIOWrapper(buffer, encoding='utf-8', errors='ignore').read()
return JsonResponse({
"pdf_bytes": buffer_decoded,
})
Taken from the doc (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
精彩评论