DynamicExamples.cs 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. using NUnit.Framework;
  4. using QuestPDF.Elements;
  5. using QuestPDF.Examples.Engine;
  6. using QuestPDF.Fluent;
  7. using QuestPDF.Helpers;
  8. using QuestPDF.Infrastructure;
  9. namespace QuestPDF.Examples
  10. {
  11. public class TableWithSubtotals : IDynamic
  12. {
  13. private ICollection<int> Values { get; }
  14. private Queue<int> ValuesQueue { get; set; }
  15. public TableWithSubtotals(ICollection<int> values)
  16. {
  17. Values = values;
  18. }
  19. public void Reset()
  20. {
  21. ValuesQueue = new Queue<int>(Values);
  22. }
  23. public bool Compose(DynamicContext context, IContainer container)
  24. {
  25. var internalQueue = new Queue<int>(ValuesQueue);
  26. container.Box().Border(2).Background(Colors.Grey.Lighten3).Stack(stack =>
  27. {
  28. var summaryHeight = 40f;
  29. var totalHeight = summaryHeight;
  30. var total = 0;
  31. while (internalQueue.Any())
  32. {
  33. var value = internalQueue.Peek();
  34. var structure = context.Content(content =>
  35. {
  36. content
  37. .Padding(10)
  38. .Text(value);
  39. });
  40. var structureHeight = structure.Measure().Height;
  41. if (totalHeight + structureHeight > context.AvailableSize.Height)
  42. break;
  43. totalHeight += structureHeight;
  44. total += value;
  45. stack.Item().Border(1).Element(structure);
  46. internalQueue.Dequeue();
  47. }
  48. stack
  49. .Item()
  50. .ShowEntire()
  51. .Border(2)
  52. .Background(Colors.Grey.Lighten1)
  53. .Padding(10)
  54. .Text($"Total: {total}", TextStyle.Default.SemiBold());
  55. });
  56. if (context.IsDrawStep)
  57. ValuesQueue = internalQueue;
  58. return internalQueue.Any();
  59. }
  60. }
  61. public static class DynamicExamples
  62. {
  63. [Test]
  64. public static void Dynamic()
  65. {
  66. RenderingTest
  67. .Create()
  68. .PageSize(300, 500)
  69. .FileName()
  70. .ShowResults()
  71. .Render(container =>
  72. {
  73. var values = Enumerable.Range(0, 15).ToList();
  74. container
  75. .Background(Colors.White)
  76. .Padding(25)
  77. .Decoration(decoration =>
  78. {
  79. decoration
  80. .Header()
  81. .PaddingBottom(5)
  82. .Text(text =>
  83. {
  84. text.DefaultTextStyle(TextStyle.Default.SemiBold().Color(Colors.Blue.Darken2).Size(16));
  85. text.Span("Page ");
  86. text.CurrentPageNumber();
  87. text.Span(" of ");
  88. text.TotalPages();
  89. });
  90. decoration
  91. .Content()
  92. .Dynamic(new TableWithSubtotals(values));
  93. });
  94. });
  95. }
  96. }
  97. }