Assign Dynamic PdfPCell width to dynamically generated PdfPCell

狂风中的少年 提交于 2021-01-29 14:09:50

问题


I am using iTextSharp version 5.4.5.0.

I am trying to print PdfPTable with Multiple PdfPCell. The Number of PdfPCell will be dynamic. So How can I assign width to the dynamically generated 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.

Please help me ?

Thanks.


回答1:


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


来源:https://stackoverflow.com/questions/35550776/assign-dynamic-pdfpcell-width-to-dynamically-generated-pdfpcell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!