Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating and displaying data in iText 7 for .NET Table

Tags:

c#

pdf

itext7

It should be simple enough:

public void WritePartsPdf(Document doc)
{
    Table table = new Table(2, true);

    foreach (var part in PartsList)
    {
        Paragraph name = new Paragraph(part.PartName);
        Paragraph length = new Paragraph(part.Length.ToString());

        var cell = new Cell().Add(name);
        var cell2 = new Cell().Add(length);
        cell.Add(cell2);

        table.AddCell(cell);
    }
    doc.Add(table);
}

However my paragraphs are duplicated across all cells, I need the obvious here being one column for name and the other one for length. This is what I got so far:

enter image description here

Help please!

like image 954
makoshichi Avatar asked Nov 20 '25 20:11

makoshichi


1 Answers

So, the "problem" was that setting the table up is even simpler than I initially thought. We don't need nested cells, since I already had a column count set just adding one cell after the other did the trick:

public void WritePartsPdf(Document doc)
{
    Table table = new Table(2, true);
    foreach (var part in PartsList)
    {
        var name = new Paragraph(part.PartName);
        var length = new Paragraph(part.Length.ToString());
        var column1 = new Cell().Add(name);
        var column2 = new Cell().Add(length);
        table.AddCell(column1);
        table.AddCell(column2);
    }
    doc.Add(table);
}

Had to dig through the code here to get the idea: https://developers.itextpdf.com/content/itext-7-jump-start-tutorial-net/chapter-3-using-renderers-and-event-handlers

****UPDATE****

It gets even easier. I was messing around with it and figured out that Paragraph extends BlockElement<T>, so we don't need the cell object at all to add cells to the table:

private void WriteListToPdf(Document doc)
{
    Table table = new Table(2, true);

    foreach (var item in myList)
    {
        table.AddCell(new Paragraph(item.Foo));
        table.AddCell(new Paragraph(item.Bar));
    }
    doc.Add(table);
}

Fortunatelly tableAddCell has an overload for BlockElement<T> ;)

You're still gonna need cell objects if you need multiple lines inside a single cell. Just add a bunch of paragraphs to the cell and then add the cell to the table.

like image 123
makoshichi Avatar answered Nov 22 '25 13:11

makoshichi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!