Search code examples
pythonpdfpdf-generationreportlab

How to make a simple table in ReportLab


How can I make simple table in ReportLab? I need to make a simple 2x20 table and put in some data. Can someone point me to an example?


Solution

  • 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.