Theo
Theo

Reputation: 3

Add cells to table vertically with foreach

When I add a cell to the table it is added to the next column.

Is there a way to add the rows first or add values more flexible? Im a beginner so I don't know much about this.

This is my code:

Document document = new Document(PageSize.A3, 50, 50, 25, 25);
MemoryStream PDFData = new MemoryStream();
PdfWriter PDFWriter = PdfWriter.GetInstance(document, PDFData);
document.Open();

PdfPTable table = new PdfPTable(testTimes);
table.DefaultCell.Border = 1;
table.HorizontalAlignment = 0;

table.WidthPercentage = 100f;

foreach (Test test in tests)
{
    switch (test.type)
    {
        case 3:
            //new Column (fail)
            PdfPCell type = new PdfPCell(new Phrase(TestType.Aimatologikes.ToString()));
            table.AddCell(type);

            PdfPCell data = new PdfPCell(new Phrase("values"));
            foreach (TestData testdata in test.TestDatas)
            {
                //Rows
                table.AddCell(data);
            }

            break;
    }
}

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

This is the result:

enter image description here

And I want to separate columns below second foreach. Is this posible?

Upvotes: 0

Views: 512

Answers (1)

Joris Schellekens
Joris Schellekens

Reputation: 9012

Two suggestions:

  • First, update your code to use iText 7 (if possible). If you are starting a new project it makes sense for you to use the latest version of the API
  • Second, (as suggested by @mkl) write an intermediary datastructure that will act as a logical view upon your Table object

Allow me to explain.
Let's call this intermediary object EasyTable.

EasyTable needs to do a few things:

  • Allow you to set a specific PdfObject at given coordinates
  • Change the PdfObject at given coordinates
  • Calculate the number of rows
  • Calculate the number of columns
  • Provide a convenient method to get all cells (including possible blanks) in a row by row fashion

To do this, you could easily implement EasyTable to use a Map. This way you can map Point objects to PdfObject. You can calculate the number of rows by iterating over all keys and finding the maximum Y value. Similar for number of columns.

Upvotes: 1

Related Questions