How to add "continue on next page" / "continued from next page" to a table?

Category: 
Tags: tablestable headertable footersplit tablecontinue on next pageiText 5

I need to build a table to which I'm adding all the content dynamically by iterating over a list of records. Every record corresponds with a row in a PdfPTable and finally I add this PdfPTable to the Document.

When the table is split, I need to add a header on the next page that explains that this is the next page of a table that started on the previous page. Unfortunately, the writer nor the document give me a correct page number if my content moves on to the next page until the full table content is added to the document. As a result, I don't know when the content is moved on to next page during iteration process. PdfWriter is only showing me the page number before entering the loop. I need to get the updated page number whenever the table's content goes on to next page. I don't need this header to be on all pages. I need it only when the table is split and rows are carried over to the next page.

Posted on StackOverflow on Nov 28, 2012 by degr

I have written an example that produces something like this:

Page 1
Page 1
Page 2
Page 2
Page 3
Page 3

As you can see, there is no header on the first page, there is only a header on the second and third page that says "Table XYZ (Continued)". I even added a footer that says "Continue on next page". As you can see, this footer only appears at the moment the table is split. It isn't present on the last page. This wasn't asked in the question, and it is easy to remove from my code.

You can find the complete code sample here: SimpleTable5

These are the relevant parts:

PdfPTable table = new PdfPTable(5);
table.setWidthPercentage(100);
PdfPCell cell = new PdfPCell(new Phrase("Table XYZ (Continued)"));
cell.setColspan(5);
table.addCell(cell);
cell = new PdfPCell(new Phrase("Continue on next page"));
cell.setColspan(5);
table.addCell(cell);
table.setHeaderRows(2);
table.setFooterRows(1);
table.setSkipFirstHeader(true);
table.setSkipLastFooter(true);
for (int i = 0; i < 350; i++) {
    table.addCell(String.valueOf(i+1));
}
document.add(table);

If you only want a header:

PdfPTable table = new PdfPTable(5);
table.setWidthPercentage(100);
PdfPCell cell = new PdfPCell(new Phrase("Table XYZ (Continued)"));
cell.setColspan(5);
table.addCell(cell);
table.setHeaderRows(1);
table.setSkipFirstHeader(true);
for (int i = 0; i < 350; i++) {
    table.addCell(String.valueOf(i+1));
}
 document.add(table);

The difference with your code, is that you add the following line to avoid that the header appears on the first page:

table.setSkipFirstHeader(true);