这是我的问题的一个例子。
Click here to check out the problem in my PDF file
from reportlab.lib import colors
from reportlab.platypus import SimpleDocTemplate, Table
doc = SimpleDocTemplate("test.pdf")
element = []
data = [["Testing Table", ""], ["Short content", "This is a short content."],["Long content", "aaaaaaaaaaaaa This is a super long content which I dont know how to
automaticaly make it fit my A4 page. aaaaaaaaaaaaaaaaaaaa"]]
t = Table(data, style=[("BOX", (0, 1), (-1, -1), 2, colors.black),
("GRID", (0, 1), (-1, -1), 0.5, colors.black),
("ALIGN", (0, 0), (0, -1), "CENTER"),
("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
("ALIGN", (1, 1), (1, -1), "LEFT")])
element.append(t)
doc.build(element)
发布于 2020-12-01 22:11:13
我不确定reportlab
中是否提供了选项,但您可以使用textwrap
模块在外部执行此操作。
输入数据:
data = [["Testing Table", ""],
["Short content", "This is a short content."],
["Long content", "aaaaaaaaaaaaa This is a super long content which I dont know how to automaticaly make it fit my A4 page.aaaaaaaaaaaaaaaaaaaa"]]
处理中:
data = [(header, '\n'.join(textwrap.wrap(content, width=70))) for header, content in data]
textwrap.wrap
会拆分超过70个字符的行。join
使用换行符(\n
)将它们相加在一起。
这将导致输出格式:
发布于 2020-12-09 21:54:04
您可以将长文本(或所有文本)包装在一个Paragraph
对象中。
为了避免重复使用Pragraph("...", style)
,我创建了一个函数P(txt)
。
from reportlab.lib import colors
from reportlab.platypus import SimpleDocTemplate, Table, Paragraph
from reportlab.lib.styles import getSampleStyleSheet
doc = SimpleDocTemplate("test.pdf")
element = []
style = getSampleStyleSheet()['Normal']
def P(txt):
return Paragraph(txt, style)
data = [[P("Testing Table"), ""], [P("Short content"), P("This is a short content.")],
[P("Long content"), P("aaaaaaaaaaaaa This is a super long content which I dont know how to automaticaly make it fit my A4 page. aaaaaaaaaaaaaaaaaaaa")]]
t = Table(data, style=[("BOX", (0, 1), (-1, -1), 2, colors.black),
("GRID", (0, 1), (-1, -1), 0.5, colors.black),
("ALIGN", (0, 0), (0, -1), "CENTER"),
("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
("ALIGN", (1, 1), (1, -1), "LEFT")])
element.append(t)
doc.build(element)
输出:
https://stackoverflow.com/questions/65091907
复制相似问题