How to invoke a page break for nested tables?

Category: 
Tags: nested tablestablespage breakiText 7

I have one PdfPTable with one column. One page fits 50 rows. If I add some text data to table (for an example, 300 rows), the report looks fine. When I nest a PdfPTable with a limited number of rows into a cell, all works fine too:

/--------
20 string rows
inner table (20 rows)
10 string rows
/-------
...additional rows
But, when my inner table has more rows, the table splits on the first page, and starts the inner table on the second page:

/---------
20 string rows
whitespace for 30 rows
/---------
inner table (50 rows from 90)
/---------
inner table (40 rows from 90)
..additional data
I need this:

/---------
20 string rows
inner table (30 rows from 90)
/---------
inner table (50 rows from 90)
/---------
inner table (10 rows from 80)
..additional data
Posted on StackOverflow on Nov 28, 2012 by degr

Please take a look at the NestedTables2 example.

Nested table
Nested table

In iText 7 the rows are not splitted by default, hence your code will look like this:

public void createPdf(String dest) throws Exception {
    PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
    Document doc = new Document(pdfDoc);
 
    Table table = new Table(new float[]{1, 15});
    table.setWidthPercent(100);
    for (int i = 1; i <= 20; i++) {
        table.addCell(String.valueOf(i));
        table.addCell("It is not smart to use iText 2.1.7!");
    }
    Table innertable = new Table(new float[]{1, 15});
    innertable.setWidthPercent(100);
    for (int i = 0; i < 90; i++) {
        innertable.addCell(String.valueOf(i + 1));
        innertable.addCell("Upgrade if you're a professional developer!");
    }
    table.addCell("21");
    table.addCell(innertable);
    for (int i = 22; i <= 40; i++) {
        table.addCell(String.valueOf(i));
        table.addCell("It is not smart to use iText 2.1.7!");
    }
    doc.add(table);
 
    doc.close();
}

Note that there are no PdfPTable and PdfPCell classes anymore. We use Table and Cell instead.

Click this link if you want to see how to answer this question in iText 5.