4

I am trying to generate PDF through python by using reportlab. (beginner level)

Basically, I want to create a table with a checkbox inside.

For example, refer to below code:

    ...
    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)
    ...

I already tested that the above code can generate table correctly.

Now, I want something further, which is something like:

    ...
    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)
    ...

How should I implement the checkbox_1, checkbox_2?

What is the most efficient way to achieve this?

2 Answers 2

7

I hope this helps. I created checkbox_1 and checkbox_2 as instances of the class:

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

Then you can do something like:

...
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)
...
Sign up to request clarification or add additional context in comments.

Comments

5

I could not find a perfect solution. In the end, I achieved similar result by drawing a rectangle inside the table. And the rectangle is implemented with below code:

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)

Thus, it can be called directly such as:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.