【问题标题】:How to align multiple tables added to a single table using itextsharp in c#?如何在 c# 中使用 itextsharp 对齐添加到单个表的多个表?
【发布时间】:2020-05-25 20:51:53
【问题描述】:

我创建了一个包含 3 列的表和另一个包含 6 列的表,然后将其添加到另一个表中以使其成为一个表。我想像这样对齐 3 列表的第二列和 6 列表的第二列:

谁能告诉我如何对齐 2 个不同表格的第二列? 我正在使用 iTextsharp 创建表格。

【问题讨论】:

    标签: c# asp.net .net itext pdftables


    【解决方案1】:

    有多种方法可以做到这一点。我会解释两个。

    列宽对齐的两个表格

    设置列宽以获得所需的对齐方式。

    // Table with 3 columns
    PdfPTable table1 = new PdfPTable(3);
    table1.SetTotalWidth(new float[] { 50, 10, 300 });
    
    table1.AddCell("One");
    table1.AddCell(" ");
    table1.AddCell(" ");
    
    // Table with 6 columns
    PdfPTable table2 = new PdfPTable(6);
    // Column 1 and 2 are the same widths as those of table1
    // Width of columns 3-6 sum up to the width of column 3 of table1
    table2.SetTotalWidth(new float[] { 50, 10, 120, 50, 10, 120 });
    for (int row = 0; row < 2; row++)
    {
        for (int column = 0; column < 6; column++)
        {
            table2.AddCell(" ");
        }
    }
    
    doc.Add(table1);
    doc.Add(table2);
    

    ...带有一个外部表

    您提到将两个表添加到另一个表中。如果这是一个明确的要求,它是可能的:

    // Outer table with 1 column
    PdfPTable outer = new PdfPTable(1);
    
    // create table1 and table2 like in the previous example
    
    // Add both tables to the outer table
    outer.AddCell(new PdfPCell(table1));
    outer.AddCell(new PdfPCell(table2));
    
    doc.Add(outer);
    

    视觉效果同上。

    使用 colspans

    除了考虑两个单独的表格之外,您还可以考虑这个表格,其中一些单元格跨越多个列。

    // Table with 6 columns
    PdfPTable table = new PdfPTable(6);
    table.SetWidths(new float[] { 50, 10, 120, 50, 10, 120 });
    
    table.AddCell("Two");
    table.AddCell(" ");
    // Third cell on the first row has a colspan of 4
    PdfPCell cell = new PdfPCell();
    cell.Colspan = 4;
    table.AddCell(cell);
    
    // Second and third row have 6 cells
    for (int row = 0; row < 2; row++)
    {
        for (int column = 0; column < 6; column++)
        {
            table.AddCell(" ");
        }
    }
    
    doc.Add(table);
    

    这种方法的好处是您不必费心保持多个表之间的列宽一致。因为这是一张表,所以列将始终对齐。

    【讨论】:

      猜你喜欢
      • 2015-04-02
      • 2011-10-17
      • 1970-01-01
      • 2011-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多