How to Remove Empty Pages of Document using .NET

HI Team , I am using Aspose words to generate a report and saving it as pdf into an stream object ,
the issue is I have conditional blocks in my template , so if the condition is false I am not showing the section, but in that case empty page gets added into the final saved document.
I also referred to : Remove Empty Pages from the Document but even that is not helping

In the template I need a page break before showing the Price details for each of the item inside my data object. but a new empty page gets added at the end .

I have attached the code doc and the test template i am using .
Let me know if you need any other information
codeN.docx (13.6 KB)
Template.docx (16.3 KB)

@nav007

Following code example shows how to remove the empty pages from the document. You can use this code after generating report using LINQ Reporting. Hope this helps you.


    Document doc = new Document(MyDir + @"input.docx");

    // A List will hold blank page numbers
    ArrayList emptyPageNumbers = new ArrayList();
    emptyPageNumbers.Add(-1);

    // Extract each page as a separate Word document
    int totalPages = doc.PageCount;
    for (int i = 0; i < totalPages; i++)
    {
        Document pageDoc = doc.ExtractPages(i, 1);

        // Get text representation of this Page
        string textOfPage = "";
        foreach (Section section in pageDoc.Sections)
            // Lets not consider the content of Headers and Footers
            textOfPage = textOfPage + section.Body.ToString(SaveFormat.Text);

        // if text_of_Page is empty then Page is blank
        if (string.IsNullOrEmpty(textOfPage.Trim()))
            emptyPageNumbers.Add(i);
    }
    emptyPageNumbers.Add(totalPages);

    // Concatenate documents with non-empty pages again
    Document final_Document = (Document)doc.Clone(false);
    final_Document.RemoveAllChildren();

    for (int i = 1; i < emptyPageNumbers.Count; i++)
    {
        int index = (int)emptyPageNumbers[i - 1] + 1;
        int count = (int)emptyPageNumbers[i] - index;

        if (count > 0)
            final_Document.AppendDocument(doc.ExtractPages(index, count), ImportFormatMode.KeepSourceFormatting);
    }

    final_Document.Save(MyDir + @"output.docx");