添加段落样式reportlab。

6

我正在尝试为报告实验设置段落样式,这是我定义的样式:

def stylesheet():
    styles= {
        'default': ParagraphStyle(
            'default',
            fontName='Arial',
            fontSize=16,
            leading=12,
            leftIndent=0,
            rightIndent=0,
            firstLineIndent=0,
            alignment=TA_LEFT,
            spaceBefore=0,
            spaceAfter=0,
            bulletFontName='Arial',
            bulletFontSize=10,
            bulletIndent=0,
            textColor= black,
            backColor=None,
            wordWrap=None,
            borderWidth= 0,
            borderPadding= 0,
            borderColor= None,
            borderRadius= None,
            allowWidows= 1,
            allowOrphans= 0,
            textTransform=None,  # 'uppercase' | 'lowercase' | None
            endDots=None,         
            splitLongWords=1,
        ),
    }

然后我就这样打印它

   pdf = PDFDocument(carte)
    pdf.init_report()
    pdf.p(str(row))
    pdf.generate()

这会产生未经格式化的输出

当我尝试时

pdf = PDFDocument(carte)
pdf.init_report()
pdf.p(str(row), default)
pdf.generate()

将默认样式应用于文本时,出现“NameError: name 'styles' is not defined”错误。有什么线索吗?

"Reportlab" 不同于 "PDFDocument" ... "PDFDocument" 只是 "Reportlab" 的简化版本。 "Reportlab" 的功能要强大得多。 - B8vrede
2个回答

9

我已经为此努力了几个小时,截至今天,提供的解决方案对我没有用。我在programcreek上找到了另一个几乎可以的解决方案。稍加修改后,这个解决方案奏效了:

#First you need to instantiate 'getSampleStyleSheet()'
from reportlab.lib.styles import (ParagraphStyle, getSampleStyleSheet)
style = getSampleStyleSheet()
yourStyle = ParagraphStyle('yourtitle',
                           fontName="Helvetica-Bold",
                           fontSize=16,
                           parent=style['Heading2'],
                           alignment=1,
                           spaceAfter=14)

要使用它,只需像这样调用yourStyle

Story.append(Paragraph("Whatever printed with yourStyle", yourStyle))

在文档中指定一个数字作为对齐方式:

有四个可能的对齐方式,定义在reportlab.lib.enums模块的常量中。这些值分别为TA_LEFT(左对齐)、TA_CENTER或TA_CENTRE(居中对齐)、TA_RIGHT(右对齐)和TA_JUSTIFY(两端对齐),其值分别为0、1、2和4。它们正是您所期望的效果。

我发布这篇回答,因为我在任何地方都找不到精确的答案,希望它能帮助其他人。


太好了!我已经找了一个小时了!第7行有个小错,parent=styles['Heading2'], 应该是 parent=style['Heading2'], - theQuantumMechanic
你说得对。我刚刚纠正了它。很高兴它有帮助。 - Arturo Mendes

6
尝试使用reportlab,将以下代码添加到您现有的代码中:
from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet
from reportlab.lib.enums import TA_LEFT
from reportlab.lib.colors import black

styles = getSampleStyleSheet()
styles['small'] = ParagraphStyle(
   'small',
    parent=styles['default'],
    fontSize=8,
    leading=8,
)

paragraphs.append(Paragraph('Text with default style<br/>', styles['default']))
paragraphs.append(Paragraph('Text with small style', styles['small']))

样式是什么,它来自哪里?找不到styles['default']。我们需要创建它吗? - makkasi
我会这样写:from reportlab.lib.styles import getSampleStyleSheet... styles = getSampleStyleSheet() - MikeHoss

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接