DataTplFixPbbNotInTable.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 deal with the
  16. // pbb (paragraph-block-behavior) template formatter
  17. // should start and end in the same cell error.
  18. public class DataTplFixPbbNotInTable
  19. {
  20. // Code demonstrating the problem:
  21. GcWordDocument Problem()
  22. {
  23. using var oceans = File.OpenRead(Path.Combine("Resources", "data", "oceans.json"));
  24. var doc = new GcWordDocument();
  25. doc.DataTemplate.DataSources.Add("ds", oceans);
  26. // Incorrect: a range with a pbb (paragraph-block-behavior) formatter is defined
  27. // outside of a table:
  28. doc.Body.Paragraphs.Add("{{#ds.seas}:pbb()}{{ds.seas.name}} {{/ds.seas}}");
  29. doc.DataTemplate.Process(CultureInfo.GetCultureInfo("en-US"));
  30. return doc;
  31. }
  32.  
  33. // Code demonstrating the fix:
  34. GcWordDocument Fix()
  35. {
  36. using var oceans = File.OpenRead(Path.Combine("Resources", "data", "oceans.json"));
  37. var doc = new GcWordDocument();
  38. doc.DataTemplate.DataSources.Add("ds", oceans);
  39. // Correct: remove the pbb formatter as it is not needed outside of table:
  40. doc.Body.Paragraphs.Add("{{#ds.seas}}{{ds.seas.name}} {{/ds.seas}}");
  41. doc.DataTemplate.Process(CultureInfo.GetCultureInfo("en-US"));
  42. return doc;
  43. }
  44.  
  45. public GcWordDocument CreateDocx()
  46. {
  47. GcWordDocument doc;
  48. try
  49. {
  50. // This fails:
  51. doc = Problem();
  52. }
  53. catch (Exception ex)
  54. {
  55. // This works:
  56. doc = Fix();
  57. // Insert a brief explanation of the problem and the fix into the generated document:
  58. doc.Body.Paragraphs.Insert(
  59. $"The error \"{ex.Message}\" occurred because a pbb (paragraph-block-behavior) formatter " +
  60. $"was defined not inside a table. A pbb formatter can only be used inside a table cell.",
  61. doc.Styles[BuiltInStyleId.BlockText],
  62. InsertLocation.Start);
  63. }
  64. return doc;
  65. }
  66. }
  67. }
  68.