facebooktwittermenuarrow-up

GemBox Support Forum

DOCX. How to find Headings?

Hi guys.

I have DOCX file with some text and headings.

For example: I want to find the word: “Hello”. Ok, I did it, but I need to show where is a nearest heading?
In my case it must be “Hi”.

Help me please!

Thanks

Hi,

Try this:

var document = DocumentModel.Load("input.docx");
var headings = new List<(int index, Paragraph paragraph)>();

// Get all heading paragraphs and their indexes in parent section.
foreach (Paragraph paragraph in document.Sections
    .SelectMany(sec => sec.Blocks.OfType<Paragraph>())
    .Where(par => par.ParagraphFormat.Style != null &&
            par.ParagraphFormat.Style.Name.Contains("heading")))
{
    int index = paragraph.ParentCollection.IndexOf(paragraph);
    headings.Add((index, paragraph));
}

// Get index of the found content in parent section.
string search = "Hello";
var foundContent = document.Content.Find(search).First();
var foundElement = foundContent.Start.Parent;
while (foundElement.Parent.ElementType != ElementType.Section)
    foundElement = foundElement.Parent;
int foundIndex = foundElement.ParentCollection.IndexOf(foundElement);

var heading = headings.LastOrDefault(h => h.index < foundIndex);
if (heading == default)
    Console.WriteLine($"There is no heading before '{search}' text.");
else
    Console.WriteLine($"Heading paragraph before '{search}' text is:\n" +
        heading.paragraph.Content.ToString().Trim());

Does it solve your issue?

Regards,
Mario