将动态PdfPCell宽度分配给动态生成的PdfPCell

时间:2016-02-22 10:06:21

标签: c# asp.net itextsharp pdfptable

我正在使用iTextSharp版本5.4.5.0。

我正在尝试使用Multiple PdfPCell打印PdfPTable。 PdfPCell的数量将是动态的。那么如何为动态生成的PdfPCell分配宽度?

我知道如何为静态和固定数量的Cell分配宽度。但对于Dynamic cell,如何为每个动态生成的Cell分配宽度? PdfPCell的数量不固定。

请帮帮我?

感谢。

1 个答案:

答案 0 :(得分:2)

即使在对原始问题的评论中来回反复,我也不能完全确定我是否正确理解了这个问题,但请试试:

因此,我们假设您事先不知道列数,但需要获取第一行的单元格以了解列数及其宽度。在这种情况下,你可以简单地做这样的事情:

public void CreatePdfWithDynamicTable()
{
    using (FileStream output = new FileStream(@"test-results\content\dynamicTable.pdf", FileMode.Create, FileAccess.Write))
    using (Document document = new Document(PageSize.A4))
    {
        PdfWriter writer = PdfWriter.GetInstance(document, output);
        document.Open();

        PdfPTable table = null;
        List<PdfPCell> cells = new List<PdfPCell>();
        List<float> widths = new List<float>();
        for (int row = 1; row < 10; row++)
        {
            // retrieve the cells of the next row and put them into the list "cells"
            ...
            // if this is the first row, determine the widths of these cells and put them into the list "widths"
            ...
            // Now create the table (if it is not yet created)
            if (table == null)
            {
                table = new PdfPTable(widths.Count);
                table.SetWidths(widths.ToArray());
            }
            // Fill the table row
            foreach (PdfPCell cell in cells)
                table.AddCell(cell);
            cells.Clear();
        }

        document.Add(table);
    }
}
相关问题