AddTocToDocx.cs
//
// This code is part of Document Solutions for Word demos.
// Copyright (c) MESCIUS inc. All rights reserved.
//
using System;
using System.IO;
using System.Drawing;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
using GrapeCity.Documents.Word;
using GrapeCity.Documents.Word.Fields;

namespace DsWordWeb.Demos
{
    // This sample shows how to insert a TOC field (Table of Contents)
    // into an existing DOCX Word document.
    public class AddTocToDocx
    {
        public GcWordDocument CreateDocx()
        {
            // Load an existing Word document that contains some heading paragraphs into a GcWordDocument:
            var doc = new GcWordDocument();
            doc.Load(Path.Combine("Resources", "WordDocs", "JsFrameworkExcerpt.docx"));

            // Create a TocFieldOptions instance that will be used to insert a TOC field
            // into the loaded document. The TOC will be updated to show the document's
            // Table of Contents based on heading paragraphs present in the original document:
            var tocOpts = new TocFieldOptions(doc);
            // Specify TOC options as needed:
            tocOpts.EntryFormatting.CreateHyperlink = true;

            // The original document starts with the title page, followed by
            // content with the first paragraph having the PageBreakBefore style on.
            // Knowing that, we want to insert the TOC between the title page
            // and the content that follows, so we look for the first paragraph
            // with PageBreakBefore on, and insert the TOC before it:
            var fo = new FindOptions(doc);
            fo.FormattingOptions.ParagraphFormat.PageBreakBefore = true;
            // Empty search pattern because we're looking for a style regardless of text:
            var find = doc.Body.Find("", fo).FirstOrDefault();
            Paragraph para;
            if (find != null)
            {
                // We found the point between the title page and the content:
                para = find.Range.ParentParagraph.GetRange().Paragraphs.Insert("Table of Contents", doc.Styles[BuiltInStyleId.TocHeading], InsertLocation.Before);
                para = para.GetRange().Paragraphs.Insert(InsertLocation.After);
            }
            else
            {
                // Otherwise, just insert the TOC at the beginning of the document:
                para = doc.Body.Paragraphs.Insert("Table of Contents", doc.Styles[BuiltInStyleId.TocHeading], InsertLocation.Start);
            }

            // Add the TOC field with our options, and update it so that it shows the actual document contents:
            para.AddComplexField(tocOpts).Update(new GrapeCity.Documents.Word.Layout.WordLayoutSettings()
            {
                FontCollection = Util.FontCollection, 
                Culture = CultureInfo.GetCultureInfo("en-US")
            });

            // Done:
            return doc;
        }
    }
}