DynamicFibonacci.cs 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  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 struct FibonacciHeaderState
  12. {
  13. public int Previous { get; set; }
  14. public int Current { get; set; }
  15. }
  16. public class FibonacciHeader : IDynamicComponent<FibonacciHeaderState>
  17. {
  18. public FibonacciHeaderState State { get; set; }
  19. public static readonly string[] ColorsTable =
  20. {
  21. Colors.Red.Lighten2,
  22. Colors.Orange.Lighten2,
  23. Colors.Green.Lighten2,
  24. };
  25. public FibonacciHeader(int previous, int current)
  26. {
  27. State = new FibonacciHeaderState
  28. {
  29. Previous = previous,
  30. Current = current
  31. };
  32. }
  33. public DynamicComponentComposeResult Compose(DynamicContext context)
  34. {
  35. var content = context.CreateElement(container =>
  36. {
  37. var colorIndex = State.Current % ColorsTable.Length;
  38. var color = ColorsTable[colorIndex];
  39. var ratio = (float)State.Current / State.Previous;
  40. container
  41. .Background(color)
  42. .Height(50)
  43. .AlignMiddle()
  44. .AlignCenter()
  45. .Text($"{State.Current} / {State.Previous} = {ratio:N5}");
  46. });
  47. State = new FibonacciHeaderState
  48. {
  49. Previous = State.Current,
  50. Current = State.Previous + State.Current
  51. };
  52. return new DynamicComponentComposeResult
  53. {
  54. Content = content,
  55. HasMoreContent = false
  56. };
  57. }
  58. }
  59. public static class DynamicFibonacci
  60. {
  61. [Test]
  62. public static void Dynamic()
  63. {
  64. RenderingTest
  65. .Create()
  66. .ShowResults()
  67. .MaxPages(100)
  68. .ProduceImages()
  69. .RenderDocument(container =>
  70. {
  71. container.Page(page =>
  72. {
  73. page.Size(PageSizes.A6);
  74. page.PageColor(Colors.White);
  75. page.Margin(1, Unit.Centimetre);
  76. page.DefaultTextStyle(x => x.FontSize(18));
  77. page.Header().Dynamic(new FibonacciHeader(17, 19));
  78. page.Content().Column(column =>
  79. {
  80. foreach (var i in Enumerable.Range(0, 50))
  81. column.Item().PaddingTop(25).Background(Colors.Grey.Lighten2).Height(50);
  82. });
  83. page.Footer().AlignCenter().Text(text =>
  84. {
  85. text.CurrentPageNumber();
  86. text.Span(" / ");
  87. text.TotalPages();
  88. });
  89. });
  90. });
  91. }
  92. }
  93. }