There are times where the contents of a table should not be split across a page. For instance when there is a title above a table, the title and the table should always be kept together on the same page to preserve proper appearance.
There are two separate techniques that are useful to achieve this functionality:
· Allow Row to Break across Pages which is applied to the rows of a table.
· Keep with Next which is applied to paragraphs in table cells.
We will use the table below in our example. By default it has the properties above disabled. Also notice how the content in the middle row is split across the page.
This involves restricting content inside the cells of a row from being split across a page. In Microsoft Word this can found under Table Properties as the option “Allow Row to break across Pages”.
In Aspose.Words this is found under the RowFormat object of a Row as the property RowFormat.AllowBreakAcrossPages.
Example
Shows how to disable rows breaking across pages for every row in a table.
[Java]
// Disable breaking across pages for all rows in the table.
for(Row row : table)
row.getRowFormat().setAllowBreakAcrossPages(false);
The result is the contents of each row are no longer split across the page. The table will only split across the page at the start of a row instead of in the middle of a row.
To stop a table from splitting across the page we need to state that we wish the content contained within the table to stay together. In Microsoft Word this involves selecting the table and enabling “Keep with Next” under Paragraph Format.
In Aspose.Words the technique is the same. Each paragraph inside the cells of the table should have ParagraphFormat.KeepWithNext set to true. The exception is the last paragraph in the table which should be set to false.
Example
Shows how to set a table to stay together on the same page.
[Java]
// To keep a table from breaking across a page we need to enable KeepWithNext
// for every paragraph in the table except for the last paragraphs in the last
// row of the table.
for (Cell cell : (Iterable<Cell>) table.getChildNodes(NodeType.CELL, true))
for (Paragraph para : cell.getParagraphs())
if (!(cell.getParentRow().isLastRow() && para.isEndOfCell()))
para.getParagraphFormat().setKeepWithNext(true);
The table is no longer split across the page and the entire table is moved to the next page instead.