如何使用 iText 创建 table 以便所有列都具有相同的宽度,而不管内容如何?

How to create a table with iText so that all columns the same width regardless of content?

我用 iText 编写了一些 C# 代码来创建 table 从数据源呈现数字。我遇到的问题是 table 主要包含单个数字,但偶尔可能会有像 100 这样的数字,并且当使用 100 呈现 PDF 时,table 呈现为包含 100 的列更宽,相邻的列更窄。

我做出了一个设计决定,即无论内容如何,​​我都希望所有列的宽度都相同。我已经使用 Cell.SetWidth 指定了列的宽度,但我仍然没有得到我想要的结果。

我需要做什么来确保 table 单元格无论其内容如何都呈现一定的宽度。

下面是呈现三行每行 48 个单元格的示例代码。无论内容如何,​​我只希望单元格呈现相同的大小。目前,如果文本可能会溢出通话或被剪裁,这没关系,但我担心的是使单元格大小相同。

using System;
using System.Collections.Generic;
using System.IO;
using iText.Kernel.Geom;
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Borders;
using iText.Layout.Element;

namespace ConsoleApp3
{
    class Program
    {
        static void Main(string[] args)
        {
            FileStream fs = new FileStream(@"c:\temp\test2.pdf", FileMode.Create);            
            PdfWriter writer = new PdfWriter(fs);
            PdfDocument pdfDocument = new PdfDocument(writer);
            pdfDocument.SetDefaultPageSize(PageSize.LETTER.Rotate());
            Document document = new Document(pdfDocument);
            document.SetMargins(18, 18, 18, 18);

            Table table = new Table(CreateRepeatingValueArray(48, 16f))
                .SetBorder(new SolidBorder(1));

            // Fill our array of values with all zeros, and then make one value 100 to
            // show how column widths are perturbed.
            var values = CreateRepeatingValueArray<byte>(48 * 3, 0);
            values[2] = 100;

            foreach (byte value in values)
            {                               
                Cell cell = new Cell(1, 1)
                    .Add(new Paragraph(Convert.ToString(value)))
                    .SetFontSize(9)
                    .SetWidth(16f)
                    .SetTextAlignment(iText.Layout.Properties.TextAlignment.CENTER);
                table.AddCell(cell);                
            }

            document.Add(table);
            document.Close();
        }        

        static T[] CreateRepeatingValueArray<T>(int length, T value)
        {
            List<T> list = new List<T>(length);
            for (int i = 0; i < length; i += 1)
            {
                list.Add(value);
            }
            return list.ToArray();
        }
    }
}

我找到了解决办法。我创建了一个 Paragraph 对象来保存每个数字,然后设置 Paragraph 对象的宽度。到目前为止,这似乎工作得很好。