python reportlab给Listitem提供格式

时间:2018-01-25 18:36:02

标签: python pdf reportlab

如何在python中为编号的reportlab PDF添加字符。示例:

  1. 第一个元素
  2. 这是第二个元素
  3. 其他:
      a)第一项
      b)第二个

    如何添加"。",")"," - ",我跑了:

    Myitems.append(ListFlowable([  
        ListItem(Paragraph("text", styleLeft),  
        leftIndent=20)],   
        bulletType='a', leftIndent=20, start=1))
    

2 个答案:

答案 0 :(得分:0)

from reportlab.lib.enums import TA_JUSTIFY
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Paragraph
from reportlab.lib.styles import getSampleStyleSheet

doc = SimpleDocTemplate("form_letter.pdf",pagesize=letter,
                        rightMargin=72,leftMargin=72,
                        topMargin=72,bottomMargin=18)

styles = getSampleStyleSheet()

Story=[]

ptext = '''
<seq>) </seq>Some Text<br/>
<seq>) </seq>Some more test Text
'''
Story.append(Paragraph(ptext, styles["Bullet"]))

doc.build(Story)

答案 1 :(得分:0)

我在任何地方都找不到此文档。答案似乎隐藏在来源中:reportlab.platypus.flowables._bulletFormat

def _bulletFormat(value,type='1',format=None):
    if type=='bullet':
        s = _bulletNames.get(value,value)
    else:
        s = _type2formatter[type](int(value))

    if format:
        if isinstance(format,strTypes):
            s = format % s
        elif isinstance(format, collections.Callable):
            s = format(s)
        else:
            raise ValueError('unexpected BulletDrawer format %r' % format)
    return s

我们可以从中得出结论,可以为bulletFormat提供ListFlowable参数,该参数将应用于有序列表中数字/字母的值。我们还可以计算出该参数可以是带有单个字符串参数并返回单个字符串值的Callable(即函数),也可以提供用于%格式设置的字符串。我不喜欢后者,但在大多数情况下可能会很好。

我留下了以下脚本来演示您的需求。我已经添加了一个屏幕快照,它可以在我的环境中为我带来什么。您可能需要使用字体和样式等。

#!/usr/bin/env python3

import unicodedata
from pathlib import Path
from reportlab.platypus import SimpleDocTemplate, Paragraph, ListFlowable, Spacer
from reportlab.lib.styles import getSampleStyleSheet

output = Path.cwd() / Path(__file__).with_suffix(".pdf").name
doc = SimpleDocTemplate(str(output))

styles = getSampleStyleSheet()
normal = styles["Normal"]
body = styles["BodyText"]
h2 = styles["Heading2"]

def second_tetration(value: str):
    try:
        n = int(value)
        try:
            # Only works up to 9 (i.e. single digits)
            exponent = unicodedata.lookup(unicodedata.name(str(n)).replace("DIGIT", "SUPERSCRIPT"))
        except KeyError:
            exponent = None

        if exponent is None:
            return f"{n}^{n} = {n ** n}"
        else:
            return f"{n}{exponent} = {n ** n}"
    except ValueError:
        return value

story = [
    Paragraph("Plain", h2),
    ListFlowable(
        [Paragraph(s, normal) for s in ["One", "Two", "Three"]]
    ),

    Paragraph("With a Full Stop (Period)", h2),
    ListFlowable(
        [Paragraph(s, normal) for s in [
            "First element",
            "This is the second element",
        ]],
        bulletFormat="%s.",  # ←
    ),

    Paragraph("With a Right Parenthesis", h2),
    ListFlowable(
        [Paragraph(s, normal) for s in [
            "First item",
            "Second one",
        ]],
        bulletType="a",
        bulletFormat="%s)",  # ←
    ),
    Paragraph(
        "Note that we must also change the bulletType here to get a sequence using "
        "letters instead of numbers.",
        body,
    ),

    Paragraph("Second Tetration", h2),
    ListFlowable(
        [Paragraph(s, normal) for s in [
            "One to the power one",
            "Two to the power two",
            "Three to the power three",
        ]],
        leftIndent=48,
        bulletFormat=second_tetration,  # ←
    ),
    Paragraph(
        """
        Here the bullet is changed to its second tetration; which is to say 'n to
        the power n'. Unlikely you want this, but a demonstration that your imagination
        is the limit here. Note that to really make use of this functionality you
        will have to play about with fonts and styles to ensure whatever characters
        you're returning have glyphs that can be rendered. Hint: grab a copy of
        <link href="https://www.gnu.org/software/freefont/">GNU FreeFont</link>.
        """,
        body,
    ),

]
doc.build(story)

Screenshot of preceding code

Code as a Gist