Free Support Forum - aspose.com

Remove empty/blank pages from the document using C#

This is my code

            AsposeWord.Document document = new AsposeWord.Document(docFilePath);

            foreach (AsposeWord.Section section in document.Sections)
            {
                if (section.ToString(AsposeWord.SaveFormat.Text).Trim() == String.Empty)
                    section.Remove();
            }

            AsposeWord.DocumentBuilder builder = new AsposeWord.DocumentBuilder(document);
            String PageText = "";

            AsposeWordLayout.LayoutCollector lc = new AsposeWordLayout.LayoutCollector(document);

            int pages = lc.GetStartPageIndex(document.LastSection.Body.LastParagraph);

            for (int i = 1; i <= pages; i++)
            {
                ArrayList nodes = GetNodesByPage(i, document);
                foreach (AsposeWord.Paragraph para in nodes)
                {
                    PageText += para.ToString(AsposeWord.SaveFormat.Text).Trim();
                }

                //Empty Page
                if (PageText == "")
                {
                    foreach (AsposeWord.Node node in nodes)
                    {
                        node.Remove();
                    }
                }

                nodes.Clear();
                PageText = "";
            }

            document.Save(docFilePath);
        }

If you need document i can provide that

@ajayvclr

Could you please ZIP and attach your input and expected output Word documents here for our reference? We will then provide you more information about your query.

InputFile.zip (265.3 KB)
CurrentOutput.zip (11.1 KB)
Expected OutPut.zip (264.9 KB)

Please find all files let me know if you have any question.

@ajayvclr

Please use the following code example to get the desired output. Hope this helps you.

Document document = new Document(MyDir + "InputFile.docx");

foreach (Section section in document.Sections)
{
    if (section.ToString(SaveFormat.Text).Trim() == String.Empty && section.GetChildNodes(NodeType.Shape, true).Count == 0)
        section.Remove();
}

DocumentBuilder builder = new DocumentBuilder(document);
String PageText = "";

LayoutCollector lc = new LayoutCollector(document);

int pages = lc.GetStartPageIndex(document.LastSection.Body.LastParagraph);

for (int i = 1; i <= pages; i++)
{
    ArrayList nodes = GetNodesByPage(i, document);
    foreach (Paragraph para in nodes)
    {
        PageText += para.ToString(SaveFormat.Text).Trim();
        Console.WriteLine(para.GetChildNodes(NodeType.Shape, true).Count);
        if (para.GetChildNodes(NodeType.Shape, true).Count > 0)
        {
            PageText += "images";
            break;
        }
    }

    //Empty Page
    if (PageText == "")
    {
        foreach (Node node in nodes)
        {
            node.Remove();
        }
    }

    nodes.Clear();
    PageText = "";
}

document.Save(MyDir + "output.docx");