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)