Search code examples
c#winformsitextwindows-forms-designeritext7

C# PDF table add row in wrong position


[EDIT due to misunderstanding of the answer]

I'm doing a simple program in C# with PDF file creation with iText7. In this PDF i'm adding a table whose first cell starts at a certain position in the file.

I don't know if I set the position correctly, but everytime I add another cell with tab.StartNewRow() the resulting new table is repositioned taking THAT last cell as position reference, putting the previously added cells from that point up, while I want to add the cells from that point down.

Which method should I use? That's my code: Previously I set the position of the first table cell using tab1.SetFixedPosition(20, heigh, width);

and then, in order to add the other cells:

if (mylistbox.Items.Count > 0)
  {
     tab1.AddCell("FIRST CELL");
     tab1.StartNewRow();
     for (int i = 0; i < mylistbox.Items.Count; i++)
        {
          tab1.AddCell(mylistbox.Items[i].ToString());
          tab1.StartNewRow();
        }
        doc.Add(tab1);
  }

[EDIT #2] in order to explain my issue better

I have to put 5 tables, which have to grow from a certain point DOWN, positioned at equal distances, same height and width in the doc. This image explains how it should result:

pdfExample


Solution

  • In a WPF application, I have a ListBox with 5 items, numbered 1 through 5. This should be very similar to WinForms.

    The CreatePercentArray takes a size which is equal to the amount of columns in a row.

    An interesting article about tables: link

      private void CreateListBoxTable(Document pdfDoc)
            {
                // Create an array where each item has an equal width, and use the entire pdf width
                // The CreatePercentArray takes a size which is equal to the amount of columns in a row
                // By using percentages, they will automatically adapt
                // Use CreatePointArray for exacter measurements
                var table = new Table(UnitValue.CreatePercentArray(2)).UseAllAvailableWidth();
    
                if (!MyListBox.Items.IsEmpty)
                {
                    foreach (var listBoxItem in MyListBox.Items)
                    {
                        table.AddCell(((ListBoxItem) listBoxItem).Content.ToString());
                    }
                }
                // Adds table to document
                pdfDoc.Add(table);
                // Closes document
                pdfDoc.Close();
            }
    

    output