Adding TOC

@alexey.noskov I am trying to add the toc to particular heading 1 below, I used below mention the code but the below code is adding the TOC to above the particular heading kindly help me.

Please find the below mentioned the input and expected output document.
Heading 1.docx (14.6 KB)
Expected_output_Heading.docx (17.1 KB)

string heading = "TABLE OF CONTENTS";

var paragraphs = doc.GetChildNodes(NodeType.Paragraph, true).Cast<Paragraph>();
foreach (Paragraph p in paragraphs)
{
    if (p.ParagraphFormat.StyleIdentifier == StyleIdentifier.Heading1 &&
        p.ToString(SaveFormat.Text).Trim().Equals(heading, StringComparison.InvariantCultureIgnoreCase))
    {
        var tocFields = doc.Range.Fields.Where(f => f.Type == FieldType.FieldTOC);

        if (!tocFields.Any())
        {
            DocumentBuilder builder = new DocumentBuilder(doc);

            builder.InsertTableOfContents("\\o \"1-3\" \\h \\z \\u");

            doc.Styles[StyleIdentifier.Toc1].Font.Color = Color.Blue;
        }
        doc.UpdateFields();
    }
}

@Manasahr You should move DocumentBuilder’s cursor to the target paragraph. Once you create DocumentBuilder it’s cursor is at the beginning of the document. I would modify your code like the following:

bool hasToc = doc.Range.Fields.Where(f => f.Type == FieldType.FieldTOC).Any();

if (!hasToc)
{
    string heading = "TABLE OF CONTENTS";

    Paragraph target = doc.GetChildNodes(NodeType.Paragraph, true).Cast<Paragraph>()
        .Where(p => p.ParagraphFormat.StyleIdentifier == StyleIdentifier.Heading1 &&
            p.ToString(SaveFormat.Text).Trim().Equals(heading, StringComparison.InvariantCultureIgnoreCase))
        .FirstOrDefault();

    if (target != null)
    {
        DocumentBuilder builder = new DocumentBuilder(doc);
        builder.MoveTo(target);
        builder.Writeln();
        builder.InsertTableOfContents("\\o \"1-3\" \\h \\z \\u");
    }
}

doc.UpdateFields();

Your suggested code is working fine but it’s adding numbers 2 and 3 heading 1. In my document don’t have any space. Kindly help me asap.
Please find the below mentioned screen short/.
image.png (5.8 KB)

@Manasahr I see Aspose.Words does not include empty heading paragraph with numbering into the TOC.

We have opened the following new ticket(s) in our internal issue tracking system and will deliver their fixes according to the terms mentioned in Free Support Policies.

Issue ID(s): WORDSNET-24910

You can obtain Paid Support services if you need support on a priority basis, along with the direct access to our Paid Support management team.

The issues you have found earlier (filed as WORDSNET-24910) have been fixed in this Aspose.Words for .NET 23.3 update also available on NuGet.