DynamicFibonacci.cs 3.2 KB

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