DynamicPositionCapture.cs 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Drawing;
  4. using System.Globalization;
  5. using System.Linq;
  6. using NUnit.Framework;
  7. using QuestPDF.Elements;
  8. using QuestPDF.Examples.Engine;
  9. using QuestPDF.Fluent;
  10. using QuestPDF.Helpers;
  11. using QuestPDF.Infrastructure;
  12. namespace QuestPDF.Examples
  13. {
  14. public class DynamicPositionCaptureExample : IDynamicComponent
  15. {
  16. public DynamicComponentComposeResult Compose(DynamicContext context)
  17. {
  18. var containerLocation = context
  19. .GetElementCapturedLocations("container")
  20. .FirstOrDefault(x => x.PageNumber == context.PageNumber);
  21. if (containerLocation == null)
  22. {
  23. return new DynamicComponentComposeResult
  24. {
  25. Content = context.CreateElement(container => { }),
  26. HasMoreContent = false
  27. };
  28. }
  29. var positions = Enumerable
  30. .Range(0, 20)
  31. .SelectMany(x => context.GetElementCapturedLocations($"capture_{x}"))
  32. .ToList();
  33. var onCurrentPage = positions.Where(x => x.PageNumber == context.PageNumber).ToList();
  34. var content = context.CreateElement(container => container.Layers(layers =>
  35. {
  36. foreach (var position in onCurrentPage)
  37. {
  38. layers.Layer()
  39. .TranslateX(position.X - containerLocation.X)
  40. .TranslateY(position.Y - containerLocation.Y)
  41. .Width(position.Width)
  42. .Height(position.Height)
  43. .Border(1)
  44. .Background(Placeholders.BackgroundColor());
  45. }
  46. layers.PrimaryLayer().Text($"{onCurrentPage.Count}");
  47. }));
  48. return new DynamicComponentComposeResult
  49. {
  50. Content = content,
  51. HasMoreContent = positions.Any(x => x.PageNumber > context.PageNumber + 1)
  52. };
  53. }
  54. }
  55. public static class DynamicPositionCapture
  56. {
  57. [Test]
  58. public static void Dynamic()
  59. {
  60. RenderingTest
  61. .Create()
  62. .PageSize(PageSizes.A4)
  63. .ShowResults()
  64. .ProducePdf()
  65. .Render(container =>
  66. {
  67. container
  68. .Background(Colors.White)
  69. .Padding(25)
  70. .Row(row =>
  71. {
  72. row.Spacing(25);
  73. row.RelativeItem().Border(1).CaptureLocation("container").Column(column =>
  74. {
  75. column.Spacing(25);
  76. foreach (var i in Enumerable.Range(0, 20))
  77. {
  78. column.Item()
  79. .Shrink()
  80. .CaptureLocation($"capture_{i}")
  81. .Border(1)
  82. .Background(Placeholders.BackgroundColor())
  83. .Width(Random.Shared.Next(25, 125))
  84. .Height(Random.Shared.Next(25, 125));
  85. }
  86. });
  87. row.RelativeItem().Dynamic(new DynamicPositionCaptureExample());
  88. });
  89. });
  90. }
  91. }
  92. }