DataTplSimpleListJson.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 is similar to DataTplSimpleList
  16. // but uses a JSON data source to generate
  17. // the list of ocean seas.
  18. public class DataTplSimpleListJson
  19. {
  20. public GcWordDocument CreateDocx()
  21. {
  22. var doc = new GcWordDocument();
  23.  
  24. // The JSON data source is loaded from oceans.json:
  25. using (var oceans = File.OpenRead(Path.Combine("Resources", "data", "oceans.json")))
  26. doc.DataTemplate.DataSources.Add("ds", oceans);
  27.  
  28. // Add a list template so that the data is formatted as a list:
  29. var myListTemplate = doc.ListTemplates.Add(BuiltInListTemplateId.BulletDefault, "myListTemplate");
  30.  
  31. // The single paragraph added to the document contains template tags:
  32. // - {{#ds}}..{{/ds}} -- root template, 'ds' is the name of the data source;
  33. // - {ds.seas.name} -- fetches the sea name;
  34. // - :toupper() -- uppercases the data:
  35. var p = doc.Body.Paragraphs.Add("{{#ds}}{{ds.seas.name}:toupper()}{{/ds}}", doc.Styles[BuiltInStyleId.ListParagraph]);
  36. p.ListFormat.Template = myListTemplate;
  37.  
  38. // This call expands all data templates in the document,
  39. // replacing template tags with data (iterating over all data items):
  40. doc.DataTemplate.Process(CultureInfo.GetCultureInfo("en-US"));
  41.  
  42. // Done:
  43. return doc;
  44. }
  45. }
  46. }
  47.