ComplexFields.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 GrapeCity.Documents.Word;
  11.  
  12. namespace DsWordWeb.Demos
  13. {
  14. // This sample demonstrates the use of complex fields.
  15. // It adds a complex field that tests whether the current date
  16. // is the New Year day, and modifies the text in the document
  17. // accordingly. See also DateAndTime sample.
  18. public class ComplexFields
  19. {
  20. public GcWordDocument CreateDocx()
  21. {
  22. GcWordDocument doc = new GcWordDocument();
  23.  
  24. // Add a title:
  25. doc.Body.Paragraphs.Add("Testing whether it is the New Year yet").Style = doc.Styles[BuiltInStyleId.Title];
  26.  
  27. // Add a paragraph and get its range:
  28. var rng = doc.Body.Paragraphs.Add().GetRange();
  29. // Add a static text:
  30. rng.Runs.Add("Today is ");
  31.  
  32. // Add a complex field with "IF" instruction. We also provide
  33. // a pre-calculated value for the sake of PDF export, as DsWord
  34. // does not yet support field calculation - see DateAndTime.
  35. // Note also that because the code field will not be calculated
  36. // in the PDF export, the "NOT " won't be bold in it:
  37. var val = Util.TimeNow().DayOfYear == 1 ? "" : "NOT ";
  38. var f = rng.ComplexFields.Add("IF ", val);
  39. // Add a complex field with "DATE" instruction:
  40. f.GetCodeRange().ComplexFields.Add(" DATE \\@ \"M-d\" ");
  41. // Add additional instruction to the "IF" field to compare the nested
  42. // DATE field result with "1-1" and return "NOT " if it is true,
  43. // also make the "NOT " bold if visible:
  44. f.CodeFields.Add("<> \"1-1\" \"NOT \"").ParentRun.Font.Bold = true;
  45.  
  46. // Add a static text:
  47. rng.Runs.Add("New Year's Day.");
  48.  
  49. // Done:
  50. return doc;
  51. }
  52. }
  53. }
  54.