DataTplSequence.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.  
  13. namespace DsWordWeb.Demos
  14. {
  15. // This sample demonstrates how to use 'sequence' ('seq') and 'follow' formatters
  16. // to synchronize two ranges from two different JSON data sources.
  17. public class DataTplSequence
  18. {
  19. public GcWordDocument CreateDocx()
  20. {
  21. // The first JSON data source - the sequence master.
  22. // In this sample we use it to spell sequence numbers.
  23. // Note that the resulting number of iterations will be the MINIMUM
  24. // of the lengths of the sequence and follower, so print all oceans
  25. // we need to provide at least 5 numbers, but more won't hurt:
  26. var sequence = @"[
  27. { ""num"": ""First"" },
  28. { ""num"": ""Second"" },
  29. { ""num"": ""Third"" },
  30. { ""num"": ""Fourth"" },
  31. { ""num"": ""Fifth"" },
  32. { ""num"": ""Sixth"" },
  33. { ""num"": ""Seventh"" },
  34. { ""num"": ""Eights"" },
  35. { ""num"": ""Ninth"" },
  36. { ""num"": ""Tenth"" }
  37. ]";
  38.  
  39. var doc = new GcWordDocument();
  40.  
  41. // Add the data sources to the data template data sources:
  42. doc.DataTemplate.DataSources.Add("nums", sequence);
  43. // The second JSON data source is loaded from oceans.json:
  44. using (var oceans = File.OpenRead(Path.Combine("Resources", "data", "oceans.json")))
  45. doc.DataTemplate.DataSources.Add("ds", oceans);
  46.  
  47. // Add a list template so that the data is formatted as a list:
  48. var myListTemplate = doc.ListTemplates.Add(BuiltInListTemplateId.BulletDefault, "myListTemplate");
  49.  
  50. // The only paragraph added to the document will print the sequence number
  51. // fetched from the first data source (the sequence master), and the ocean name
  52. // fetched from the second data source (the sequence follower):
  53. var p = doc.Body.Paragraphs.Add("{{#nums}:seq(seq1)}{{nums.num}} -- {{#ds}:follow(seq1)}{{ds.name}}{{/ds}}{{/nums}}", doc.Styles[BuiltInStyleId.ListParagraph]);
  54. p.ListFormat.Template = myListTemplate;
  55.  
  56. // This call expands all data templates in the document,
  57. // replacing template tags with data (iterating over all data items):
  58. doc.DataTemplate.Process(CultureInfo.GetCultureInfo("en-US"));
  59.  
  60. // Done:
  61. return doc;
  62. }
  63. }
  64. }
  65.