IndexFieldOpts.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. using GrapeCity.Documents.Word.Layout;
  14. using System.Text;
  15. using C1.DataCollection;
  16. using System.Text.RegularExpressions;
  17.  
  18. namespace DsWordWeb.Demos
  19. {
  20. // This sample shows how to use the INDEX and XE field options
  21. // to add an index to a DOCX Word document.
  22. public class IndexFieldOpts
  23. {
  24. // For this demo, we arbitrarily pick some of the 'lorem ipsum' words to include in the index:
  25. private static string[] s_indexWords =
  26. {
  27. "lorem", "ipsum", "dolor", "sit", "amet", "consectetur", "adipiscing", "elit", "mauris", "id", "volutpat",
  28. "tellus", "ullamcorper", "sem", "praesent", "et", "ante", "laoreet", "lobortis", "nunc", "congue",
  29. };
  30.  
  31. public GcWordDocument CreateDocx()
  32. {
  33. var doc = new GcWordDocument();
  34.  
  35. // Arbitrary number of sample paragraphs in the document:
  36. const int NPARS = 30;
  37. // We add some random "lorem ipsum" paragraphs to the document,
  38. // and build the index on the arbitrarily chosen subset of words,
  39. // including pages where the indexed word appears as the first
  40. // word in a paragraph:
  41. for (int i = 0; i < NPARS; ++i)
  42. {
  43. var par = doc.Body.Paragraphs.Add();
  44. var txt = Util.LoremIpsumPar();
  45.  
  46. var words = txt.Split([' ', ',', '.'], 2);
  47. if (words.Length != 2)
  48. throw new Exception("Unexpected");
  49.  
  50. var word = words[0];
  51. var xe = new XeFieldOptions(doc);
  52. xe.Entry.Content.Text = word;
  53. par.AddComplexField(xe);
  54. par.AddRun(txt);
  55. }
  56. // Add new section for the index:
  57. doc.Body.Paragraphs.Last.AddSectionBreak();
  58. var p = doc.Body.Paragraphs.Add(doc.Styles[BuiltInStyleId.Index1]);
  59. // Set up INDEX field options:
  60. var index = new IndexFieldOptions(doc);
  61. // Two column layout:
  62. index.Columns = 2;
  63. // Use headings for index entries:
  64. index.Heading = "A";
  65. // Set any additional options as needed,
  66. // then create the INDEX field with the specified options:
  67. ComplexField field = p.AddComplexField(index);
  68.  
  69. // Update the index field using a specific culture:
  70. field.Update(new WordLayoutSettings() { FontCollection = Util.FontCollection, Culture = CultureInfo.GetCultureInfo("en-US") });
  71.  
  72. // Done:
  73. return doc;
  74. }
  75. }
  76. }
  77.