How to resize column to content in ReportLab?

Zeb picture Zeb · Mar 19, 2014 · Viewed 12.4k times · Source

I am working in python using ReportLab. I need to generate report in PDF format. The data is retrieving from the database and insert into table. Here is simple code:

from reportlab.lib import colors
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle
from reportlab.lib.units import inch
doc = SimpleDocTemplate("simple_table.pdf", pagesize=letter)
elements = []

data= [['00', '01', '02', '03', '04'],
       ['10', 'Here is large field retrieve from database', '12', '13', '14'],
       ['20', '21', '22', '23', '24'],
       ['30', '31', '32', 'Here is second value', '34']]
t=Table(data)
columnWidth = 1.9*inch;
for x in range(5):
        t._argW[x]= cellWidth
elements.append(t)
doc.build(elements)

There are three issues:

  1. The lengthy data in a cell overlap on the other cell in a row.
  2. When I increase the column-width manually such as cellWidth = 2.9*inch; , the page is not visible and not scroll from Left-Right
  3. I do not know how to append the data in a cell , mean if the size of the data is large ,it should append to the next line in the same cell.

How I reach this problem?

Answer

Fookatchu picture Fookatchu · Mar 20, 2014

For starters i would not set the column size as you did. just pass Table the colWidths argument like this:

Table(data, colWidths=[1.9*inch] * 5)

Now to your problem. If you don't set the colWidth parameter reportlab will do this for you and space the columns according to your data. If this is not what you want, you can encapsulate your data into Paragraph's, like Bertrand said. Here is an modified example of your code:

from reportlab.lib import colors
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Paragraph
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.units import inch
styles = getSampleStyleSheet()
doc = SimpleDocTemplate("simple_table.pdf", pagesize=letter)
elements = []

data= [['00', '01', '02', '03', '04'],
       ['10', Paragraph('Here is large field retrieve from database', styles['Normal']), '12', '13', '14'],
       ['20', '21', '22', '23', '24'],
       ['30', '31', '32', 'Here is second value', '34']]
t=Table(data)
elements.append(t)
doc.build(elements)

I think you will get the idea.