如何在表格单元格内的元素中添加注释

2 投票
1 回答
39 浏览
提问于 2025-04-13 20:35

我刚开始学习Python,现在正在使用borb这个PDF库来创建PDF文档。我想做一个目录页,上面有页码,并且这些页码可以链接到对应的页面。以下是我现在的代码:

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)

我尝试在目录表的布局元素中添加链接注释,但出现了一个错误,提示'NoneType'对象没有属性'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 个回答

0

免责声明:我是 borb 的作者

你能试着访问一下 TableCell 里面的 LayoutElement 吗?
这样可能会有效果。它是一个私有属性,叫 _layout_element

撰写回答