首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Reportlab中的表的内容太长

Reportlab中的表的内容太长
EN

Stack Overflow用户
提问于 2020-12-01 21:59:32
回答 2查看 46关注 1票数 0

这是我的问题的一个例子。

Click here to check out the problem in my PDF file

代码语言:javascript
复制
    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)
EN

回答 2

Stack Overflow用户

发布于 2020-12-01 22:11:13

我不确定reportlab中是否提供了选项,但您可以使用textwrap模块在外部执行此操作。

输入数据:

代码语言:javascript
复制
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"]]

处理中:

代码语言:javascript
复制
data = [(header, '\n'.join(textwrap.wrap(content, width=70))) for header, content in data]

textwrap.wrap会拆分超过70个字符的行。join使用换行符(\n)将它们相加在一起。

这将导致输出格式:

票数 0
EN

Stack Overflow用户

发布于 2020-12-09 21:54:04

您可以将长文本(或所有文本)包装在一个Paragraph对象中。

为了避免重复使用Pragraph("...", style),我创建了一个函数P(txt)

代码语言:javascript
复制
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)

输出:

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65091907

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档