We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

Remove PageBreak if there is nothing after it

Hi

After inserting a chart I insert a page break.
Sometimes this is the last thing added to the document, so I have a spare page, that I don’t want.
So I want to remove the last page break, but only if has no text following it, I know it will be a paragraph marker because that is always the last thing in a word document.

Thanks

Hi
Graham,


Thanks for your inquiry.

An empty page can be caused by unnecessary empty paragraphs at the end. You can try removing all empty paragraphs from the end of the document. by using the following code:


while (!doc.LastSection.Body.LastParagraph.HasChildNodes)

doc.LastSection.Body.LastParagraph.Remove();


I hope, this will help.

Best Regards,

Thanks Awais
The last line of code that adds items to my document is often
builder.InsertBreak(BreakType.PageBreak);

so my docuement ends with a PageBreak and a final Paragraph mark.

I need to remove that PageBreak.

I might also need to set the font size of the last paragraph to 1point as well (a technique I often use to 'encourage' training paragraphs onto the previous page)

typo - ‘trailing’ not ‘training’
(didn’t see the edit button) doh!

Hi Graham,


Thanks for your inquiry. Please note that when you use builder.InsertBreak(BreakType.PageBreak);
it inserts the ControlChar.PageBreak character in the current paragraph on the current page and moves the rest of the paragraph (including the ControlChar.ParagraphBreak marker) to the next page. If after the page break the paragraph is empty then you can try using the following code snippet to remove such empty pages:

NodeCollection runs = doc.GetChildNodes(NodeType.Run, true);

foreach (Run run in runs)

{

if (run.Text.EndsWith("\f"))

run.Text = run.Text.Replace("\f", "");

}


I hope, this will help.

Best Regards,

Thanks Awis

That removed all of my page breaks!

I have combined the two you gave me, although I think it could be improved, I'm not sure what a 'run' is, but I suspect I don't really need the foreach as I will be in the last paragraph

This works :)...

private void RemoveTrailingPageBreaks(Document doc) {
NodeCollection runs = doc.LastSection.Body.LastParagraph.GetChildNodes(NodeType.Run, true);
foreach(Run run in runs) {
if(run.Text.EndsWith("\f"))
run.Text = run.Text.Replace("\f", "");
}
}

Hi Graham,


Thanks for your inquiry. It is perfect that you managed to achieve what you were looking for. Moreover, for more information about Run nodes, please read the following API link:
http://docs.aspose.com/display/wordsnet/Run+Class

Best Regards,