How we can remove heading and subheading from word find using gembox. I want to remove heading 1.1.1
Hi,
Heading and subheading are just Paragraph
elements with a specific style.
So what you can do is search for the Paragraph
element of the targeted style and remove it.
For example, something like this:
var document = DocumentModel.Load("input.docx");
string headingName = "heading 3";
string listNumber = "1.1.1";
document.CalculateListItems();
var paragraph = document.GetChildElements(true, ElementType.Paragraph)
.Cast<Paragraph>()
.FirstOrDefault(p =>
p.ParagraphFormat.Style?.Name == headingName &&
p.ListItem.ToString().TrimEnd() == listNumber);
paragraph.Content.Delete();
document.Save("output.docx");
I hope this helps.
Regards,
Mario
Hi Sonu,
Try something like this:
var document = DocumentModel.Load("input.docx");
var headings = document.GetChildElements(true, ElementType.Paragraph)
.Cast<Paragraph>()
.Where(p => p.ParagraphFormat.Style != null && p.ParagraphFormat.Style.Name.StartsWith("heading "))
.ToList();
string listNumber = "1.1";
document.CalculateListItems();
for (int i = 0; i < headings.Count; i++)
{
var heading = headings[i];
if (heading.ListItem.ToString().TrimEnd() != listNumber)
continue;
var start = heading.Content.Start;
// If it's the last heading paragraph, we'll delete the whole content from its start to the end of the document.
// Otherwise, we'll delete the content from the current heading's start to the next heading's start.
var end = i == headings.Count - 1 ?
document.Content.End :
headings[i + 1].Content.Start;
new ContentRange(start, end).Delete();
// If you want to repeat this process to delete some other heading
// you'll need to remove the heading that we just deleted from the headings list
// and recalculate the list numbers.
//headings.RemoveAt(i);
//document.CalculateListItems();
break;
}
document.Save("output.docx");
I hope this helps.
Regards,
Mario
Thanks for your help!.