Browse Source

Feat svg output format (#890)

Marcin Ziąbek 1 year ago
parent
commit
95637a01e2

+ 10 - 0
Source/QuestPDF/Drawing/DocumentGenerator.cs

@@ -51,6 +51,16 @@ namespace QuestPDF.Drawing
 
             return canvas.Images;
         }
+        
+        internal static ICollection<string> GenerateSvg(IDocument document)
+        {
+            ValidateLicense();
+            
+            var canvas = new SvgCanvas();
+            RenderDocument(canvas, document, document.GetSettings());
+
+            return canvas.Images;
+        }
 
         private static void ValidateLicense()
         {

+ 5 - 0
Source/QuestPDF/Drawing/ImageCanvas.cs

@@ -20,6 +20,11 @@ namespace QuestPDF.Drawing
             Settings = settings;
         }
         
+        ~ImageCanvas()
+        {
+            Bitmap?.Dispose();
+        }
+        
         public override void BeginDocument()
         {
             

+ 51 - 0
Source/QuestPDF/Drawing/SvgCanvas.cs

@@ -0,0 +1,51 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Text;
+using QuestPDF.Drawing.Exceptions;
+using QuestPDF.Helpers;
+using QuestPDF.Infrastructure;
+using QuestPDF.Skia;
+
+namespace QuestPDF.Drawing
+{
+    internal sealed class SvgCanvas : SkiaCanvasBase
+    {
+        internal SkWriteStream WriteStream { get; set; }
+        internal ICollection<string> Images { get; } = new List<string>();
+        
+        ~SvgCanvas()
+        {
+            WriteStream?.Dispose();
+        }
+        
+        public override void BeginDocument()
+        {
+            
+        }
+
+        public override void EndDocument()
+        {
+            
+        }
+
+        public override void BeginPage(Size size)
+        {
+            WriteStream?.Dispose();
+            WriteStream = new SkWriteStream();
+            Canvas = SkSvgCanvas.CreateSvg(size.Width, size.Height, WriteStream);
+        }
+
+        public override void EndPage()
+        {
+            Canvas.Save();
+            Canvas.Dispose();
+            
+            using var data = WriteStream.DetachData();
+            var svgImage = Encoding.UTF8.GetString(data.ToBytes());
+            Images.Add(svgImage);
+            
+            WriteStream.Dispose();
+        }
+    }
+}

+ 12 - 0
Source/QuestPDF/Fluent/GenerateExtensions.cs

@@ -150,5 +150,17 @@ namespace QuestPDF.Fluent
         }
 
         #endregion
+        
+        #region SVG
+
+        /// <summary>
+        /// Generates the document as a series of SVG images and returns them as a collection of strings.
+        /// </summary>
+        public static ICollection<string> GenerateSvg(this IDocument document)
+        {
+            return DocumentGenerator.GenerateSvg(document);
+        }
+
+        #endregion
     }
 }