Aspose word .NET remove header footer where content is empty with bookmark

I am using below code to remove content from page , it is working fine however the page is empty but the header footer is still displayed.

if (bookmarkExists && !isVisible)
{
    Bookmark bookmark = doc.Range.Bookmarks[bookmarkName];

    // Get the nodes in the bookmark's range
    Node startNode = bookmark.BookmarkStart;
    Node endNode = bookmark.BookmarkEnd;

    // Start iterating from the start node
    Node currentNode = startNode.NextPreOrder(doc);
    while (currentNode != null && !currentNode.Equals(endNode))
    {
        Node nextNode = currentNode.NextPreOrder(doc); // Save the next node before potentially removing the current one

        // Check if the current node is a paragraph and is empty
        if (currentNode.NodeType == NodeType.Paragraph)
        {
            Paragraph paragraph = (Paragraph)currentNode;
            if (string.IsNullOrWhiteSpace(paragraph.ToString(SaveFormat.Text)) && !paragraph.HasChildNodes)
            {
                paragraph.Remove(); // Remove the empty paragraph
            }
        }

        currentNode = nextNode;
    }

    // Clear the bookmark content
    doc.Range.Bookmarks[bookmarkName].Text = "";

    // Use LayoutCollector to check if the page is empty
    Aspose.Words.Layout.LayoutCollector layoutCollector = new Aspose.Words.Layout.LayoutCollector(doc);
    int bookmarkPageIndex = layoutCollector.GetStartPageIndex(bookmark.BookmarkStart);

    bool isPageEmpty = true;

    // Check if any content exists on the same page
    foreach (Node node in doc.GetChildNodes(NodeType.Any, true))
    {
        if (layoutCollector.GetStartPageIndex(node) == bookmarkPageIndex)
        {
            // Skip header, footer, and shapes while checking
            if (node.NodeType != NodeType.HeaderFooter && node.NodeType != NodeType.Shape)
            {
                isPageEmpty = false;
                break;
            }
        }
    }

    if (isPageEmpty)
    {
        // Remove headers and footers of the section
        Section sectionWithBookmark = bookmark.BookmarkStart.GetAncestor(NodeType.Section) as Section;
        if (sectionWithBookmark != null && sectionWithBookmark.HeadersFooters != null)
        {
            sectionWithBookmark.HeadersFooters.Clear();
        }

        // Remove shapes on the page
        foreach (Aspose.Words.Drawing.Shape shape in doc.GetChildNodes(NodeType.Shape, true))
        {
            if (layoutCollector.GetStartPageIndex(shape) == bookmarkPageIndex)
            {
                shape.Remove();
            }
        }

        // Remove section breaks and page breaks for the same page
        foreach (Node node in doc.GetChildNodes(NodeType.Any, true))
        {
            int nodePageIndex = layoutCollector.GetStartPageIndex(node);
            if (nodePageIndex == bookmarkPageIndex)
            {
                if (node.NodeType == NodeType.Section)
                {
                    node.Remove(); // Remove section break
                }
                else if (node.NodeType == NodeType.Paragraph)
                {
                    Paragraph paragraph = (Paragraph)node;
                    if (paragraph.ParagraphFormat.PageBreakBefore)
                    {
                        paragraph.ParagraphFormat.PageBreakBefore = false; // Remove page break
                    }

                    foreach (Run run in paragraph.Runs)
                    {
                        if (run.Text.Contains(ControlChar.PageBreak) || run.Text.Contains(ControlChar.SectionBreak))
                        {
                            run.Text = run.Text.Replace(ControlChar.PageBreak, "")
                                               .Replace(ControlChar.SectionBreak, ""); // Remove page/section breaks
                        }
                    }
                }
            }
        }
    }
}

I am attching the word file for reference.
Testdd.docx (84.7 KB)

@SachinSingh

To remove headers and footers from a Word document when the content is empty, you can utilize the HeaderFooter.Remove method or clear all headers and footers in a section using the HeaderFooterCollection.Clear method.

In your case, after checking if the page is empty, you can remove the headers and footers associated with the section containing the bookmark. Here’s a simplified approach based on your existing code:

  1. Check if the page is empty: You already have this logic in place.
  2. Remove headers and footers: If the page is empty, you can clear the headers and footers for the section.

Here’s a code snippet that demonstrates how to achieve this:

// Assuming 'bookmark' is your existing bookmark
Section sectionWithBookmark = bookmark.BookmarkStart.GetAncestor(NodeType.Section) as Section;
if (sectionWithBookmark != null && sectionWithBookmark.HeadersFooters != null)
{
    // Clear all headers and footers in the section
    sectionWithBookmark.HeadersFooters.Clear();
}

This code will effectively remove all headers and footers from the section where the bookmark is located, ensuring that they do not display when the content is empty.

For more detailed information on managing headers and footers in Aspose.Words, you can refer to the official documentation on removing headers and footers here [1].

If you need further assistance or have specific scenarios, feel free to ask!

Sources:
[1]: Remove Headers and Footers from a Word Document - Aspose Documentation

This is removing the header footer from all the pages, i don’t want that.

@SachinSingh MS Word documents are flow by their nature, so there is no concept of “Page”. The consumer applications reflows the document content into pages on the fly. Headers/Footers in MS word documents are applied to sections. Please see output documentation to lean more about Aspose.Words Document object Model:
https://docs.aspose.com/words/net/aspose-words-document-object-model/

If your goal is to remove empty pages from the document, you can use a built-in Document.RemoveBlankPages method.

My organization is using older version of aspose word so i don’t have access to the Document.RemoveBlankPages method, can you please provide me some working solution for older versions.

@SachinSingh As you may know, MS Word documents are not fixed page, they have flow nature, more like HTML. So, there is no easy way to determine where page starts or ends and no easy way to determine whether some particular page is blank. However, there are few options to set an explicit page break in Word document. For example,

If you delete such explicit page breaks from your document, this might help you to get rid blank pages.

If possible, could you please save and attach your document before removing blank pages from it? We will check it and determine what causes a blank page in your particular case.