TocFieldOpts.cs
  1. //
  2. // This code is part of Document Solutions for Word demos.
  3. // Copyright (c) MESCIUS inc. All rights reserved.
  4. //
  5. using System;
  6. using System.IO;
  7. using System.Drawing;
  8. using System.Collections.Generic;
  9. using System.Linq;
  10. using System.Globalization;
  11. using GrapeCity.Documents.Word;
  12. using GrapeCity.Documents.Word.Fields;
  13.  
  14. namespace DsWordWeb.Demos
  15. {
  16. // This sample shows how to add a TOC (Table of Contents) to a Word document,
  17. // and specify its options.
  18. public class TocFieldOpts
  19. {
  20. public GcWordDocument CreateDocx()
  21. {
  22. var doc = new GcWordDocument();
  23.  
  24. // The TocFieldOptions class provides a convenient strong-typed access
  25. // to options specific to the 'TOC' MS Word field:
  26. var tocOpts = new TocFieldOptions(doc);
  27. tocOpts.EntryFormatting.CreateHyperlink = true;
  28. // Include paragraphs formatted only with 'Heading 1', 'Heading 2' or 'Heading 3' styles:
  29. foreach (TocStyleLevel style in tocOpts.Styles)
  30. {
  31. switch (style.Level)
  32. {
  33. case OutlineLevel.Level1:
  34. case OutlineLevel.Level2:
  35. case OutlineLevel.Level3:
  36. style.Collect = true;
  37. break;
  38. default:
  39. style.Collect = false;
  40. break;
  41. }
  42. }
  43.  
  44. // Add TOC and a section break to the document:
  45. var toc = doc.Body.Paragraphs.Add().AddComplexField(tocOpts);
  46. doc.Body.Paragraphs.Last().AddSectionBreak();
  47.  
  48. // Create random content with 3 levels of headers:
  49. var rnd = Util.NewRandom();
  50. for (int i = 0; i < rnd.Next(2, 4); i++)
  51. {
  52. var p = doc.Body.AddParagraph($"This is top-level header {i + 1}", doc.Styles[BuiltInStyleId.Heading1]);
  53. var par = Util.LoremIpsumPar();
  54. doc.Body.AddParagraph(par);
  55. for (int j = 0; j < rnd.Next(3, 5); j++)
  56. {
  57. p = doc.Body.AddParagraph($"This is second-level header {j + 1}", doc.Styles[BuiltInStyleId.Heading2]);
  58. par = Util.LoremIpsumPar();
  59. doc.Body.AddParagraph(par);
  60. for (int k = 0; k < rnd.Next(2, 3); k++)
  61. {
  62. p = doc.Body.AddParagraph($"This is third-level header {k + 1}", doc.Styles[BuiltInStyleId.Heading3]);
  63. par = Util.LoremIpsumPar();
  64. doc.Body.AddParagraph(par);
  65. }
  66. }
  67. }
  68.  
  69. // For reference add a simple page header with page number to the document:
  70. var phdr = doc.Body.Sections.First.Headers[HeaderFooterType.Primary].Body.AddParagraph(doc.Styles[BuiltInStyleId.Closing]);
  71. phdr.AddComplexField(new PageFieldOptions(doc) { NumberFormat = "'Page '0" });
  72.  
  73. // Update fields using a specific culture:
  74. doc.UpdateFields(new GrapeCity.Documents.Word.Layout.WordLayoutSettings() { FontCollection = Util.FontCollection, Culture = CultureInfo.GetCultureInfo("en-US") });
  75.  
  76. // Done:
  77. return doc;
  78. }
  79. }
  80. }
  81.