问题
Is it possible in Gembox.Document to insert a table to a document and prevent it from being split by a page break but instead move it to the next page if it does not fit on the previous page? I have looked through the samples and the documentation but not found anything.
回答1:
You need to set KeepLinesTogether
and KeepWithNext
properties to true
for paragraphs that are located in that table. For example try the following:
Table table = ...
foreach (ParagraphFormat paragraphFormat in table
.GetChildElements(true, ElementType.Paragraph)
.Cast<Paragraph>()
.Select(p => p.ParagraphFormat))
{
paragraphFormat.KeepLinesTogether = true;
paragraphFormat.KeepWithNext = true;
}
EDIT
The above will work for most cases, however the problem can occur when the Table
element has empty TableCell
elements, that do not have any Paragraph
elements.
For this we need to add an empty Paragraph
element to those TableCell
elements so that we can set the desired formatting (source: Keep Table on same page):
// Get all Paragraph formats in a Table element.
IEnumerable<ParagraphFormat> formats = table
.GetChildElements(true, ElementType.TableCell)
.Cast<TableCell>()
.SelectMany(cell =>
{
if (cell.Blocks.Count == 0)
cell.Blocks.Add(new Paragraph(cell.Document));
return cell.GetChildElements(true, ElementType.Paragraph);
})
.Cast<Paragraph>()
.Select(p => p.ParagraphFormat);
// Set KeepLinesTogether and KeepWithNext properties.
foreach (ParagraphFormat format in formats)
{
format.KeepLinesTogether = true;
format.KeepWithNext = true;
}
来源:https://stackoverflow.com/questions/33612420/gembox-document-prevent-pagebreak-in-table