//// This code is part of Document Solutions for Word demos.// Copyright (c) MESCIUS inc. All rights reserved.//usingSystem.IO;usingSystem.Linq;usingSystem.Globalization;usingGrapeCity.Documents.Word;usingGrapeCity.Documents.Word.Fields; namespaceDsWordWeb.Demos{// This sample shows how to insert a TOC (Table of Contents) field// into an existing DOCX Word document.publicclassAddTocToDocx {publicGcWordDocumentCreateDocx() {// Load an existing Word document that contains some heading paragraphs into a GcWordDocument:var doc = newGcWordDocument(); 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 = newTocFieldOptions(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 = newFindOptions(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(newGrapeCity.Documents.Word.Layout.WordLayoutSettings() {FontCollection = Util.FontCollection, Culture = CultureInfo.GetCultureInfo("en-US") }); // Done:return doc; } }}