iText

How to write a table header if part of a table is forwarded to the next page?

I want this page to have table header row as well. However, I want this header row only when the table data goes on new page.

I am using PdfWriter to create a PDF document. I am adding a PdfPTable to the PDF document. This table has header row and then actual data rows. If the table is big, then part of it gets carried forward to new page. I want this page to have table header row as well. However, I want this header row only when the table data goes on new page.

Posted on StackOverflow on Sep 15, 2015 by Amit Ware

This is how you create a table with a header row in iText 7:

Java
// table with 2 columns:
Table table = new Table(UnitValue.createPercentArray(2)).useAllAvailableWidth();

// header row:
table.addHeaderCell("Key");
table.addHeaderCell("Value");

// many data rows:
for (int i = 1; i < 51; i++) {
  table.addCell("key: " + i);
  table.addCell("value: " + i);
}

doc.add(table);
C#
 // table with 2 columns:
 Table table = new Table(UnitValue.CreatePercentArray(2)).UseAllAvailableWidth();

 // header row:
 table.AddHeaderCell("Key");
 table.AddHeaderCell("Value");

 // many data rows:
 for (int i = 1; i < 51; i++) {
   table.AddCell("key: " + i);
   table.AddCell("value: " + i);
 }

 doc.Add(table);

In this case, the table needs more than one page. As you used addHeaderCell(), the first row will be repeated:

Repeating header

If you don't want the header to be present on the first page, you have to add a single line: table.setSkipFirstHeader(true);

Java
// table with 2 columns:
Table table = new Table(UnitValue.createPercentArray(2)).useAllAvailableWidth();

// header row:
table.addHeaderCell("Key");
table.addHeaderCell("Value");
table.setSkipFirstHeader(true);

// many data rows:
for (int i = 1; i < 51; i++) {
  table.addCell("key: " + i);
  table.addCell("value: " + i);
}

doc.add(table);
C#
 // table with 2 columns:
 Table table = new Table(UnitValue.CreatePercentArray(2)).UseAllAvailableWidth();

 // header row:
 table.AddHeaderCell("Key");
 table.AddHeaderCell("Value");
 table.SetSkipFirstHeader(true);

 // many data rows:
 for (int i = 1; i < 51; i++) {
   table.AddCell("key: " + i);
   table.AddCell("value: " + i);
 }

 doc.Add(table);

Now the table looks like this:

Repeating header

The above snippets were adapted from HeaderRowRepeated (Java/.NET).

Click How to write a table header if part of a table is forwarded to the next page? | iText 5 PDF Development Guide if you want to see how to answer this question in iText 5.