简体   繁体   English

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

[英]Assign Dynamic PdfPCell width to dynamically generated PdfPCell

I am using iTextSharp version 5.4.5.0. 我正在使用iTextSharp 5.4.5.0版本。

I am trying to print PdfPTable with Multiple PdfPCell. 我正在尝试使用多个PdfPCell打印PdfPTable。 The Number of PdfPCell will be dynamic. PdfPCell的数量将是动态的。 So How can I assign width to the dynamically generated PdfPCell ? 那么,如何为动态生成的PdfPCell分配宽度?

I know how to assign width to Static and Fixed number of Cell. 我知道如何将宽度分配给静态和固定数量的单元格。 But for Dynamic cell, how can I assign width to each of the dynamically generated Cells ? 但是对于动态像元,如何为每个动态生成的像元分配宽度? The Number of PdfPCell is not fixed. PdfPCell的数量不固定。

Please help me ? 请帮我 ?

Thanks. 谢谢。

Even after some back and forth in comments to the original question, I am not entirely sure I understand the question correctly, but let's try: 即使在对原始问题的评论中来回反复后,我也不完全确定我正确理解了该问题,但让我们尝试:

So let us assume you do not know the number of columns beforehand but need to fetch the cells of the first row to get to know the number of columns and their widths. 因此,让我们假设您事先不知道列数,但是需要获取第一行的单元格才能知道列数及其宽度。 In that case you can simply do something like this: 在这种情况下,您可以简单地执行以下操作:

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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM