How do you add annotation to an element inside a Table Cell

43 Views Asked by At

I'm new to using Python and currently using borb pdf package to create pdf documents. I am trying to build a table of contents page with page numbers that links to the designated page. Here is what my current code looks like:

doc = Document()
    toc_page = Page(*self.page_size)

    doc.add_page(toc_page)

    layout = SingleColumnLayoutWithOverflow(toc_page)
    layout.vertical_margin = Decimal(0)
    layout.horizontal_margin = Decimal(0)

    toc_table = FixedColumnWidthTable(
        number_of_columns=2,
        number_of_rows=self.toc_row_count,
        column_widths=[Decimal(3), Decimal(1)],
    )
    
    section_index = 1

    for section_title, value in self.toc_sections.items():
        page_number = value.get('page_number')
        
        # Add section title
        toc_table.add(
            TableCell(
                Paragraph(
                    f'Section {section_index}: {section_title}',
                    font_size=Decimal(11),
                    padding_top=Decimal(5),
                    padding_bottom=Decimal(5)
                )
            )
        )
        
        # Add page number
        page_num_p = Paragraph(
            f'{int(page_number)}',
            font_size=Decimal(11),
            text_alignment=Alignment.RIGHT,
            horizontal_alignment=Alignment.RIGHT,
            padding_top=Decimal(5),
            padding_bottom=Decimal(5)
        )

        toc_table.add(TableCell(page_num_p))
        section_index += 1
    
    toc_table.no_borders()
    layout.add(toc_table)

I tried adding the link annotation into the toc_table layout element but it's giving me an error about 'NoneType' object has no attribute 'get_x':

toc_page_num_cell = TableCell(page_num_p)
toc_table.add(toc_page_num_cell)

toc_table.add(LinkAnnotation(
   toc_page_num_cell.get_previous_layout_box(),
   page=Decimal(page_number),
   destination_type=DestinationType.X_Y_Z,
   top=Decimal(0),
   left=Decimal(0),
   zoom=Decimal(1)
))
1

There are 1 best solutions below

0
Joris Schellekens On

disclaimer: I am the author of borb

Can you try accessing the LayoutElement inside the TableCell?
That might work. It's a private property as _layout_element.