DataTplParaBlockBehavior.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 example shows how to use the 'pbb' ('paragraph-block-behavior') formatter
  16. // to print all data items of a list as separate paragraphs inside a single table cell
  17. // rather than generating a new row for each item.
  18. public class DataTplParaBlockBehavior
  19. {
  20. public GcWordDocument CreateDocx()
  21. {
  22. using var oceans = File.OpenRead(Path.Combine("Resources", "data", "oceans.json"));
  23. var doc = new GcWordDocument();
  24. doc.DataTemplate.DataSources.Add("ds", oceans);
  25.  
  26. // Add a list for oceans, and a nested table for seas:
  27. // doc.Body.Paragraphs.Add("{{#ds}}{{ds.name}}", doc.Styles[BuiltInStyleId.ListParagraph]);
  28.  
  29. // Add a table with one column and two rows, note that each cell has one default paragraph
  30. // when the table is created, so we add template tags to those already existing paragraphs:
  31. var table = doc.Body.Tables.Add(1, 2, doc.Styles[BuiltInStyleId.ColorfulShadingAccent1]);
  32. // The first row is used to print the ocean's name:
  33. table[0, 0].GetRange().Paragraphs.First.GetRange().Runs.Add("{{#ds}}{{ds.name}}");
  34. // The second row prints the ocean's seas range. Using the 'pbb' (paragraph-block-b) formatter
  35. // allows us to print all items in the range (seas) inside the same single cell rather than
  36. // generating a row per each item:
  37. table[1, 0].GetRange().Paragraphs.First.GetRange().Runs.Add("{{#ds.seas}:pbb()}{{ds.seas.name}}{{/ds.seas}}");
  38.  
  39. // Close the parent range '#ds':
  40. doc.Body.Paragraphs.Add("{{/ds}}");
  41.  
  42. // Process the template:
  43. doc.DataTemplate.Process(CultureInfo.GetCultureInfo("en-US"));
  44.  
  45. return doc;
  46. }
  47. }
  48. }
  49.