DynamicPositionCapture.cs 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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. .Background(Placeholders.BackgroundColor());
  44. }
  45. layers.PrimaryLayer().Text($"{onCurrentPage.Count}");
  46. }));
  47. return new DynamicComponentComposeResult
  48. {
  49. Content = content,
  50. HasMoreContent = positions.Any(x => x.PageNumber > context.PageNumber + 1)
  51. };
  52. }
  53. }
  54. public static class DynamicPositionCapture
  55. {
  56. [Test]
  57. public static void Dynamic()
  58. {
  59. RenderingTest
  60. .Create()
  61. .PageSize(PageSizes.A4)
  62. .ShowResults()
  63. .ProducePdf()
  64. .Render(container =>
  65. {
  66. container
  67. .Background(Colors.White)
  68. .Padding(25)
  69. .Row(row =>
  70. {
  71. row.Spacing(25);
  72. row.RelativeItem().Border(1).CaptureLocation("container").Column(column =>
  73. {
  74. column.Spacing(25);
  75. foreach (var i in Enumerable.Range(0, 20))
  76. {
  77. column.Item()
  78. .CaptureLocation($"capture_{i}")
  79. .Width(Random.Shared.Next(25, 125))
  80. .Height(Random.Shared.Next(25, 125))
  81. .Background(Placeholders.BackgroundColor());
  82. }
  83. });
  84. row.RelativeItem().Dynamic(new DynamicPositionCaptureExample());
  85. });
  86. });
  87. }
  88. }
  89. }