AddTocToDocx.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 insert a TOC field (Table of Contents)
  17. // into an existing DOCX Word document.
  18. public class AddTocToDocx
  19. {
  20. public GcWordDocument CreateDocx()
  21. {
  22. // Load an existing Word document that contains some heading paragraphs into a GcWordDocument:
  23. var doc = new GcWordDocument();
  24. doc.Load(Path.Combine("Resources", "WordDocs", "JsFrameworkExcerpt.docx"));
  25.  
  26. // Create a TocFieldOptions instance that will be used to insert a TOC field
  27. // into the loaded document. The TOC will be updated to show the document's
  28. // Table of Contents based on heading paragraphs present in the original document:
  29. var tocOpts = new TocFieldOptions(doc);
  30. // Specify TOC options as needed:
  31. tocOpts.EntryFormatting.CreateHyperlink = true;
  32.  
  33. // The original document starts with the title page, followed by
  34. // content with the first paragraph having the PageBreakBefore style on.
  35. // Knowing that, we want to insert the TOC between the title page
  36. // and the content that follows, so we look for the first paragraph
  37. // with PageBreakBefore on, and insert the TOC before it:
  38. var fo = new FindOptions(doc);
  39. fo.FormattingOptions.ParagraphFormat.PageBreakBefore = true;
  40. // Empty search pattern because we're looking for a style regardless of text:
  41. var find = doc.Body.Find("", fo).FirstOrDefault();
  42. Paragraph para;
  43. if (find != null)
  44. {
  45. // We found the point between the title page and the content:
  46. para = find.Range.ParentParagraph.GetRange().Paragraphs.Insert("Table of Contents", doc.Styles[BuiltInStyleId.TocHeading], InsertLocation.Before);
  47. para = para.GetRange().Paragraphs.Insert(InsertLocation.After);
  48. }
  49. else
  50. {
  51. // Otherwise, just insert the TOC at the beginning of the document:
  52. para = doc.Body.Paragraphs.Insert("Table of Contents", doc.Styles[BuiltInStyleId.TocHeading], InsertLocation.Start);
  53. }
  54.  
  55. // Add the TOC field with our options, and update it so that it shows the actual document contents:
  56. para.AddComplexField(tocOpts).Update(new GrapeCity.Documents.Word.Layout.WordLayoutSettings()
  57. {
  58. FontCollection = Util.FontCollection,
  59. Culture = CultureInfo.GetCultureInfo("en-US")
  60. });
  61.  
  62. // Done:
  63. return doc;
  64. }
  65. }
  66. }
  67.