ExampleTestBase.cs 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using System;
  2. using System.Diagnostics;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Reflection;
  6. using NUnit.Framework;
  7. using QuestPDF.Drawing;
  8. using QuestPDF.Elements;
  9. using QuestPDF.Fluent;
  10. using QuestPDF.Infrastructure;
  11. using SkiaSharp;
  12. namespace QuestPDF.Examples.Engine
  13. {
  14. [TestFixture]
  15. public class ExampleTestBase
  16. {
  17. private readonly Size DefaultImageSize = new Size(400, 300);
  18. private const string ResultPath = "Result";
  19. [SetUp]
  20. public void Setup()
  21. {
  22. if (Directory.Exists(ResultPath))
  23. Directory.Delete(ResultPath, true);
  24. Directory.CreateDirectory(ResultPath);
  25. }
  26. [Test]
  27. public void RunTest()
  28. {
  29. GetType()
  30. .GetMethods()
  31. .Where(IsExampleMethod)
  32. .ToList()
  33. .ForEach(HandleExample);
  34. }
  35. private bool IsExampleMethod(MethodInfo method)
  36. {
  37. var parameters = method.GetParameters();
  38. return parameters.Length == 1 && parameters.First().ParameterType == typeof(IContainer);
  39. }
  40. private T GetAttribute<T>(MethodInfo methodInfo) where T : Attribute
  41. {
  42. return methodInfo.GetCustomAttributes().FirstOrDefault(y => y is T) as T;
  43. }
  44. private void HandleExample(MethodInfo methodInfo)
  45. {
  46. var size = GetAttribute<ImageSizeAttribute>(methodInfo)?.Size ?? DefaultImageSize;
  47. var fileName = GetAttribute<FileNameAttribute>(methodInfo)?.FileName ?? methodInfo.Name;
  48. var showResult = GetAttribute<ShowResultAttribute>(methodInfo) != null;
  49. var shouldIgnore = GetAttribute<IgnoreAttribute>(methodInfo) != null;
  50. if (shouldIgnore)
  51. return;
  52. var container = new Container();
  53. methodInfo.Invoke(this, new object[] {container});
  54. Func<int, string> fileNameSchema = i => $"{fileName.ToLower()}-${i}.png";
  55. var document = new SimpleDocument(container, size);
  56. document.GenerateImages(fileNameSchema);
  57. if (showResult)
  58. Process.Start("explorer", fileNameSchema(0));
  59. }
  60. private byte[] RenderPage(Element element, Size size)
  61. {
  62. // scale the result so it is more readable
  63. const float scalingFactor = 2;
  64. var imageInfo = new SKImageInfo((int)(size.Width * scalingFactor), (int)(size.Height * scalingFactor));
  65. using var surface = SKSurface.Create(imageInfo);
  66. surface.Canvas.Scale(scalingFactor);
  67. var canvas = new Canvas(surface.Canvas);
  68. element?.Draw(canvas, size);
  69. surface.Canvas.Save();
  70. return surface.Snapshot().Encode(SKEncodedImageFormat.Png, 100).ToArray();
  71. }
  72. }
  73. }