Search code examples
pythondjangoreportlab

Set different size for each columns in Reportlab


I am using Reportlab in python. Now I am trying to customize each column width. Because some of the columns need small width rather than other columns. Is there any way to make each column customizable?

Exported PDF file

Currently from the picture, I would like to increase the width of the Partname column width and set small width for tax, Style p, etc.

views.py

columns = [
        {'title': 'Part No', 'field': 'partno'},
        {'title': 'Part Name', 'field': 'partname'},
        {'title': 'Style P', 'field': 'style'},
        {'title': 'Standard P', 'field': 'standardpack'},
        {'title': 'Unit Per Car', 'field': 'unit'},
        {'title': 'Quantity PCS', 'field': 'quantity'},
        {'title': 'Tax', 'field': 'tax'},
        {'title': 'Unit Price', 'field': 'price'},
        {'title': 'Amount', 'field': 'amount'},
    ]

    table_data = [[col['title'] for col in columns]]
    
        table_row = [str(tr.part.partno),tr.part.partname,
                     tr.part.stylepack, tr.part.standardpack,tr.part.unit, tr.quantity, tr.part.tax, tr.part.price, tr.amount]
        table_data.append(table_row)

    table = Table(table_data, repeatRows=1, colWidths=[150,150])
    table.setStyle(TableStyle([
        ('BOX', (0, 0), (-1, -1), 0.20, colors.dimgrey),
        ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold'),
        ('INNERGRID', (0, 0), (-1, -1), 0.1, colors.black),     
        ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
        ('FONTSIZE', (0, 0), (-1, -1), 10),      
    ]))
    elements.append(table)

Solution

  • You can apply like this :

    from reportlab.lib.units import inch
    
     colWidths=(1.2*inch, 1.2*inch, 2.4*inch, 1.2*inch, 1.2*inch, 1.2*inch, 1.2*inch, 1.2*inch)