You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用borb将PDF表格单元格内文本对齐至最右侧边界?

解决borb表格单元格文本右对齐问题

问题核心在于你使用的FixedColumnWidthTable默认列宽仅适配内容宽度,导致单元格宽度与文本宽度几乎一致,即使设置了text_alignment=Alignment.RIGHT,视觉上也会呈现居中效果。同时需要确保单元格本身的水平对齐也设置为右对齐。

以下是修正后的代码:

from borb.pdf import Document
from borb.pdf import Page
from borb.pdf import SingleColumnLayout
from borb.pdf import Paragraph
from borb.pdf import PDF
from borb.pdf import Alignment
from borb.pdf import TableCell
from borb.pdf import FixedColumnWidthTable
from decimal import Decimal
from pathlib import Path

pdf = Document()
page = Page()
pdf.add_page(page)
layout = SingleColumnLayout(page)

# 获取页面可用宽度(减去左右边距)
page_width = layout.get_page_width() - layout.get_margin_left() - layout.get_margin_right()

layout.add(
    FixedColumnWidthTable(number_of_columns=1, number_of_rows=1, column_widths=[page_width])
    .add(TableCell(
        Paragraph(
            """
            Report generated on 2022-01-01 at 00:00 am (UTC)
            Date: 01 Jan
            """,
            text_alignment=Alignment.RIGHT,
            padding_top=Decimal(12),
            respect_newlines_in_text=True,
            font_size=Decimal(10)
        ),
        horizontal_alignment=Alignment.RIGHT  # 设置单元格水平对齐为右
    ))
)

with open(Path("output.pdf"), "wb") as pdf_file_handle:
    PDF.dumps(pdf_file_handle, pdf)

关键修改点:

  • 补充FixedColumnWidthTable、Decimal和Path的正确导入
  • 设置表格列宽为页面可用宽度,确保单元格有足够空间展示右对齐效果
  • 用TableCell包裹Paragraph,并设置horizontal_alignment=Alignment.RIGHT,让单元格内容整体右对齐
  • 保留Paragraph的text_alignment=Alignment.RIGHT,确保文本自身在单元格内右对齐

内容的提问来源于stack exchange,提问作者Olga

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 11:20:28