Java – iText – avoid last row not to cut tables on page split to next page

itextitextpdfjava

I am working on itext 5 using java. I have pages with mutiple tables with dynamic rows. In some instances, the table last row is splitted into next page with the folowing header. I am using setHeaderRows() and setSkipFirstHeader() to manage continuation of next page. The last row has enough space to fit on earlier page. I would like to fit that last row in same page instead of next page.

For example, on page 1, the last row is splitted into first row of next page. Instead I would like to fit that row in page 1 so save one extra page with all blanks.

I tried using setExtendLastRow(), but its not working. Does anyone know how to fix this problem. I am attaching a working sample code.

public class ProposalItextSplitLastRow {
 public static void main(String[] args) {
    try {
        Document document = new Document();
        document.setPageSize(PageSize.LETTER);
        document.setMargins(16, 14, 14, 14);
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("C:/SplitLastRow.pdf"));
        document.open();
        document.setPageSize(PageSize.LETTER);
        document.setMargins(16, 14, 42, 38);

        for (int m = 1; m < 20; m++) {

            int row = 0;
            PdfPTable table = new PdfPTable(1);
            table.setSpacingAfter(0);
            table.setSpacingBefore(0);
            table.setWidthPercentage(100);

            table.setHeaderRows(1);
            table.setSkipFirstHeader(true);
            add(table, "Header Row continued " + m, BaseColor.LIGHT_GRAY, row++);
            add(table, "Header Row normal " + m, BaseColor.LIGHT_GRAY, row++);

            add(table, "Text Row 1 ", BaseColor.WHITE, row++);
            add(table, "Text Row 2 ", BaseColor.WHITE, row++);
            add(table, "Text Row 3 ", BaseColor.WHITE, row++);

            addPadding(table);

            document.add(table);
        }

        document.close();
    } catch (Exception de) {
        de.printStackTrace();
    }
}

private static void add(PdfPTable table, String text, BaseColor color, int row) {
    PdfPCell pdfCellHeader = new PdfPCell();
    pdfCellHeader.setBackgroundColor(color);
    pdfCellHeader.addElement(new Paragraph(new Phrase(text)));
    table.addCell(pdfCellHeader);
}

private static void addPadding(PdfPTable table) {
    PdfPCell cell = new PdfPCell();
    cell.setFixedHeight(2f);
    cell.setBorder(Rectangle.NO_BORDER);
    cell.setColspan(table.getNumberOfColumns());
    table.addCell(cell);
}
}

Best Answer

you can table.setKeepRowsTogather(true);

table.setHeaderRows(1) as well alongwith it

setKeepRowsTogather() checks if it can keep all the rows in page but splits the rows in case the table spans multiple pages. In that case setHeaderRows(1) will put the header rows again in the next page.

Related Topic