Word wrap on report lab PDF table
I'm using the Table of Report Lab library to print a table on a PDF report. I would like to know if it's possible to configure the table to perform an automatic wrapping of the content of a cell.
For example, I have a text that do开发者_高级运维esn't fit on a cell inside a column. I would like that the table performs the wrap automatically adjusting the content of the cells to fit on the columns width. Is it possible?
You can put any flowable in a table element. It is probably good practice to have all table elements as flowables, so they can be styled the same. For your case you will most likely need a Paragraph flowable. eg.
styles = getSampleStyleSheet()
text = Paragraph("long line",
styles['Normal'])
You can put `text' into the data you feed to a table and it will automatically wrap.
My solution, force newline in the string:
def __chopLine(line, maxline):
cant = len(line) / maxline
cant += 1
strline = ""
index = maxline
for i in range(1,cant):
index = maxline * i
strline += "%s\n" %(line[(index-maxline):index])
strline += "%s\n" %(line[index:])
return strline
*whole code of word wrap
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.platypus import Paragraph, Table, TableStyle
from reportlab.lib.enums import TA_JUSTIFY, TA_LEFT, TA_CENTER
from reportlab.lib import colors
# bodytext style used for wrapping data on flowables
styles = getSampleStyleSheet()
styleN = styles["BodyText"]
#used alignment if required
styleN.alignment = TA_LEFT
styleBH = styles["Normal"]
styleBH.alignment = TA_CENTER
hdescrpcion = Paragraph('''<b>descrpcion</b>''', styleBH)
hpartida = Paragraph('''<b>partida</b>''', styleBH)
descrpcion = Paragraph('long long long long long long long long long long long long long long long long long long long long line ', styleN)
partida = Paragraph('1', styleN)
data= [[hdescrpcion, hpartida],
[partida ,descrpcion]]
table = Table(data)
table.setStyle(TableStyle([
('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
('BOX', (0,0), (-1,-1), 0.25, colors.black),
]))
c = canvas.Canvas("a.pdf", pagesize=A4)
table.wrapOn(c, 50, 50)
table.drawOn(c, 100,600)
c.save()
精彩评论