PageFieldOpts.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 use the PAGE and NUMPAGES field options
  17. // to insert the current and total page numbers into the document
  18. // and customize the fields' appearance.
  19. public class PageFieldOpts
  20. {
  21. public GcWordDocument CreateDocx()
  22. {
  23. var doc = new GcWordDocument();
  24.  
  25. // The PageFieldOptions and NumPagesFieldOptions classes provide
  26. // convenient strong-typed access to options specific to the
  27. // 'PAGE' and 'NUMPAGES' MS Word fields respectively.
  28.  
  29. // PAGE field options for the page header:
  30. var pgOptHeader = new PageFieldOptions(doc);
  31. pgOptHeader.NumberStyle = NumberStyle.Decimal;
  32.  
  33. // PAGE field options for page numbers in the body:
  34. var pgOptBody = new PageFieldOptions(doc);
  35. pgOptBody.NumberStyle = NumberStyle.UpperRoman;
  36.  
  37. // NUMPAGES field options:
  38. var numpagesOpt = new NumPagesFieldOptions(doc);
  39. numpagesOpt.NumberStyle = NumberStyle.Decimal;
  40.  
  41. // Add a page header that includes the current and total page numbers:
  42. var para = doc.Body.Sections.First.Headers[HeaderFooterType.Primary].Body.AddParagraph("Page header - page ");
  43. para.AddComplexField(pgOptHeader);
  44. para.AddRun(" of ");
  45. para.AddComplexField(numpagesOpt);
  46.  
  47. // Pick a style that will be used for page numbers in the document body:
  48. var pageStyle = doc.Styles[BuiltInStyleId.IndexHeading];
  49.  
  50. // Add some pages, with periodic inclusions of the PAGE field:
  51. var rnd = Util.NewRandom();
  52. for (int i = 0; i < rnd.Next(6, 12); i++)
  53. {
  54. var p = doc.Body.AddParagraph("This text is on page ", pageStyle);
  55. p.AddComplexField(pgOptBody);
  56. p.AddRun(" of ");
  57. p.AddComplexField(numpagesOpt);
  58. p.GetRange().Runs.Add(".");
  59. var par = Util.LoremIpsumPar();
  60. doc.Body.AddParagraph(par);
  61. }
  62.  
  63. // Update fields using a specific culture:
  64. doc.UpdateFields(new GrapeCity.Documents.Word.Layout.WordLayoutSettings() { FontCollection = Util.FontCollection, Culture = CultureInfo.GetCultureInfo("en-US") });
  65.  
  66. // Done:
  67. return doc;
  68. }
  69. }
  70. }
  71.