Remove Empty Pages from Word document using C# .NET | Page.IsBlank | Delete Page's Blank Nodes from Word Document

can you let me know to detect the node of that specific blank page which can be used to delete from the word doc.
below is the code sample

MemoryStream outputStream = new MemoryStream();
doc.Save(outputStream, Aspose.Words.SaveFormat.Pdf);

        Aspose.Pdf.Document pdfdoc = new Aspose.Pdf.Document(outputStream);
        
        PageCollection _pagecoll = pdfdoc.Pages;
        for(int pg = 1; pg <= _pagecoll.Count;pg++)
        {
            Console.WriteLine(_pagecoll[pg].Number);
            Console.WriteLine(_pagecoll[pg].IsBlank(0.01));
        }

I have word doc, which has blank document which is generated at the runtime, i want to delete those

@sunnydeol1712,

You can try implementing the following workflow:

  • Convert Word document to a temporary PDF in memory by using Aspose.Words for .NET
  • Use Aspose.PDF for .NET API to detect which page numbers are blank/empty in this PDF (see Page.IsBlank Method and PageCollection Class)
  • Use Aspose.Words to remove only those nodes which are present on such blank pages detected in previous step.

Now suppose that by using the Aspose.PDF API you have found that 2, 5, 8, 11, 114, and 117 page numbers are blank or empty. After that you can use the following Aspose.Words code to remove Nodes from these pages of Word document:

Document doc = new Document("E:\\Temp\\sample Word doc\\Sample DOc.docx");
LayoutCollector layoutCollector = new LayoutCollector(doc);

ArrayList list = new ArrayList();
foreach (Node node in doc.GetChildNodes(NodeType.Any, true))
{
    if (layoutCollector.GetNumPagesSpanned(node) == 0)
    {
        int pageIndex = layoutCollector.GetStartPageIndex(node);
        if (pageIndex == 2 || pageIndex == 5 || pageIndex == 8 || pageIndex == 11 || pageIndex == 114 || pageIndex == 117)
        {
            list.Add(node);
        }
    }
}

foreach (Node node in list)
    node.Remove();

doc.Save("E:\\Temp\\sample Word doc\\20.6.docx");