如何在Python中的Reportlab表中添加复选框?

Cas*_*ter 3 python reportlab

我正在尝试使用reportlab通过python生成PDF。(初学者级)

基本上,我想创建一个表,里面有一个复选框。

例如,参考下面的代码:

    ...
    data =[
        [Paragraph("Option 1",style=custom_para), "anything"],
        [Paragraph("Option 2",style=custom_para), "anything"]
    ]

    t=Table(data, style=style_table, colWidths=[100, 100])
    Story.append(t)
    ...
Run Code Online (Sandbox Code Playgroud)

我已经测试过上面的代码可以正确生成表格。

现在,我想要更进一步的东西,比如:

    ...
    data =[
        [Paragraph("Option 1",style=custom_para), checkbox_1],
        [Paragraph("Option 2",style=custom_para), checkbox_2]
    ]

    t=Table(data, style=style_table, colWidths=[100, 100])
    Story.append(t)
    ...
Run Code Online (Sandbox Code Playgroud)

我应该如何实现checkbox_1、checkbox_2?

实现这一目标最有效的方法是什么?

use*_*837 6

我希望这有帮助。我创建了 checkbox_1 和 checkbox_2 作为该类的实例:

class InteractiveCheckBox(Flowable):
    def __init__(self, text='A Box'):
        Flowable.__init__(self)
        self.text = text
        self.boxsize = 12

    def draw(self):
        self.canv.saveState()
        form = self.canv.acroForm
        form.checkbox(checked=False,
                      buttonStyle='check',
                      name=self.text,
                      tooltip=self.text,
                      relative=True,
                      size=self.boxsize)
        self.canv.restoreState()
        return
Run Code Online (Sandbox Code Playgroud)

然后你可以做类似的事情:

...
checkbox_1 = InteractiveCheckBox('cb1')
checkbox_2 = InteractiveCheckBox('cb2')
data =[
    [Paragraph("Option 1",style=custom_para), checkbox_1],
    [Paragraph("Option 2",style=custom_para), checkbox_2]
]

t=Table(data, style=style_table, colWidths=100])
Story.append(t)
...
Run Code Online (Sandbox Code Playgroud)


Cas*_*ter 5

我找不到完美的解决方案。最后,我通过在表格内绘制一个矩形获得了类似的结果。矩形是用下面的代码实现的:

class flowable_rect(Flowable):
    def __init__(self, width, height):
        Flowable.__init__(self)
        self.width = width
        self.height = height

    def draw(self):
        self.canv.rect(0, 0, self.width, self.height, fill=0)
Run Code Online (Sandbox Code Playgroud)

因此,可以直接调用它,例如:

rect = flowable_rect(6, 6)
t_opt_1=Table([[rect,option_1]], style=style_table, 
             colWidths=[100, 200], hAlign="LEFT")
Run Code Online (Sandbox Code Playgroud)