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

使用PDF Quest生成PDF时如何使表格单元格与对应表头水平对齐

问题原因

表头与内容行的列宽配置规则不一致是对齐失效的核心原因:

  • 表头的11列中,仅第2列设置了相对权重3,其余9个内容列的相对权重均为默认值1
  • 内容行的11列中,第2、6、10列的相对权重均为3,其余列相对权重为1,二者的列宽计算规则不匹配,最终导致列错位。

修复方法

只要保证表头和每一行内容的列数量、每列的宽度配置(固定值/相对权重)完全一致即可,修正后的代码如下:

void ComposeTable(IContainer container)
{
    var headerStyle = TextStyle.Default.SemiBold();

    container.Decoration(decoration =>
    {
        // 表头:和内容行列配置完全对齐
        decoration.Header().BorderBottom(1).Padding(5).Row(row =>
        {
            row.ConstantColumn(25).Text("#", headerStyle);
            row.RelativeColumn(3).Text("1", headerStyle);
            row.RelativeColumn().AlignRight().Text("2", headerStyle);
            row.RelativeColumn().AlignRight().Text("3", headerStyle);
            row.RelativeColumn().AlignRight().Text("4", headerStyle);
            // 第6列对应内容行的第二个Name列,权重设为3
            row.RelativeColumn(3).AlignRight().Text("5", headerStyle);
            row.RelativeColumn().AlignRight().Text("6", headerStyle);
            row.RelativeColumn().AlignRight().Text("7", headerStyle);
            row.RelativeColumn().AlignRight().Text("8", headerStyle);
            // 第10列对应内容行的第三个Name列,权重设为3
            row.RelativeColumn(3).AlignRight().Text("9", headerStyle);
            row.RelativeColumn().AlignRight().Text("10", headerStyle);
        });

        // 内容
        decoration
            .Content()
            .Stack(column =>
            {
                foreach (var item in Model.Items)
                {
                    column.Item().ShowEntire().BorderBottom(1).BorderColor(Colors.Grey.Lighten2).Padding(5).Row(row =>
                    {
                        row.ConstantColumn(25).Text(Model.Items.IndexOf(item) + 1);
                        row.RelativeColumn(3).Text(item.Name);
                        row.RelativeColumn().AlignRight().Text($"{item.Price}$");
                        row.RelativeColumn().AlignRight().Text(item.Quantity);
                        row.RelativeColumn().AlignRight().Text($"{item.Price * item.Quantity}$");
                        row.RelativeColumn(3).Text(item.Name);
                        row.RelativeColumn().AlignRight().Text($"{item.Price}$");
                        row.RelativeColumn().AlignRight().Text(item.Quantity);
                        row.RelativeColumn().AlignRight().Text($"{item.Price * item.Quantity}$");
                        row.RelativeColumn(3).Text(item.Name);
                        row.RelativeColumn().AlignRight().Text($"{item.Price}$");
                    });
                    
                }
    
            });

    });
}

优化建议

更推荐直接使用库原生的Table组件实现表格,无需手动拼接布局,原生支持自动列对齐、跨页重复表头、边框统一配置,代码可维护性更高。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 04:36:04