How to avoid page breaks inside tags in Aspose.words for .NET

Hii

Do you have a solution to avoid these kind of page breaksissue.PNG (51.8 KB)

Currently we are solving that kind of page breaks via CSS. (page-break-after: avoid;)

h1 {
    font-size: 30px;
    color: #1094C8;
    white-space: nowrap;
    font-weight: 700
    page-break-after: avoid;
}

We want to handle it from the code. not only for the h1 tag but also each and every tag. Do you have any solution to avoid that kind of page breaks???

HTML HTML.zip (2.0 KB)
Word document WordDoc.docx (17.3 KB)

@nethmi You can achieve this by setting ParagraphFormat.KeepWithNext and ParagraphFormat.KeepTogether properties of the paragraphs that should appear on the same page.
In your case, the properties must be set for heading paragraph and all paragraphs after the heading except the last (paragraph before the next heading).

sorry I couldn’t get your point. Can you explain that again ??

@nethmi You should set the mentioned properties like shown on the screenshow:

I have created a simple code that demonstrates the basic technique using DocumentVisitor:

Document doc = new Document(@"C:\Temp\in.docx");
doc.Accept(new KeepWithNextVisitor());
doc.Save(@"C:\Temp\out.docx");
private class KeepWithNextVisitor : DocumentVisitor
{
    public override VisitorAction VisitParagraphEnd(Paragraph paragraph)
    {
        if (paragraph.ParagraphFormat.IsHeading)
        {
            if (mPrevParagraph != null)
                mPrevParagraph.ParagraphFormat.KeepWithNext = false;
        }

        paragraph.ParagraphFormat.KeepWithNext = true;
        paragraph.ParagraphFormat.KeepTogether = true;

        mPrevParagraph = paragraph;

        return VisitorAction.Continue;
    }

    private Paragraph mPrevParagraph;
}
1 Like

Thank you very much for your support.

1 Like