I'm getting unexpected results when I try to keep rows in an iText table together. Below is some standalone code that creates a PDF with the results I'm seeing.
FileOutputStream out = new FileOutputStream(new File("table.pdf"));
Document document = new Document(new Rectangle(612, 242));
PdfWriter.getInstance(document, out);
document.open();
PdfPTable table = new PdfPTable(1);
table.setWidthPercentage(100);
for (int i = 0; i < 10; i++) {
PdfPCell cell;
if (i == 9) {
cell = new PdfPCell(new Phrase("Two\nLines"));
}
else {
cell = new PdfPCell(new Phrase(Integer.toString(i)));
}
table.addCell(cell);
}
table.keepRowsTogether(new int[] { 8, 9 });
document.add(table);
document.close();
The example creates a table that is two pixels too small to fit on the first page, forcing the last row onto the next page. I would expect, however, since I added the array using keepRowsTogether
, to see the first eight rows to stay on one page and the last two to stay together on the next page but that isn't the case as shown by the example images below. Instead the seventh row (counting from zero) is also carried over to the next page.
According to the API documentation found here, keepRowsTogether
"Defines which rows should not allow a page break (if possible)." That indicates to me that row seven, which isn't included in the array, should allow a page break.
Does anyone have any ideas how to keep the seventh row from getting carried over to the next page when it definitely fits on the first?
Solution: After talking to Bruno, I realized I misunderstood how keepRowsTogether
works. All I need to do for the example above is change table.keepRowsTogether(new int[] { 8, 9 });
to table.keepRowsTogether(9)
.
I think there's a misunderstanding about what keepRowsTogether()
means. If you use:
table.keepRowsTogether(new int[] { 8, 9 });
You indicate that the table won't split at row 8 or 9. This is consistent with what I see.
Maybe you want something like this: split_at_row.pdf
This PDF is created using SplitRowAtSpecificRow. Instead of keepRowsTogether()
, it uses:
table.setBreakPoints(8);
This means that iText will give preference to splitting the table after row 8 (start counting at 0). You can introduce more than one breakpoint. For instance:
table.setBreakPoints(4, 8, 12);