python - 添加段落样式reportlab

标签 python pdf

我正在尝试设置报告实验室的段落样式,我在这里定义了一个样式:

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:名称'样式'未定义”

有什么线索吗?

最佳答案

我已经为此苦苦挣扎了几个小时,截至今天,提供的解决方案对我来说不起作用。我在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))

对齐必须按照文档中所示给出数字:

There are four possible values of alignment, defined as constants in the module reportlab.lib.enums. These are TA_LEFT, TA_CENTER or TA_CENTRE, TA_RIGHT and TA_JUSTIFY, with values of 0, 1, 2 and 4 respectively. These do exactly what you would expect.

我发布答案是因为我在任何地方都找不到准确的答案,希望它可以帮助其他人。

关于python - 添加段落样式reportlab,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38557119/

相关文章:

angularjs - 使用 angularjs 在浏览器的新窗口中打开 PDF

python - 将图像插入 pdf 文件

javascript - window.open 不能正常工作

python - jira-python 转换 REST API

python - 如何在 OpenCV/Python 中制作可拖动/可调整的 ROI?

python - 如何在 scikit-learn 管道中向 Keras 网络添加纪元

python - 属性错误 : Menu instance has no attribute '__len__'

r - knitr 没有将 pdf 输出中的数字对齐到中心——替代方案?

python - 加入字典项、键

javascript - 使用 SAPUI5 中响应表的实时数据生成 PDF 文件