iText pdf library
Website search

How to prevent splitting a table?

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 

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);

Now you get this result:

The table doesn
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 

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.

Ready to use iText?

Try our iText 7 Library and add-ons FREE for 30 days. Test your proof of concept, and see if our solution is right for you.

Get my FREE trial

Still have questions? 

We're happy to answer your questions. Reach out to us and we'll get back to you shortly.

Contact us
Stay updated

Join 11,000+ subscribers and become an iText PDF expert by staying up to date with our new products, updates, tips, technical solutions and happenings.

Subscribe Now