TocFieldOpts.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 add a TOC (Table of Contents) to a Word document,
- // and specify its options.
- public class TocFieldOpts
- {
- public GcWordDocument CreateDocx()
- {
- var doc = new GcWordDocument();
-
- // The TocFieldOptions class provides a convenient strong-typed access
- // to options specific to the 'TOC' MS Word field:
- var tocOpts = new TocFieldOptions(doc);
- tocOpts.EntryFormatting.CreateHyperlink = true;
- // Include paragraphs formatted only with 'Heading 1', 'Heading 2' or 'Heading 3' styles:
- foreach (TocStyleLevel style in tocOpts.Styles)
- {
- switch (style.Level)
- {
- case OutlineLevel.Level1:
- case OutlineLevel.Level2:
- case OutlineLevel.Level3:
- style.Collect = true;
- break;
- default:
- style.Collect = false;
- break;
- }
- }
-
- // Add TOC and a section break to the document:
- var toc = doc.Body.Paragraphs.Add().AddComplexField(tocOpts);
- doc.Body.Paragraphs.Last().AddSectionBreak();
-
- // Create random content with 3 levels of headers:
- var rnd = Util.NewRandom();
- for (int i = 0; i < rnd.Next(2, 4); i++)
- {
- var p = doc.Body.AddParagraph($"This is top-level header {i + 1}", doc.Styles[BuiltInStyleId.Heading1]);
- var par = Util.LoremIpsumPar();
- doc.Body.AddParagraph(par);
- for (int j = 0; j < rnd.Next(3, 5); j++)
- {
- p = doc.Body.AddParagraph($"This is second-level header {j + 1}", doc.Styles[BuiltInStyleId.Heading2]);
- par = Util.LoremIpsumPar();
- doc.Body.AddParagraph(par);
- for (int k = 0; k < rnd.Next(2, 3); k++)
- {
- p = doc.Body.AddParagraph($"This is third-level header {k + 1}", doc.Styles[BuiltInStyleId.Heading3]);
- par = Util.LoremIpsumPar();
- doc.Body.AddParagraph(par);
- }
- }
- }
-
- // For reference add a simple page header with page number to the document:
- var phdr = doc.Body.Sections.First.Headers[HeaderFooterType.Primary].Body.AddParagraph(doc.Styles[BuiltInStyleId.Closing]);
- phdr.AddComplexField(new PageFieldOptions(doc) { NumberFormat = "'Page '0" });
-
- // Update fields using a specific culture:
- doc.UpdateFields(new GrapeCity.Documents.Word.Layout.WordLayoutSettings() { FontCollection = Util.FontCollection, Culture = CultureInfo.GetCultureInfo("en-US") });
-
- // Done:
- return doc;
- }
- }
- }
-