How to prevent splitting a table?

Category: 
Tags: tablessplit tableiText 5

I'm developing an app that generates PDF using iText. I have a table that has 3 rows and when this table is near the end of a page, it sometimes puts one row on one page and two rows on the next page. Is there a way to force this table to start on the next page so I can have the full table on the next page?

Posted on StackOverflow on Oct 22, 2015 by user3392572

This was the original answer (the better solution follows):

Please take a look at the Splitting example:

Paragraph p = new Paragraph("Test");
PdfPTable table = new PdfPTable(2);
for (int i = 1; i < 6; i++) {
    table.addCell("key " + i);
    table.addCell("value " + i);
}
for (int i = 0; i < 40; i++) {
    document.add(p);
}
document.add(table);

We have a table with 5 rows, and in this case, we're adding some paragraphs so that the table is added at the end of a page.

By default, iText will try not to split rows, but if the full table doesn't fit, it will forward the rows that don't fit to the next page:

The table splits
The table splits

You want to avoid this behavior: you don't want the table to split.

Knowing that iText will try to keep full rows intact, you can work around this problem by nesting the table you don' want to split inside another table:

PdfPTable nesting = new PdfPTable(1);
PdfPCell cell = new PdfPCell(table);
cell.setBorder(PdfPCell.NO_BORDER);
nesting.addCell(cell);
document.add(nesting);

Now you get this result:

The table doesn't split
The table doesn't split

There was sufficient space on the previous page to render a couple of rows, but as we've wrapped the full table inside a row with a single column, iText will forward the complete table to the next page.

Raf Hens provided an even better solution:

As an alternative to Bruno's approach of nesting the table in a 1-cell table to prevent splitting, you can also use PdfPTable.setKeepTogether(true) to start the table on a new page when it doesn't fit the current page.

Using a similar example:

Paragraph p = new Paragraph("Test");
PdfPTable table = new PdfPTable(2);
for (int i = 1; i < 6; i++) {
    table.addCell("key " + i);
    table.addCell("value " + i);
}
for (int i = 0; i < 40; i++) {
    document.add(p);
}
// Try to keep the table on 1 page
table.setKeepTogether(true);
document.add(table);

Both approaches (nesting in a 1-cell table and using setKeepTogether()) behave exactly the same in my tests. This includes when the table is too large to fit on the new page and still needs to be split, e.g. when adding 50 instead of 5 rows in the example above.