How to resize a column to content in ReportLab?

I am working on python using ReportLab. I need to create a report in PDF format. Data is retrieved from the database and inserted into the table. Here is a 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 problems:

  • Long data in a cell overlaps in another cell in the row.
  • When I increase the column width manually, for example cellWidth = 2.9*inch;, the page is not displayed and does not scroll on the left side.
  • I do not know how to add data to a cell, if the data size is large, it should be added to the next row in the same cell.

How can I solve this problem?

+4
source share
1 answer

, . Table colWidths :

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

. colWidth, reportlab . , , Paragraph, . :

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)

, .

+4

Source: https://habr.com/ru/post/1532559/


All Articles