diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 2f3e6ab48..0a38b5be9 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -82,6 +82,7 @@ jobs:
if ($failed) { exit 1 }
env:
PDF_OUTPUT_DIRECTORY: ${{ github.workspace }}/pdf-artifacts/${{ matrix.platform.name }}-${{ matrix.dotnet.name }}
+ HTML_RENDERER_REGRESSION_OUTPUT_DIRECTORY: ${{ github.workspace }}/image-regression/${{ matrix.platform.name }}-${{ matrix.dotnet.name }}
- name: Spec compliance report
if: ${{ !cancelled() && runner.os == 'Windows' && matrix.dotnet.name == '.NET 8' }}
@@ -101,6 +102,9 @@ jobs:
- name: Create HtmlRenderer.PdfSharp NuGet package
run: dotnet pack Source/HtmlRenderer.PdfSharp/HtmlRenderer.PdfSharp.csproj --configuration Release --include-symbols -p:SymbolPackageFormat=snupkg --no-build --verbosity normal --output ${{ env.NuGetDirectory }}
+ - name: Create HtmlRenderer.SkiaSharp NuGet package
+ run: dotnet pack Source/HtmlRenderer.SkiaSharp/HtmlRenderer.SkiaSharp.csproj --configuration Release --include-symbols -p:SymbolPackageFormat=snupkg --no-build --verbosity normal --output ${{ env.NuGetDirectory }}
+
- name: Create HtmlRenderer.WinForms NuGet package
run: dotnet pack Source/HtmlRenderer.WinForms/HtmlRenderer.WinForms.csproj --configuration Release --include-symbols -p:SymbolPackageFormat=snupkg --no-build --verbosity normal --output ${{ env.NuGetDirectory }}
diff --git a/README.md b/README.md
index 0a8553037..6777de54c 100644
--- a/README.md
+++ b/README.md
@@ -23,6 +23,7 @@ The latest NuGet packages can be found on NuGet.org:
* [HtmlRenderer.WinForms](https://www.nuget.org/packages/HtmlRenderer.WinForms)
* [HtmlRenderer.WPF](https://www.nuget.org/packages/HtmlRenderer.WPF)
* [HtmlRenderer.PdfSharp](https://www.nuget.org/packages/HtmlRenderer.PdfSharp)
+* [HtmlRenderer.SkiaSharp](https://www.nuget.org/packages/HtmlRenderer.SkiaSharp)
* [HtmlRenderer.Core](https://www.nuget.org/packages/HtmlRenderer.Core)
diff --git a/Source/HtmlRenderer.CrossPlatform.slnf b/Source/HtmlRenderer.CrossPlatform.slnf
index f756150bb..3e456d5b7 100644
--- a/Source/HtmlRenderer.CrossPlatform.slnf
+++ b/Source/HtmlRenderer.CrossPlatform.slnf
@@ -7,10 +7,12 @@
"Demo\\WPF\\HtmlRenderer.Demo.WPF.csproj",
"HtmlRenderer\\HtmlRenderer.csproj",
"HtmlRenderer.PdfSharp\\HtmlRenderer.PdfSharp.csproj",
+ "HtmlRenderer.SkiaSharp\\HtmlRenderer.SkiaSharp.csproj",
"HtmlRenderer.WinForms\\HtmlRenderer.WinForms.csproj",
"HtmlRenderer.WPF\\HtmlRenderer.WPF.csproj",
"Test\\HtmlRenderer.IntegrationTest\\HtmlRenderer.IntegrationTest.csproj",
"Test\\HtmlRenderer.PdfSharp.Test\\HtmlRenderer.PdfSharp.Test.csproj",
+ "Test\\HtmlRenderer.SkiaSharp.Test\\HtmlRenderer.SkiaSharp.Test.csproj",
"Test\\HtmlRenderer.Test\\HtmlRenderer.Test.csproj",
"Tools\\HtmlRenderer.SpecCompliance\\HtmlRenderer.SpecCompliance.csproj"
]
diff --git a/Source/HtmlRenderer.SkiaSharp/Adapters/BrushAdapter.cs b/Source/HtmlRenderer.SkiaSharp/Adapters/BrushAdapter.cs
new file mode 100644
index 000000000..e29f7f780
--- /dev/null
+++ b/Source/HtmlRenderer.SkiaSharp/Adapters/BrushAdapter.cs
@@ -0,0 +1,57 @@
+// "Therefore those skilled at the unorthodox
+// are infinite as heaven and earth,
+// inexhaustible as the great rivers.
+// When they come to an end,
+// they begin again,
+// like the days and months;
+// they die and are reborn,
+// like the four seasons."
+//
+// - Sun Tsu,
+// "The Art of War"
+
+using SkiaSharp;
+using TheArtOfDev.HtmlRenderer.Adapters;
+
+namespace TheArtOfDev.HtmlRenderer.SkiaSharp.Adapters
+{
+ ///
+ /// Adapter for SkiaSharp brushes: a solid color, or a shader for gradients and images.
+ ///
+ internal sealed class BrushAdapter : RBrush
+ {
+ private readonly SKColor _color;
+
+ private SKShader _shader;
+
+ public BrushAdapter(SKColor color)
+ {
+ _color = color;
+ }
+
+ public BrushAdapter(SKShader shader)
+ {
+ _color = SKColors.Black;
+ _shader = shader;
+ }
+
+ ///
+ /// Sets up the paint to fill with this brush.
+ ///
+ public void Apply(SKPaint paint)
+ {
+ paint.Style = SKPaintStyle.Fill;
+ paint.Color = _color;
+ paint.Shader = _shader;
+ }
+
+ ///
+ /// Only releases the shader, the core also disposes the cached solid brushes and uses them again afterwards.
+ ///
+ public override void Dispose()
+ {
+ _shader?.Dispose();
+ _shader = null;
+ }
+ }
+}
diff --git a/Source/HtmlRenderer.SkiaSharp/Adapters/FontAdapter.cs b/Source/HtmlRenderer.SkiaSharp/Adapters/FontAdapter.cs
new file mode 100644
index 000000000..cf739c9e6
--- /dev/null
+++ b/Source/HtmlRenderer.SkiaSharp/Adapters/FontAdapter.cs
@@ -0,0 +1,390 @@
+// "Therefore those skilled at the unorthodox
+// are infinite as heaven and earth,
+// inexhaustible as the great rivers.
+// When they come to an end,
+// they begin again,
+// like the days and months;
+// they die and are reborn,
+// like the four seasons."
+//
+// - Sun Tsu,
+// "The Art of War"
+
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using SkiaSharp;
+using SkiaSharp.HarfBuzz;
+using TheArtOfDev.HtmlRenderer.Adapters;
+
+namespace TheArtOfDev.HtmlRenderer.SkiaSharp.Adapters
+{
+ ///
+ /// Adapter for a SkiaSharp font, including the fonts it falls back to for characters it has no glyph for.
+ ///
+ ///
+ /// Skia has no font linking like GDI or DirectWrite, without the fallback CJK text or emoji end up as boxes.
+ ///
+ internal sealed class FontAdapter : RFont
+ {
+ #region Fields and Consts
+
+ private readonly SKFont _font;
+
+ private readonly SKFontStyle _style;
+
+ ///
+ /// The size in points, the core's unit for font sizes.
+ ///
+ private readonly double _size;
+
+ private readonly double _height;
+
+ ///
+ /// Distance from the top of the line to the baseline.
+ ///
+ private readonly float _ascent;
+
+ private readonly double _underlineOffset;
+
+ ///
+ /// The fonts found so far for characters the primary font doesn't cover. Fonts are shared between layouts.
+ ///
+ private readonly List _fallbacks = new List();
+
+ ///
+ /// The shapers by typeface handle, typefaces live as long as the process.
+ ///
+ private static readonly Dictionary _shapers = new Dictionary();
+
+ private double _whitespaceWidth = -1;
+
+ #endregion
+
+ ///
+ /// Init.
+ ///
+ /// the typeface to draw with
+ /// the requested style, bold and italic are synthesized when the typeface lacks them
+ /// the font size, in points
+ public FontAdapter(SKTypeface typeface, SKFontStyle style, double size)
+ {
+ _style = style;
+ _size = size;
+ _font = CreateFont(typeface, style, (float)(size * 96d / 72d));
+
+ _font.GetFontMetrics(out var metrics);
+ _ascent = -metrics.Ascent;
+ _height = -metrics.Ascent + metrics.Descent;
+
+ // The core takes this as the baseline for vertical alignment too, so it stays close to it
+ _underlineOffset = _ascent + metrics.Descent * 0.15;
+ }
+
+ public SKFont Font
+ {
+ get { return _font; }
+ }
+
+ ///
+ /// Distance from the top of the line to the baseline.
+ ///
+ public float Ascent
+ {
+ get { return _ascent; }
+ }
+
+ public override double Size
+ {
+ get { return _size; }
+ }
+
+ public override double UnderlineOffset
+ {
+ get { return _underlineOffset; }
+ }
+
+ public override double Height
+ {
+ get { return _height; }
+ }
+
+ public override double LeftPadding
+ {
+ get { return _height / 6f; }
+ }
+
+ public override double GetWhitespaceWidth(RGraphics graphics)
+ {
+ if (_whitespaceWidth < 0)
+ {
+ _whitespaceWidth = graphics.MeasureString(" ", this).Width;
+ }
+ return _whitespaceWidth;
+ }
+
+ ///
+ /// The advance width of the text.
+ ///
+ public float MeasureText(string text)
+ {
+ float width = 0;
+ foreach (var run in GetRuns(text))
+ width += Shape(text, run).Width;
+ return width;
+ }
+
+ ///
+ /// The number of characters from the start of the text that fit into the width, and the width they take.
+ ///
+ public int BreakText(string text, float maxWidth, out float measuredWidth)
+ {
+ measuredWidth = 0;
+ var count = 0;
+ foreach (var run in GetRuns(text))
+ {
+ var result = Shape(text, run);
+ if (measuredWidth + result.Width <= maxWidth)
+ {
+ measuredWidth += result.Width;
+ count += run.Length;
+ continue;
+ }
+
+ // The glyphs are in visual order, the clusters map them back to the characters
+ var advances = new float[run.Length];
+ var glyphCount = result.Codepoints.Length;
+ for (var i = 0; i < glyphCount; i++)
+ {
+ var end = i + 1 < glyphCount ? result.Points[i + 1].X : result.Width;
+ advances[result.Clusters[i]] += Math.Abs(end - result.Points[i].X);
+ }
+
+ foreach (var advance in advances)
+ {
+ if (measuredWidth + advance > maxWidth)
+ return count;
+ measuredWidth += advance;
+ count++;
+ }
+ }
+ return count;
+ }
+
+ ///
+ /// Draws the text with its baseline at the given position, is the direction of
+ /// text without a strong directional character.
+ ///
+ public void DrawText(SKCanvas canvas, string text, float x, float baseline, SKPaint paint, bool rtl = false)
+ {
+ // HarfBuzz orders the glyphs within a run, the runs of a right-to-left word go from right to left
+ var runs = GetRuns(text);
+ if (runs.Count > 1 && IsRightToLeft(text, rtl))
+ runs.Reverse();
+
+ foreach (var run in runs)
+ {
+ var result = Shape(text, run);
+ var glyphCount = result.Codepoints.Length;
+ if (glyphCount > 0)
+ {
+ var glyphs = new ushort[glyphCount];
+ for (var i = 0; i < glyphCount; i++)
+ glyphs[i] = (ushort)result.Codepoints[i];
+
+ using (var builder = new SKTextBlobBuilder())
+ {
+ builder.AddPositionedRun(glyphs, run.Font, result.Points);
+ using (var blob = builder.Build())
+ {
+ if (blob != null)
+ canvas.DrawText(blob, x, baseline, paint);
+ }
+ }
+ }
+ x += result.Width;
+ }
+ }
+
+ #region Private methods
+
+ private static SKFont CreateFont(SKTypeface typeface, SKFontStyle style, float pixelSize)
+ {
+ return new SKFont(typeface, pixelSize)
+ {
+ Edging = SKFontEdging.Antialias,
+ Subpixel = true,
+ LinearMetrics = true,
+ Hinting = SKFontHinting.Slight,
+ // Like browsers, a family without a bold or italic face still gets bold or slanted text
+ Embolden = style.Weight >= (int)SKFontStyleWeight.SemiBold && typeface.FontWeight < (int)SKFontStyleWeight.SemiBold,
+ SkewX = style.Slant != SKFontStyleSlant.Upright && typeface.FontSlant == SKFontStyleSlant.Upright ? -0.25f : 0f,
+ };
+ }
+
+ ///
+ /// Shapes one run with HarfBuzz, for ligatures, kerning, joining scripts and right-to-left text.
+ ///
+ private static SKShaper.Result Shape(string text, TextRun run)
+ {
+ var runText = run.Start == 0 && run.Length == text.Length ? text : text.Substring(run.Start, run.Length);
+ return GetShaper(run.Font.Typeface).Shape(ReplaceControlCharacters(runText), run.Font);
+ }
+
+ ///
+ /// Control characters such as a tab in white-space: pre become spaces, fonts map them to the missing glyph box.
+ ///
+ private static string ReplaceControlCharacters(string text)
+ {
+ var index = 0;
+ while (index < text.Length && text[index] >= 0x20)
+ index++;
+ if (index == text.Length)
+ return text;
+
+ var chars = text.ToCharArray();
+ for (; index < chars.Length; index++)
+ {
+ if (chars[index] < 0x20)
+ chars[index] = ' ';
+ }
+ return new string(chars);
+ }
+
+ ///
+ /// A shaper per typeface, creating one copies the whole font file.
+ ///
+ private static SKShaper GetShaper(SKTypeface typeface)
+ {
+ lock (_shapers)
+ {
+ if (!_shapers.TryGetValue(typeface.Handle, out var shaper))
+ _shapers[typeface.Handle] = shaper = new SKShaper(typeface);
+ return shaper;
+ }
+ }
+
+ ///
+ /// Splits the text into runs of the same font, the fallback fonts cover what the primary font lacks.
+ ///
+ private List GetRuns(string text)
+ {
+ if (string.IsNullOrEmpty(text) || _font.ContainsGlyphs(text))
+ return new List(1) { new TextRun(0, text?.Length ?? 0, _font) };
+
+ var runs = new List();
+ var runStart = 0;
+ SKFont runFont = null;
+ for (var i = 0; i < text.Length;)
+ {
+ var codepoint = CodepointAt(text, i, out var charCount);
+ var category = CharUnicodeInfo.GetUnicodeCategory(text, i);
+
+ // Marks, joiners and variation selectors belong to the character before them
+ var attaches = runFont != null
+ && (category == UnicodeCategory.NonSpacingMark
+ || category == UnicodeCategory.EnclosingMark
+ || category == UnicodeCategory.SpacingCombiningMark
+ || category == UnicodeCategory.Format);
+
+ var font = attaches ? runFont : GetFontFor(codepoint);
+ if (runFont != null && font != runFont)
+ {
+ runs.Add(new TextRun(runStart, i - runStart, runFont));
+ runStart = i;
+ }
+ runFont = font;
+ i += charCount;
+ }
+ runs.Add(new TextRun(runStart, text.Length - runStart, runFont));
+ return runs;
+ }
+
+ private SKFont GetFontFor(int codepoint)
+ {
+ if (codepoint < 0x20 || _font.ContainsGlyph(codepoint))
+ return _font;
+
+ lock (_fallbacks)
+ {
+ foreach (var fallback in _fallbacks)
+ {
+ if (fallback.ContainsGlyph(codepoint))
+ return fallback;
+ }
+
+ var typeface = SKFontManager.Default.MatchCharacter(_font.Typeface.FamilyName, _style, null, codepoint);
+ if (typeface == null)
+ return _font;
+
+ // A typeface that lacks the glyph after all would be matched again for every character
+ foreach (var fallback in _fallbacks)
+ {
+ if (fallback.Typeface.Handle == typeface.Handle)
+ return fallback;
+ }
+
+ var font = CreateFont(typeface, _style, _font.Size);
+ _fallbacks.Add(font);
+ return font;
+ }
+ }
+
+ ///
+ /// Whether the first strong character is right-to-left (UAX #9 P2 and P3). Letters in the Hebrew, Arabic,
+ /// Syriac, Thaana, NKo, Samaritan and Mandaic blocks and their presentation forms count as right-to-left.
+ ///
+ private static bool IsRightToLeft(string text, bool defaultRtl)
+ {
+ for (var i = 0; i < text.Length;)
+ {
+ var codepoint = CodepointAt(text, i, out var charCount);
+ var isLetter = char.IsLetter(text, i);
+ i += charCount;
+
+ if (!isLetter)
+ continue;
+
+ return (codepoint >= 0x0590 && codepoint <= 0x08FF)
+ || (codepoint >= 0xFB1D && codepoint <= 0xFDFF)
+ || (codepoint >= 0xFE70 && codepoint <= 0xFEFF)
+ || (codepoint >= 0x10800 && codepoint <= 0x10FFF)
+ || (codepoint >= 0x1E800 && codepoint <= 0x1EFFF);
+ }
+ return defaultRtl;
+ }
+
+ ///
+ /// The code point at the index, a lone surrogate is returned as is.
+ ///
+ private static int CodepointAt(string text, int index, out int charCount)
+ {
+ if (char.IsHighSurrogate(text[index]) && index + 1 < text.Length && char.IsLowSurrogate(text[index + 1]))
+ {
+ charCount = 2;
+ return char.ConvertToUtf32(text[index], text[index + 1]);
+ }
+
+ charCount = 1;
+ return text[index];
+ }
+
+ #endregion
+
+ private readonly struct TextRun
+ {
+ public TextRun(int start, int length, SKFont font)
+ {
+ Start = start;
+ Length = length;
+ Font = font;
+ }
+
+ public int Start { get; }
+
+ public int Length { get; }
+
+ public SKFont Font { get; }
+ }
+ }
+}
diff --git a/Source/HtmlRenderer.SkiaSharp/Adapters/FontFamilyAdapter.cs b/Source/HtmlRenderer.SkiaSharp/Adapters/FontFamilyAdapter.cs
new file mode 100644
index 000000000..90147c1c6
--- /dev/null
+++ b/Source/HtmlRenderer.SkiaSharp/Adapters/FontFamilyAdapter.cs
@@ -0,0 +1,57 @@
+// "Therefore those skilled at the unorthodox
+// are infinite as heaven and earth,
+// inexhaustible as the great rivers.
+// When they come to an end,
+// they begin again,
+// like the days and months;
+// they die and are reborn,
+// like the four seasons."
+//
+// - Sun Tsu,
+// "The Art of War"
+
+using SkiaSharp;
+using TheArtOfDev.HtmlRenderer.Adapters;
+
+namespace TheArtOfDev.HtmlRenderer.SkiaSharp.Adapters
+{
+ ///
+ /// Adapter for a font family, either installed and found by name, or a single loaded typeface.
+ ///
+ internal sealed class FontFamilyAdapter : RFontFamily
+ {
+ private readonly string _name;
+
+ private readonly SKTypeface _typeface;
+
+ ///
+ /// An installed family, the font manager picks the typeface for each style.
+ ///
+ public FontFamilyAdapter(string name)
+ {
+ _name = name;
+ }
+
+ ///
+ /// A typeface that isn't installed, e.g. from a font file or an @font-face rule.
+ ///
+ public FontFamilyAdapter(SKTypeface typeface)
+ {
+ _name = typeface.FamilyName;
+ _typeface = typeface;
+ }
+
+ public override string Name
+ {
+ get { return _name; }
+ }
+
+ ///
+ /// The loaded typeface, null for an installed family.
+ ///
+ public SKTypeface Typeface
+ {
+ get { return _typeface; }
+ }
+ }
+}
diff --git a/Source/HtmlRenderer.SkiaSharp/Adapters/GraphicsAdapter.cs b/Source/HtmlRenderer.SkiaSharp/Adapters/GraphicsAdapter.cs
new file mode 100644
index 000000000..0b14a16e6
--- /dev/null
+++ b/Source/HtmlRenderer.SkiaSharp/Adapters/GraphicsAdapter.cs
@@ -0,0 +1,265 @@
+// "Therefore those skilled at the unorthodox
+// are infinite as heaven and earth,
+// inexhaustible as the great rivers.
+// When they come to an end,
+// they begin again,
+// like the days and months;
+// they die and are reborn,
+// like the four seasons."
+//
+// - Sun Tsu,
+// "The Art of War"
+
+using System;
+using SkiaSharp;
+using TheArtOfDev.HtmlRenderer.Adapters;
+using TheArtOfDev.HtmlRenderer.Adapters.Entities;
+using TheArtOfDev.HtmlRenderer.Core.Utils;
+using TheArtOfDev.HtmlRenderer.SkiaSharp.Utilities;
+
+namespace TheArtOfDev.HtmlRenderer.SkiaSharp.Adapters
+{
+ ///
+ /// Adapter for a SkiaSharp canvas.
+ ///
+ internal sealed class GraphicsAdapter : RGraphics
+ {
+ #region Fields and Consts
+
+ private static readonly SKSamplingOptions ImageSampling = new SKSamplingOptions(SKFilterMode.Linear, SKMipmapMode.Linear);
+
+ ///
+ /// The canvas to draw on, null for a measure-only instance.
+ ///
+ private readonly SKCanvas _canvas;
+
+ private readonly SKPaint _paint = new SKPaint();
+
+ private bool _antiAlias;
+
+ #endregion
+
+ ///
+ /// Init.
+ ///
+ /// the canvas to draw on
+ /// the initial clip of the graphics
+ public GraphicsAdapter(SKCanvas canvas, RRect initialClip)
+ : base(SkiaSharpAdapter.Instance, initialClip)
+ {
+ ArgChecker.AssertArgNotNull(canvas, "canvas");
+
+ _canvas = canvas;
+ }
+
+ ///
+ /// Init a measure-only instance, text measuring needs no canvas.
+ ///
+ public GraphicsAdapter()
+ : base(SkiaSharpAdapter.Instance, RRect.Empty)
+ {
+ }
+
+ public override void PopClip()
+ {
+ _clipStack.Pop();
+ _canvas?.Restore();
+ }
+
+ public override void PushClip(RRect rect)
+ {
+ _clipStack.Push(rect);
+ if (_canvas != null)
+ {
+ _canvas.Save();
+ _canvas.ClipRect(Utils.Convert(rect));
+ }
+ }
+
+ public override void PushClipExclude(RRect rect)
+ {
+ _clipStack.Push(_clipStack.Peek());
+ if (_canvas != null)
+ {
+ _canvas.Save();
+ _canvas.ClipRect(Utils.Convert(rect), SKClipOperation.Difference);
+ }
+ }
+
+ public override object SetAntiAliasSmoothingMode()
+ {
+ var prevMode = _antiAlias;
+ _antiAlias = true;
+ return prevMode;
+ }
+
+ public override void ReturnPreviousSmoothingMode(object prevMode)
+ {
+ if (prevMode is bool antiAlias)
+ _antiAlias = antiAlias;
+ }
+
+ public override RSize MeasureString(string str, RFont font)
+ {
+ var fontAdapter = (FontAdapter)font;
+ return new RSize(fontAdapter.MeasureText(str), fontAdapter.Height);
+ }
+
+ public override void MeasureString(string str, RFont font, double maxWidth, out int charFit, out double charFitWidth)
+ {
+ charFit = ((FontAdapter)font).BreakText(str, (float)maxWidth, out var width);
+ charFitWidth = width;
+ }
+
+ public override void DrawString(string str, RFont font, RColor color, RPoint point, RSize size, bool rtl)
+ {
+ var fontAdapter = (FontAdapter)font;
+ ResetPaint(true);
+ _paint.Color = Utils.Convert(color);
+ fontAdapter.DrawText(_canvas, str, (float)point.X, (float)point.Y + fontAdapter.Ascent, _paint, rtl);
+ }
+
+ public override RBrush GetTextureBrush(RImage image, RRect dstRect, RPoint translateTransformLocation)
+ {
+ var skImage = ((ImageAdapter)image).Image;
+ var translation = SKMatrix.CreateTranslation((float)translateTransformLocation.X, (float)translateTransformLocation.Y);
+
+ // The rectangle is the part of the image to tile with
+ // Subset returns null for a rectangle that isn't fully inside the image
+ var subset = SKRectI.Round(Utils.Convert(dstRect));
+ subset.Intersect(new SKRectI(0, 0, skImage.Width, skImage.Height));
+ if (subset.IsEmpty || subset == new SKRectI(0, 0, skImage.Width, skImage.Height))
+ return new BrushAdapter(skImage.ToShader(SKShaderTileMode.Repeat, SKShaderTileMode.Repeat, ImageSampling, translation));
+
+ using (var part = skImage.Subset(subset))
+ {
+ return new BrushAdapter(part.ToShader(SKShaderTileMode.Repeat, SKShaderTileMode.Repeat, ImageSampling, translation));
+ }
+ }
+
+ public override RGraphicsPath GetGraphicsPath()
+ {
+ return new GraphicsPathAdapter();
+ }
+
+ public override void Dispose()
+ {
+ if (_canvas != null)
+ {
+ while (_clipStack.Count > 1)
+ PopClip();
+ }
+
+ _paint.Dispose();
+ }
+
+ #region Delegate graphics methods
+
+ public override void DrawLine(RPen pen, double x1, double y1, double x2, double y2)
+ {
+ x1 = (int)x1;
+ x2 = (int)x2;
+ y1 = (int)y1;
+ y2 = (int)y2;
+
+ // An odd width centered on a pixel edge would smear over two rows or columns
+ var adj = ((PenAdapter)pen).StrokeWidth;
+ if (Math.Abs(x1 - x2) < .1 && Math.Abs(adj % 2 - 1) < .1)
+ {
+ x1 += .5;
+ x2 += .5;
+ }
+ if (Math.Abs(y1 - y2) < .1 && Math.Abs(adj % 2 - 1) < .1)
+ {
+ y1 += .5;
+ y2 += .5;
+ }
+
+ ResetPaint(_antiAlias);
+ using (((PenAdapter)pen).Apply(_paint))
+ {
+ _canvas.DrawLine((float)x1, (float)y1, (float)x2, (float)y2, _paint);
+ }
+ }
+
+ public override void DrawRectangle(RPen pen, double x, double y, double width, double height)
+ {
+ var adj = ((PenAdapter)pen).StrokeWidth;
+ if (Math.Abs(adj % 2 - 1) < .1)
+ {
+ x += .5;
+ y += .5;
+ }
+
+ ResetPaint(_antiAlias);
+ using (((PenAdapter)pen).Apply(_paint))
+ {
+ _canvas.DrawRect((float)x, (float)y, (float)width, (float)height, _paint);
+ }
+ }
+
+ public override void DrawRectangle(RBrush brush, double x, double y, double width, double height)
+ {
+ ResetPaint(_antiAlias);
+ ((BrushAdapter)brush).Apply(_paint);
+ _canvas.DrawRect((float)x, (float)y, (float)width, (float)height, _paint);
+ }
+
+ public override void DrawImage(RImage image, RRect destRect, RRect srcRect)
+ {
+ ResetPaint(false);
+ _canvas.DrawImage(((ImageAdapter)image).Image, Utils.Convert(srcRect), Utils.Convert(destRect), ImageSampling, _paint);
+ }
+
+ public override void DrawImage(RImage image, RRect destRect)
+ {
+ ResetPaint(false);
+ _canvas.DrawImage(((ImageAdapter)image).Image, Utils.Convert(destRect), ImageSampling, _paint);
+ }
+
+ public override void DrawPath(RPen pen, RGraphicsPath path)
+ {
+ ResetPaint(_antiAlias);
+ using (((PenAdapter)pen).Apply(_paint))
+ {
+ _canvas.DrawPath(((GraphicsPathAdapter)path).GetPath(), _paint);
+ }
+ }
+
+ public override void DrawPath(RBrush brush, RGraphicsPath path)
+ {
+ ResetPaint(_antiAlias);
+ ((BrushAdapter)brush).Apply(_paint);
+ _canvas.DrawPath(((GraphicsPathAdapter)path).GetPath(), _paint);
+ }
+
+ public override void DrawPolygon(RBrush brush, RPoint[] points)
+ {
+ if (points == null || points.Length == 0)
+ return;
+
+ var skPoints = new SKPoint[points.Length];
+ for (int i = 0; i < points.Length; i++)
+ skPoints[i] = Utils.Convert(points[i]);
+
+ using (var builder = new SKPathBuilder())
+ {
+ builder.AddPoly(skPoints, true);
+ using (var path = builder.Detach())
+ {
+ ResetPaint(_antiAlias);
+ ((BrushAdapter)brush).Apply(_paint);
+ _canvas.DrawPath(path, _paint);
+ }
+ }
+ }
+
+ #endregion
+
+ private void ResetPaint(bool antiAlias)
+ {
+ _paint.Reset();
+ _paint.IsAntialias = antiAlias;
+ }
+ }
+}
diff --git a/Source/HtmlRenderer.SkiaSharp/Adapters/GraphicsPathAdapter.cs b/Source/HtmlRenderer.SkiaSharp/Adapters/GraphicsPathAdapter.cs
new file mode 100644
index 000000000..64c8d8b8f
--- /dev/null
+++ b/Source/HtmlRenderer.SkiaSharp/Adapters/GraphicsPathAdapter.cs
@@ -0,0 +1,63 @@
+// "Therefore those skilled at the unorthodox
+// are infinite as heaven and earth,
+// inexhaustible as the great rivers.
+// When they come to an end,
+// they begin again,
+// like the days and months;
+// they die and are reborn,
+// like the four seasons."
+//
+// - Sun Tsu,
+// "The Art of War"
+
+using SkiaSharp;
+using TheArtOfDev.HtmlRenderer.Adapters;
+
+namespace TheArtOfDev.HtmlRenderer.SkiaSharp.Adapters
+{
+ ///
+ /// Adapter for SkiaSharp paths.
+ ///
+ internal sealed class GraphicsPathAdapter : RGraphicsPath
+ {
+ private readonly SKPathBuilder _builder = new SKPathBuilder();
+
+ ///
+ /// The path, built on first use.
+ ///
+ private SKPath _path;
+
+ public override void Start(double x, double y)
+ {
+ _builder.MoveTo((float)x, (float)y);
+ }
+
+ public override void LineTo(double x, double y)
+ {
+ _builder.LineTo((float)x, (float)y);
+ }
+
+ public override void ArcTo(double x, double y, double radiusX, double radiusY, Corner corner)
+ {
+ // The core walks the shapes clockwise, so each corner is the small clockwise arc to the end point
+ _builder.ArcTo((float)radiusX, (float)radiusY, 0, SKPathArcSize.Small, SKPathDirection.Clockwise, (float)x, (float)y);
+ }
+
+ ///
+ /// The path to draw or fill.
+ ///
+ ///
+ /// Left open, the core strokes each rounded border side as its own open path, filling closes it anyway.
+ ///
+ public SKPath GetPath()
+ {
+ return _path ?? (_path = _builder.Detach());
+ }
+
+ public override void Dispose()
+ {
+ _path?.Dispose();
+ _builder.Dispose();
+ }
+ }
+}
diff --git a/Source/HtmlRenderer.SkiaSharp/Adapters/ImageAdapter.cs b/Source/HtmlRenderer.SkiaSharp/Adapters/ImageAdapter.cs
new file mode 100644
index 000000000..c2629b63d
--- /dev/null
+++ b/Source/HtmlRenderer.SkiaSharp/Adapters/ImageAdapter.cs
@@ -0,0 +1,50 @@
+// "Therefore those skilled at the unorthodox
+// are infinite as heaven and earth,
+// inexhaustible as the great rivers.
+// When they come to an end,
+// they begin again,
+// like the days and months;
+// they die and are reborn,
+// like the four seasons."
+//
+// - Sun Tsu,
+// "The Art of War"
+
+using SkiaSharp;
+using TheArtOfDev.HtmlRenderer.Adapters;
+
+namespace TheArtOfDev.HtmlRenderer.SkiaSharp.Adapters
+{
+ ///
+ /// Adapter for SkiaSharp images.
+ ///
+ internal sealed class ImageAdapter : RImage
+ {
+ private readonly SKImage _image;
+
+ public ImageAdapter(SKImage image)
+ {
+ _image = image;
+ }
+
+ public SKImage Image
+ {
+ get { return _image; }
+ }
+
+ public override double Width
+ {
+ get { return _image.Width; }
+ }
+
+ public override double Height
+ {
+ get { return _image.Height; }
+ }
+
+ public override void Dispose()
+ {
+ _image.Dispose();
+ }
+ }
+}
diff --git a/Source/HtmlRenderer.SkiaSharp/Adapters/PenAdapter.cs b/Source/HtmlRenderer.SkiaSharp/Adapters/PenAdapter.cs
new file mode 100644
index 000000000..2b9147c56
--- /dev/null
+++ b/Source/HtmlRenderer.SkiaSharp/Adapters/PenAdapter.cs
@@ -0,0 +1,95 @@
+// "Therefore those skilled at the unorthodox
+// are infinite as heaven and earth,
+// inexhaustible as the great rivers.
+// When they come to an end,
+// they begin again,
+// like the days and months;
+// they die and are reborn,
+// like the four seasons."
+//
+// - Sun Tsu,
+// "The Art of War"
+
+using SkiaSharp;
+using TheArtOfDev.HtmlRenderer.Adapters;
+using TheArtOfDev.HtmlRenderer.Adapters.Entities;
+
+namespace TheArtOfDev.HtmlRenderer.SkiaSharp.Adapters
+{
+ ///
+ /// Adapter for SkiaSharp strokes.
+ ///
+ ///
+ /// The core changes width and dash style of the cached pens before every use, so the paint is set up per draw call.
+ ///
+ internal sealed class PenAdapter : RPen
+ {
+ private readonly SKColor _color;
+
+ private double _width = 1;
+
+ private RDashStyle _dashStyle = RDashStyle.Solid;
+
+ public PenAdapter(SKColor color)
+ {
+ _color = color;
+ }
+
+ public override double Width
+ {
+ get { return _width; }
+ set { _width = value; }
+ }
+
+ ///
+ /// A width between 0 and 1 is drawn 1 wide, like GDI+ and the border width snapping of CSS Values 4 §6.
+ /// Narrower non-antialiased strokes fall between the pixel centers and disappear.
+ ///
+ public float StrokeWidth
+ {
+ get { return _width > 0 && _width < 1 ? 1f : (float)_width; }
+ }
+
+ public override RDashStyle DashStyle
+ {
+ set { _dashStyle = value; }
+ }
+
+ ///
+ /// Sets up the paint to stroke with this pen, the returned path effect has to be disposed after drawing.
+ ///
+ public SKPathEffect Apply(SKPaint paint)
+ {
+ var width = StrokeWidth;
+ paint.Style = SKPaintStyle.Stroke;
+ paint.Color = _color;
+ paint.Shader = null;
+ paint.StrokeWidth = width;
+
+ // The same patterns as GDI+, in multiples of the width
+ float[] intervals;
+ switch (_dashStyle)
+ {
+ case RDashStyle.Dash:
+ intervals = new[] { 3 * width, width };
+ break;
+ case RDashStyle.Dot:
+ intervals = new[] { width, width };
+ break;
+ case RDashStyle.DashDot:
+ intervals = new[] { 3 * width, width, width, width };
+ break;
+ case RDashStyle.DashDotDot:
+ intervals = new[] { 3 * width, width, width, width, width, width };
+ break;
+ default:
+ intervals = null;
+ break;
+ }
+
+ var effect = intervals != null && width > 0 ? SKPathEffect.CreateDash(intervals, 0) : null;
+ paint.PathEffect = effect;
+ return effect;
+ }
+ }
+}
diff --git a/Source/HtmlRenderer.SkiaSharp/Adapters/SkiaSharpAdapter.cs b/Source/HtmlRenderer.SkiaSharp/Adapters/SkiaSharpAdapter.cs
new file mode 100644
index 000000000..d79714cee
--- /dev/null
+++ b/Source/HtmlRenderer.SkiaSharp/Adapters/SkiaSharpAdapter.cs
@@ -0,0 +1,210 @@
+// "Therefore those skilled at the unorthodox
+// are infinite as heaven and earth,
+// inexhaustible as the great rivers.
+// When they come to an end,
+// they begin again,
+// like the days and months;
+// they die and are reborn,
+// like the four seasons."
+//
+// - Sun Tsu,
+// "The Art of War"
+
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Reflection;
+using SkiaSharp;
+using TheArtOfDev.HtmlRenderer.Adapters;
+using TheArtOfDev.HtmlRenderer.Adapters.Entities;
+using TheArtOfDev.HtmlRenderer.Core.Utils;
+using TheArtOfDev.HtmlRenderer.SkiaSharp.Utilities;
+
+namespace TheArtOfDev.HtmlRenderer.SkiaSharp.Adapters
+{
+ ///
+ /// Adapter for the SkiaSharp platform.
+ ///
+ internal sealed class SkiaSharpAdapter : RAdapter
+ {
+ #region Fields and Consts
+
+ private static readonly SkiaSharpAdapter _instance = new SkiaSharpAdapter();
+
+ ///
+ /// The named colors of , e.g. for .NET names the CSS engine doesn't know.
+ ///
+ private static readonly Dictionary _namedColors = CreateNamedColors();
+
+ #endregion
+
+ private SkiaSharpAdapter()
+ {
+ var installed = new HashSet(StringComparer.OrdinalIgnoreCase);
+ foreach (var family in SKFontManager.Default.FontFamilies)
+ {
+ AddFontFamily(new FontFamilyAdapter(family));
+ installed.Add(family);
+ }
+
+ // Same as the other adapters where the fonts exist, else the common Linux and macOS fonts, else the font
+ // the system picks for the generic family. The NoDependencies native assets on Linux have no fontconfig
+ // and can't resolve a generic family. serif isn't mapped by any adapter, see Spec/css21.yml.
+ MapFamily(installed, "monospace", "monospace", "Courier New", "Liberation Mono", "DejaVu Sans Mono", "Menlo", "Courier");
+ MapFamily(installed, "Helvetica", "sans-serif", "Arial", "Liberation Sans");
+ MapFamily(installed, CssConstants.DefaultFont, "sans-serif", "Arial", "Liberation Sans", "DejaVu Sans", "Helvetica");
+ MapFamily(installed, "Arial", "sans-serif", "Liberation Sans", "Helvetica", "DejaVu Sans");
+ MapFamily(installed, "Times New Roman", "serif", "Liberation Serif", "Times", "DejaVu Serif");
+ MapFamily(installed, "Courier New", "monospace", "Liberation Mono", "Courier", "DejaVu Sans Mono", "Menlo");
+ MapFamily(installed, "Consolas", "monospace", "DejaVu Sans Mono", "Liberation Mono", "Menlo");
+ }
+
+ public static SkiaSharpAdapter Instance
+ {
+ get { return _instance; }
+ }
+
+ ///
+ /// Maps a missing family to the first installed candidate, or else to what the system resolves the
+ /// generic family to. The core doesn't chain mappings, so the target has to be installed.
+ ///
+ private void MapFamily(HashSet installed, string family, string generic, params string[] candidates)
+ {
+ if (installed.Contains(family))
+ return;
+
+ foreach (var candidate in candidates)
+ {
+ if (installed.Contains(candidate))
+ {
+ AddFontFamilyMapping(family, candidate);
+ return;
+ }
+ }
+
+ // Not disposed, SkiaSharp returns the same wrapper to everyone who asks for that typeface
+ var match = SKFontManager.Default.MatchFamily(generic);
+ if (match != null && installed.Contains(match.FamilyName))
+ AddFontFamilyMapping(family, match.FamilyName);
+ }
+
+ protected override RColor GetColorInt(string colorName)
+ {
+ return _namedColors.TryGetValue(colorName, out var color) ? Utils.Convert(color) : RColor.Empty;
+ }
+
+ protected override RPen CreatePen(RColor color)
+ {
+ return new PenAdapter(Utils.Convert(color));
+ }
+
+ protected override RBrush CreateSolidBrush(RColor color)
+ {
+ return new BrushAdapter(Utils.Convert(color));
+ }
+
+ protected override RBrush CreateLinearGradientBrush(RPoint p1, RPoint p2, (RColor Color, double Position)[] stops)
+ {
+ var colors = new SKColor[stops.Length];
+ var positions = new float[stops.Length];
+ for (int i = 0; i < stops.Length; i++)
+ {
+ colors[i] = Utils.Convert(stops[i].Color);
+ positions[i] = (float)stops[i].Position;
+ }
+
+ return new BrushAdapter(SKShader.CreateLinearGradient(Utils.Convert(p1), Utils.Convert(p2), colors, positions, SKShaderTileMode.Clamp));
+ }
+
+ protected override RImage ConvertImageInt(object image)
+ {
+ switch (image)
+ {
+ case SKImage skImage:
+ return new ImageAdapter(ToDrawableImage(skImage, false));
+ case SKBitmap bitmap:
+ return new ImageAdapter(SKImage.FromBitmap(bitmap));
+ default:
+ return null;
+ }
+ }
+
+ protected override RImage ImageFromStreamInt(Stream memoryStream)
+ {
+ using (var data = SKData.Create(memoryStream))
+ {
+ var image = data != null ? SKImage.FromEncodedData(data) : null;
+ return image != null ? new ImageAdapter(ToDrawableImage(image, true)) : null;
+ }
+ }
+
+ protected override RFont CreateFontInt(string family, double size, RFontStyle style)
+ {
+ var fontStyle = Convert(style);
+ var typeface = SKFontManager.Default.MatchFamily(family, fontStyle) ?? SKTypeface.FromFamilyName(family, fontStyle);
+ return new FontAdapter(typeface, fontStyle, size);
+ }
+
+ protected override RFont CreateFontInt(RFontFamily family, double size, RFontStyle style)
+ {
+ var familyAdapter = (FontFamilyAdapter)family;
+ if (familyAdapter.Typeface == null)
+ return CreateFontInt(family.Name, size, style);
+
+ return new FontAdapter(familyAdapter.Typeface, Convert(style), size);
+ }
+
+ protected override RFontFamily LoadFontFaceFontInt(byte[] fontBytes, string filePath)
+ {
+ var typeface = SKTypeface.FromData(SKData.CreateCopy(fontBytes));
+ return typeface != null ? new FontFamilyAdapter(typeface) : null;
+ }
+
+ #region Private methods
+
+ ///
+ /// Decodes a lazily decoded image other than JPEG, Skia's PDF backend aborts the process when it draws one.
+ /// A JPEG stays encoded, the PDF embeds it as is instead of as much larger raw pixels.
+ ///
+ private static SKImage ToDrawableImage(SKImage image, bool ownsImage)
+ {
+ if (!image.IsLazyGenerated)
+ return image;
+
+ using (var encoded = image.EncodedData)
+ {
+ var bytes = encoded != null && encoded.Size >= 3 ? encoded.AsSpan() : default;
+ if (bytes.Length >= 3 && bytes[0] == 0xFF && bytes[1] == 0xD8 && bytes[2] == 0xFF)
+ return image;
+ }
+
+ var raster = image.ToRasterImage(true);
+ if (raster == null || ReferenceEquals(raster, image))
+ return image;
+
+ if (ownsImage)
+ image.Dispose();
+ return raster;
+ }
+
+ private static SKFontStyle Convert(RFontStyle style)
+ {
+ var weight = (style & RFontStyle.Bold) != 0 ? SKFontStyleWeight.Bold : SKFontStyleWeight.Normal;
+ var slant = (style & RFontStyle.Italic) != 0 ? SKFontStyleSlant.Italic : SKFontStyleSlant.Upright;
+ return new SKFontStyle(weight, SKFontStyleWidth.Normal, slant);
+ }
+
+ private static Dictionary CreateNamedColors()
+ {
+ var colors = new Dictionary(StringComparer.OrdinalIgnoreCase);
+ foreach (var field in typeof(SKColors).GetFields(BindingFlags.Public | BindingFlags.Static))
+ {
+ if (field.FieldType == typeof(SKColor))
+ colors[field.Name] = (SKColor)field.GetValue(null);
+ }
+ return colors;
+ }
+
+ #endregion
+ }
+}
diff --git a/Source/HtmlRenderer.SkiaSharp/HtmlContainer.cs b/Source/HtmlRenderer.SkiaSharp/HtmlContainer.cs
new file mode 100644
index 000000000..7222a5683
--- /dev/null
+++ b/Source/HtmlRenderer.SkiaSharp/HtmlContainer.cs
@@ -0,0 +1,318 @@
+// "Therefore those skilled at the unorthodox
+// are infinite as heaven and earth,
+// inexhaustible as the great rivers.
+// When they come to an end,
+// they begin again,
+// like the days and months;
+// they die and are reborn,
+// like the four seasons."
+//
+// - Sun Tsu,
+// "The Art of War"
+
+using System;
+using System.Collections.Generic;
+using System.Threading.Tasks;
+using SkiaSharp;
+using TheArtOfDev.HtmlRenderer.Adapters.Entities;
+using TheArtOfDev.HtmlRenderer.Core;
+using TheArtOfDev.HtmlRenderer.Core.Entities;
+using TheArtOfDev.HtmlRenderer.Core.Utils;
+using TheArtOfDev.HtmlRenderer.SkiaSharp.Adapters;
+using TheArtOfDev.HtmlRenderer.SkiaSharp.Utilities;
+
+namespace TheArtOfDev.HtmlRenderer.SkiaSharp
+{
+ ///
+ /// Low level handling of Html Renderer logic, for drawing onto your own .
+ /// For simply rendering a document or an image use .
+ ///
+ ///
+ public sealed class HtmlContainer : IDisposable
+ {
+ #region Fields and Consts
+
+ ///
+ /// The internal core html container
+ ///
+ private readonly HtmlContainerInt _htmlContainerInt;
+
+ #endregion
+
+ ///
+ /// Init.
+ ///
+ public HtmlContainer()
+ {
+ _htmlContainerInt = new HtmlContainerInt(SkiaSharpAdapter.Instance);
+ _htmlContainerInt.SetMargins(0);
+ // One continuous page, painting clips to it
+ _htmlContainerInt.PageSize = new RSize(99999, 99999);
+ _htmlContainerInt.AvoidAsyncImagesLoading = true;
+ _htmlContainerInt.AvoidImagesLateLoading = true;
+ }
+
+ ///
+ /// Raised when the set html document has been fully loaded.
+ /// Allows manipulation of the html dom, scroll position, etc.
+ ///
+ public event EventHandler LoadComplete
+ {
+ add { _htmlContainerInt.LoadComplete += value; }
+ remove { _htmlContainerInt.LoadComplete -= value; }
+ }
+
+ ///
+ /// Raised when an error occurred during html rendering.
+ ///
+ ///
+ /// There is no guarantee that the event will be raised on the main thread, it can be raised on thread-pool thread.
+ ///
+ public event EventHandler RenderError
+ {
+ add { _htmlContainerInt.RenderError += value; }
+ remove { _htmlContainerInt.RenderError -= value; }
+ }
+
+ ///
+ /// Raised when a stylesheet is about to be loaded by file path or URI by link element.
+ /// This event allows to provide the stylesheet manually or provide new source (file or Uri) to load from.
+ /// If no alternative data is provided the original source will be used.
+ ///
+ public event EventHandler StylesheetLoad
+ {
+ add { _htmlContainerInt.StylesheetLoad += value; }
+ remove { _htmlContainerInt.StylesheetLoad -= value; }
+ }
+
+ ///
+ /// Raised when an image is about to be loaded by file path or URI.
+ /// This event allows to provide the image manually as an or ,
+ /// if not handled the image will be loaded from file or download from URI.
+ ///
+ public event EventHandler ImageLoad
+ {
+ add { _htmlContainerInt.ImageLoad += value; }
+ remove { _htmlContainerInt.ImageLoad -= value; }
+ }
+
+ ///
+ /// The internal core html container
+ ///
+ internal HtmlContainerInt HtmlContainerInt
+ {
+ get { return _htmlContainerInt; }
+ }
+
+ ///
+ /// the parsed stylesheet data used for handling the html
+ ///
+ public CssData CssData
+ {
+ get { return _htmlContainerInt.CssData; }
+ }
+
+ ///
+ /// Gets or sets a value indicating if anti-aliasing should be avoided for geometry like backgrounds and borders (default - false).
+ ///
+ public bool AvoidGeometryAntialias
+ {
+ get { return _htmlContainerInt.AvoidGeometryAntialias; }
+ set { _htmlContainerInt.AvoidGeometryAntialias = value; }
+ }
+
+ ///
+ /// The scroll offset of the html.
+ /// This will adjust the rendered html by the given offset so the content will be "scrolled".
+ ///
+ ///
+ /// Element that is rendered at location (50,100) with offset of (0,200) will not be rendered as it
+ /// will be at -100 therefore outside the client rectangle.
+ ///
+ public SKPoint ScrollOffset
+ {
+ get { return Utils.Convert(_htmlContainerInt.ScrollOffset); }
+ set { _htmlContainerInt.ScrollOffset = Utils.Convert(value); }
+ }
+
+ ///
+ /// The top-left most location of the rendered html.
+ /// This will offset the top-left corner of the rendered html.
+ ///
+ public SKPoint Location
+ {
+ get { return Utils.Convert(_htmlContainerInt.Location); }
+ set { _htmlContainerInt.Location = Utils.Convert(value); }
+ }
+
+ ///
+ /// The max width and height of the rendered html.
+ /// The max width will effect the html layout wrapping lines, resize images and tables where possible.
+ /// The max height does NOT effect layout, but will not render outside it (clip).
+ /// can be exceed the max size by layout restrictions (unwrappable line, set image size, etc.).
+ /// Set zero for unlimited (width\height separately).
+ ///
+ public SKSize MaxSize
+ {
+ get { return Utils.Convert(_htmlContainerInt.MaxSize); }
+ set { _htmlContainerInt.MaxSize = Utils.Convert(value); }
+ }
+
+ ///
+ /// The CSS media type @media rules are evaluated against, "screen" by default.
+ /// Set it before .
+ ///
+ public string MediaType
+ {
+ get { return _htmlContainerInt.MediaType ?? SkiaSharpAdapter.Instance.DefaultMediaType; }
+ set { _htmlContainerInt.MediaType = value; }
+ }
+
+ ///
+ /// The actual size of the rendered html (after layout)
+ ///
+ public SKSize ActualSize
+ {
+ get { return Utils.Convert(_htmlContainerInt.ActualSize); }
+ }
+
+ ///
+ /// Get the currently selected text segment in the html.
+ ///
+ public string SelectedText
+ {
+ get { return _htmlContainerInt.SelectedText; }
+ }
+
+ ///
+ /// Copy the currently selected html segment with style.
+ ///
+ public string SelectedHtml
+ {
+ get { return _htmlContainerInt.SelectedHtml; }
+ }
+
+ ///
+ /// Init with optional document and stylesheet.
+ ///
+ /// the html to init with, init empty if not given
+ /// optional: the stylesheet to init with, init default if not given
+ public Task SetHtml(string htmlSource, CssData baseCssData = null)
+ {
+ return _htmlContainerInt.SetHtml(htmlSource, baseCssData);
+ }
+
+ ///
+ /// Get html from the current DOM tree with style if requested.
+ ///
+ /// Optional: controls the way styles are generated when html is generated (default: )
+ /// generated html
+ public string GetHtml(HtmlGenerationStyle styleGen = HtmlGenerationStyle.Inline)
+ {
+ return _htmlContainerInt.GetHtml(styleGen);
+ }
+
+ ///
+ /// Get attribute value of element at the given x,y location by given key.
+ /// If more than one element exist with the attribute at the location the inner most is returned.
+ ///
+ /// the location to find the attribute at
+ /// the attribute key to get value by
+ /// found attribute value or null if not found
+ public string GetAttributeAt(SKPoint location, string attribute)
+ {
+ return _htmlContainerInt.GetAttributeAt(Utils.Convert(location), attribute);
+ }
+
+ ///
+ /// Get all the links in the HTML with the element rectangle and href data.
+ ///
+ /// collection of all the links in the HTML
+ public List> GetLinks()
+ {
+ var linkElements = new List>();
+ foreach (var link in HtmlContainerInt.GetLinks())
+ {
+ linkElements.Add(new LinkElementData(link.Id, link.Href, Utils.Convert(link.Rectangle)));
+ }
+ return linkElements;
+ }
+
+ ///
+ /// Get css link href at the given x,y location.
+ ///
+ /// the location to find the link at
+ /// css link href if exists or null
+ public string GetLinkAt(SKPoint location)
+ {
+ return _htmlContainerInt.GetLinkAt(Utils.Convert(location));
+ }
+
+ ///
+ /// Get the rectangle of html element as calculated by html layout.
+ /// Element if found by id (id attribute on the html element).
+ /// Note: to get the screen rectangle you need to adjust by the hosting control.
+ ///
+ /// the id of the element to get its rectangle
+ /// the rectangle of the element or null if not found
+ public SKRect? GetElementRectangle(string elementId)
+ {
+ var r = _htmlContainerInt.GetElementRectangle(elementId);
+ return r.HasValue ? Utils.Convert(r.Value) : (SKRect?)null;
+ }
+
+ ///
+ /// Measures the bounds of box and children, recursively.
+ ///
+ ///
+ /// Skia measures text without a canvas, so the layout doesn't depend on where it's drawn later.
+ ///
+ public void PerformLayout()
+ {
+ using (var ig = new GraphicsAdapter())
+ {
+ _htmlContainerInt.PerformLayout(ig);
+ }
+ }
+
+ ///
+ /// Render the html onto the given canvas.
+ ///
+ /// the canvas to draw on
+ public void PerformPaint(SKCanvas canvas)
+ {
+ ArgChecker.AssertArgNotNull(canvas, "canvas");
+
+ var clip = canvas.LocalClipBounds;
+ using (var ig = new GraphicsAdapter(canvas, Utils.Convert(clip)))
+ {
+ _htmlContainerInt.PerformPaint(ig);
+ }
+ }
+
+ ///
+ /// The fragment tree of the last , one fragmentainer per page.
+ ///
+ internal Core.Fragments.FragmentTree FragmentTree
+ {
+ get { return _htmlContainerInt.FragmentTree; }
+ }
+
+ ///
+ /// Render one page onto the given canvas.
+ ///
+ internal void PerformPaint(SKCanvas canvas, Core.Fragments.FragmentainerFragment fragmentainer)
+ {
+ var clip = canvas.LocalClipBounds;
+ using (var ig = new GraphicsAdapter(canvas, Utils.Convert(clip)))
+ {
+ _htmlContainerInt.PerformPaint(ig, fragmentainer);
+ }
+ }
+
+ public void Dispose()
+ {
+ _htmlContainerInt.Dispose();
+ }
+ }
+}
diff --git a/Source/HtmlRenderer.SkiaSharp/HtmlRender.cs b/Source/HtmlRenderer.SkiaSharp/HtmlRender.cs
new file mode 100644
index 000000000..6d8982eb4
--- /dev/null
+++ b/Source/HtmlRenderer.SkiaSharp/HtmlRender.cs
@@ -0,0 +1,335 @@
+// "Therefore those skilled at the unorthodox
+// are infinite as heaven and earth,
+// inexhaustible as the great rivers.
+// When they come to an end,
+// they begin again,
+// like the days and months;
+// they die and are reborn,
+// like the four seasons."
+//
+// - Sun Tsu,
+// "The Art of War"
+
+using System;
+using System.Threading.Tasks;
+using SkiaSharp;
+using TheArtOfDev.HtmlRenderer.Adapters.Entities;
+using TheArtOfDev.HtmlRenderer.Core;
+using TheArtOfDev.HtmlRenderer.Core.Entities;
+using TheArtOfDev.HtmlRenderer.Core.Utils;
+using TheArtOfDev.HtmlRenderer.SkiaSharp.Adapters;
+using TheArtOfDev.HtmlRenderer.SkiaSharp.Utilities;
+
+namespace TheArtOfDev.HtmlRenderer.SkiaSharp
+{
+ ///
+ /// Standalone static class for simple and direct HTML rendering with SkiaSharp.
+ /// For low-level control and performance consider using .
+ ///
+ ///
+ ///
+ /// Overwrite stylesheet resolution
+ /// Exposed by optional "stylesheetLoad" delegate argument.
+ /// Invoked when a stylesheet is about to be loaded by file path or URL in 'link' element.
+ /// Allows to overwrite the loaded stylesheet by providing the stylesheet data manually, or different source (file or URL) to load from.
+ /// If no alternative data is provided the original source will be used.
+ ///
+ ///
+ /// Overwrite image resolution
+ /// Exposed by optional "imageLoad" delegate argument.
+ /// Invoked when an image is about to be loaded by file path, URL or inline data in 'img' element or background-image CSS style.
+ /// Allows to overwrite the loaded image by providing an or , or different source (file or URL) to load from.
+ /// If no alternative data is provided the original source will be used.
+ ///
+ ///
+ ///
+ ///
+ /// Simple rendering
+ /// await HtmlRender.RenderAsync(canvas, "Hello World]]>");
+ /// await HtmlRender.RenderAsync(canvas, "Hello World]]>", 10, 10, 500, CssData.Parse("body {font-size: 20px}")");
+ ///
+ ///
+ /// Image rendering
+ /// using var image = await HtmlRender.RenderToImageAsync("Hello World]]>", new SKSizeI(600, 400));
+ /// using var image = await HtmlRender.RenderToImageAsync("Hello World]]>", 600);
+ ///
+ ///
+ public static class HtmlRender
+ {
+ private const int MaxUnlimitedWidth = 4096;
+
+ // 4096 x 32768 RGBA are 512 MB
+ private const int MaxUnlimitedHeight = 32768;
+
+ ///
+ /// Adds a typeface that isn't installed, e.g. loaded from a file, as a font family to be used in html rendering.
+ /// The family is available by the typeface's family name.
+ ///
+ /// The typeface to add.
+ public static void AddFontFamily(SKTypeface typeface)
+ {
+ ArgChecker.AssertArgNotNull(typeface, "typeface");
+
+ SkiaSharpAdapter.Instance.AddFontFamily(new FontFamilyAdapter(typeface));
+ }
+
+ ///
+ /// Adds a font mapping from to iff the is not found.
+ /// When the font is used in rendered html and is not found in existing
+ /// fonts (installed or added) it will be replaced by .
+ ///
+ ///
+ /// This fonts mapping can be used as a fallback in case the requested font is not installed in the client system.
+ ///
+ /// the font family to replace
+ /// the font family to replace with
+ public static void AddFontFamilyMapping(string fromFamily, string toFamily)
+ {
+ ArgChecker.AssertArgNotNullOrEmpty(fromFamily, "fromFamily");
+ ArgChecker.AssertArgNotNullOrEmpty(toFamily, "toFamily");
+
+ SkiaSharpAdapter.Instance.AddFontFamilyMapping(fromFamily, toFamily);
+ }
+
+ ///
+ /// Parse the given stylesheet to object.
+ /// If is true the parsed css blocks are added to the
+ /// default css data (as defined by W3), merged if class name already exists. If false only the data in the given stylesheet is returned.
+ ///
+ /// the stylesheet source to parse
+ /// true - combine the parsed css data with default css data, false - return only the parsed css data
+ /// the parsed css data
+ public static CssData ParseStyleSheet(string stylesheet, bool combineWithDefault = true)
+ {
+ return CssData.Parse(SkiaSharpAdapter.Instance, stylesheet, combineWithDefault);
+ }
+
+ ///
+ /// Measure the size (width and height) required to draw the given html under given max width restriction.
+ /// If no max width restriction is given the layout will use the maximum possible width required by the content,
+ /// it can be the longest text line or full image width.
+ ///
+ /// HTML source to render
+ /// optional: bound the width of the html to render in (default - 0, unlimited)
+ /// optional: the style to use for html rendering (default - use W3 default style)
+ /// optional: can be used to overwrite stylesheet resolution logic
+ /// optional: can be used to overwrite image resolution logic
+ /// the size required for the html
+ public static async Task MeasureAsync(string html, float maxWidth = 0, CssData cssData = null,
+ EventHandler stylesheetLoad = null, EventHandler imageLoad = null)
+ {
+ if (string.IsNullOrEmpty(html))
+ return SKSize.Empty;
+
+ using (var container = CreateContainer(stylesheetLoad, imageLoad))
+ {
+ container.MaxSize = new SKSize(maxWidth, 0);
+ await container.SetHtml(html, cssData).ConfigureAwait(false);
+ container.PerformLayout();
+ return container.ActualSize;
+ }
+ }
+
+ ///
+ /// Renders the specified HTML source on the specified location and max width restriction.
+ /// If is zero the html will use all the required width, otherwise it will perform line
+ /// wrap as specified in the html
+ /// Returned is the actual width and height of the rendered html.
+ ///
+ /// the canvas to draw on
+ /// HTML source to render
+ /// optional: the left most location to start render the html at (default - 0)
+ /// optional: the top most location to start render the html at (default - 0)
+ /// optional: bound the width of the html to render in (default - 0, unlimited)
+ /// optional: the style to use for html rendering (default - use W3 default style)
+ /// optional: can be used to overwrite stylesheet resolution logic
+ /// optional: can be used to overwrite image resolution logic
+ /// the actual size of the rendered html
+ public static Task RenderAsync(SKCanvas canvas, string html, float left = 0, float top = 0, float maxWidth = 0, CssData cssData = null,
+ EventHandler stylesheetLoad = null, EventHandler imageLoad = null)
+ {
+ return RenderAsync(canvas, html, new SKPoint(left, top), new SKSize(maxWidth, 0), cssData, stylesheetLoad, imageLoad);
+ }
+
+ ///
+ /// Renders the specified HTML source on the specified location and max size restriction.
+ /// If .Width is zero the html will use all the required width, otherwise it will perform line
+ /// wrap as specified in the html
+ /// If .Height is zero the html will use all the required height, otherwise it will clip at the
+ /// given max height not rendering the html below it.
+ /// Returned is the actual width and height of the rendered html.
+ ///
+ /// the canvas to draw on
+ /// HTML source to render
+ /// the top-left most location to start render the html at
+ /// the max size of the rendered html (if height above zero it will be clipped)
+ /// optional: the style to use for html rendering (default - use W3 default style)
+ /// optional: can be used to overwrite stylesheet resolution logic
+ /// optional: can be used to overwrite image resolution logic
+ /// the actual size of the rendered html
+ public static async Task RenderAsync(SKCanvas canvas, string html, SKPoint location, SKSize maxSize, CssData cssData = null,
+ EventHandler stylesheetLoad = null, EventHandler imageLoad = null)
+ {
+ ArgChecker.AssertArgNotNull(canvas, "canvas");
+
+ if (string.IsNullOrEmpty(html))
+ return SKSize.Empty;
+
+ using (var container = CreateContainer(stylesheetLoad, imageLoad))
+ {
+ container.Location = location;
+ container.MaxSize = maxSize;
+ await container.SetHtml(html, cssData).ConfigureAwait(false);
+ container.PerformLayout();
+
+ var saveCount = canvas.Save();
+ try
+ {
+ if (maxSize.Height > 0)
+ canvas.ClipRect(SKRect.Create(location, maxSize));
+
+ container.PerformPaint(canvas);
+ }
+ finally
+ {
+ canvas.RestoreToCount(saveCount);
+ }
+
+ return container.ActualSize;
+ }
+ }
+
+ ///
+ /// Renders the specified HTML into a new image of the requested size.
+ /// The HTML will be layout by the given size but will be clipped if cannot fit.
+ ///
+ /// HTML source to render
+ /// The size of the image to render into, layout html by width and clipped by height
+ /// optional: the color to fill the image with (default - white), can be transparent
+ /// optional: the style to use for html rendering (default - use W3 default style)
+ /// optional: can be used to overwrite stylesheet resolution logic
+ /// optional: can be used to overwrite image resolution logic
+ /// the generated image of the html
+ public static async Task RenderToImageAsync(string html, SKSizeI size, SKColor? backgroundColor = null, CssData cssData = null,
+ EventHandler stylesheetLoad = null, EventHandler imageLoad = null)
+ {
+ using (var surface = CreateSurface(size))
+ {
+ var canvas = surface.Canvas;
+ canvas.Clear(backgroundColor ?? SKColors.White);
+
+ if (!string.IsNullOrEmpty(html))
+ await RenderAsync(canvas, html, SKPoint.Empty, size, cssData, stylesheetLoad, imageLoad).ConfigureAwait(false);
+
+ return surface.Snapshot();
+ }
+ }
+
+ ///
+ /// Renders the specified HTML into a new image of unknown size that will be determined by max width/height and HTML layout.
+ /// If is zero the html will use all the required width, otherwise it will perform line
+ /// wrap as specified in the html
+ /// If is zero the html will use all the required height, otherwise it will clip at the
+ /// given max height not rendering the html below it.
+ ///
+ /// HTML source to render
+ /// optional: the max width of the rendered html, if not zero and html cannot be layout within the limit it will be clipped
+ /// optional: the max height of the rendered html, if not zero and html cannot be layout within the limit it will be clipped
+ /// optional: the color to fill the image with (default - white), can be transparent
+ /// optional: the style to use for html rendering (default - use W3 default style)
+ /// optional: can be used to overwrite stylesheet resolution logic
+ /// optional: can be used to overwrite image resolution logic
+ /// the generated image of the html
+ public static Task RenderToImageAsync(string html, int maxWidth = 0, int maxHeight = 0, SKColor? backgroundColor = null, CssData cssData = null,
+ EventHandler stylesheetLoad = null, EventHandler imageLoad = null)
+ {
+ return RenderToImageAsync(html, SKSizeI.Empty, new SKSizeI(maxWidth, maxHeight), backgroundColor, cssData, stylesheetLoad, imageLoad);
+ }
+
+ ///
+ /// Renders the specified HTML into a new image of unknown size that will be determined by min/max width/height and HTML layout.
+ /// If is zero the html will use all the required width, otherwise it will perform line
+ /// wrap as specified in the html
+ /// If is zero the html will use all the required height, otherwise it will clip at the
+ /// given max height not rendering the html below it.
+ /// If (Width/Height) is above zero the rendered image will not be smaller than the given min size.
+ ///
+ /// HTML source to render
+ /// optional: the min size of the rendered html (zero - not limit the width/height)
+ /// optional: the max size of the rendered html, if not zero and html cannot be layout within the limit it will be clipped (zero - not limit the width/height)
+ /// optional: the color to fill the image with (default - white), can be transparent
+ /// optional: the style to use for html rendering (default - use W3 default style)
+ /// optional: can be used to overwrite stylesheet resolution logic
+ /// optional: can be used to overwrite image resolution logic
+ /// the generated image of the html
+ public static async Task RenderToImageAsync(string html, SKSizeI minSize, SKSizeI maxSize, SKColor? backgroundColor = null, CssData cssData = null,
+ EventHandler stylesheetLoad = null, EventHandler imageLoad = null)
+ {
+ using (var container = CreateContainer(stylesheetLoad, imageLoad))
+ {
+ var finalSize = minSize;
+ if (!string.IsNullOrEmpty(html))
+ {
+ await container.SetHtml(html, cssData).ConfigureAwait(false);
+ finalSize = MeasureHtmlByRestrictions(container, minSize, maxSize);
+ container.MaxSize = finalSize;
+ }
+
+ using (var surface = CreateSurface(finalSize))
+ {
+ var canvas = surface.Canvas;
+ canvas.Clear(backgroundColor ?? SKColors.White);
+
+ if (!string.IsNullOrEmpty(html))
+ container.PerformPaint(canvas);
+
+ return surface.Snapshot();
+ }
+ }
+ }
+
+ #region Private methods
+
+ private static HtmlContainer CreateContainer(EventHandler stylesheetLoad, EventHandler imageLoad)
+ {
+ var container = new HtmlContainer();
+ if (stylesheetLoad != null)
+ container.StylesheetLoad += stylesheetLoad;
+ if (imageLoad != null)
+ container.ImageLoad += imageLoad;
+ return container;
+ }
+
+ ///
+ /// A raster surface, a zero size becomes a single pixel, Skia can't create an empty one.
+ ///
+ private static SKSurface CreateSurface(SKSizeI size)
+ {
+ var info = new SKImageInfo(Math.Max(size.Width, 1), Math.Max(size.Height, 1), SKColorType.Rgba8888, SKAlphaType.Premul);
+ return SKSurface.Create(info)
+ ?? throw new InvalidOperationException($"Skia can't allocate an image of {info.Width}x{info.Height} pixels, limit the size with a max width and height.");
+ }
+
+ ///
+ /// Measure the size of the html by performing layout under the given restrictions.
+ ///
+ private static SKSizeI MeasureHtmlByRestrictions(HtmlContainer htmlContainer, SKSizeI minSize, SKSizeI maxSize)
+ {
+ using (var g = new GraphicsAdapter())
+ {
+ var size = HtmlRendererUtils.MeasureHtmlByRestrictions(g, htmlContainer.HtmlContainerInt,
+ new RSize(minSize.Width, minSize.Height), new RSize(maxSize.Width, maxSize.Height));
+
+ // Without a limit an unbreakable line or a long document could ask for a huge surface
+ if (maxSize.Width < 1 && size.Width > MaxUnlimitedWidth)
+ size.Width = MaxUnlimitedWidth;
+ if (maxSize.Height < 1 && size.Height > MaxUnlimitedHeight)
+ size.Height = MaxUnlimitedHeight;
+
+ return Utils.ConvertRound(size);
+ }
+ }
+
+ #endregion
+ }
+}
diff --git a/Source/HtmlRenderer.SkiaSharp/HtmlRenderer.SkiaSharp.csproj b/Source/HtmlRenderer.SkiaSharp/HtmlRenderer.SkiaSharp.csproj
new file mode 100644
index 000000000..dced87213
--- /dev/null
+++ b/Source/HtmlRenderer.SkiaSharp/HtmlRenderer.SkiaSharp.csproj
@@ -0,0 +1,38 @@
+
+
+ netstandard2.0;net8.0
+ Library
+ TheArtOfDev.HtmlRenderer.SkiaSharp
+
+
+
+ HtmlRenderer.SkiaSharp
+ HTML Renderer for SkiaSharp
+ html render renderer draw skia skiasharp image pdf
+ HTML and CSS rendering onto a SkiaSharp canvas, into images and into PDF documents, 100% managed (C#) layout on top of SkiaSharp, on Windows, Linux and macOS.
+
+Features and Benefits:
+---
+* 100% managed layout, depends only on SkiaSharp and HarfBuzzSharp, no browser engine.
+* HTML5 parsing and a modern CSS engine.
+* Renders onto any SKCanvas, into an SKImage of a given or measured size, or into a paginated PDF.
+* Text shaping with HarfBuzz and font fallback for scripts the chosen font lacks.
+* Support separating CSS from HTML by loading stylesheet code separately.
+* Handles "real world" malformed HTML, it doesn't have to be XHTML.
+* Extendable and configurable.
+ HTML and CSS rendering onto a SkiaSharp canvas, into images and into PDF documents, 100% managed (C#) layout on top of SkiaSharp.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Source/HtmlRenderer.SkiaSharp/PdfGenerateConfig.cs b/Source/HtmlRenderer.SkiaSharp/PdfGenerateConfig.cs
new file mode 100644
index 000000000..5d22a240d
--- /dev/null
+++ b/Source/HtmlRenderer.SkiaSharp/PdfGenerateConfig.cs
@@ -0,0 +1,88 @@
+// "Therefore those skilled at the unorthodox
+// are infinite as heaven and earth,
+// inexhaustible as the great rivers.
+// When they come to an end,
+// they begin again,
+// like the days and months;
+// they die and are reborn,
+// like the four seasons."
+//
+// - Sun Tsu,
+// "The Art of War"
+
+using SkiaSharp;
+
+namespace TheArtOfDev.HtmlRenderer.SkiaSharp
+{
+ ///
+ /// The configuration for : page size, margins and document metadata.
+ ///
+ ///
+ /// Sizes are in points (1/72 inch) like everything in a PDF, a CSS pixel is 0.75pt.
+ ///
+ public sealed class PdfGenerateConfig
+ {
+ ///
+ /// The size of each page in points, by default.
+ ///
+ public SKSize PageSize { get; set; } = PdfPageSizes.A4;
+
+ ///
+ /// The space between the top of the page and the content, in points.
+ ///
+ public float MarginTop { get; set; } = 36;
+
+ ///
+ /// The space between the bottom of the page and the content, in points.
+ ///
+ public float MarginBottom { get; set; } = 36;
+
+ ///
+ /// The space between the left of the page and the content, in points.
+ ///
+ public float MarginLeft { get; set; } = 36;
+
+ ///
+ /// The space between the right of the page and the content, in points.
+ ///
+ public float MarginRight { get; set; } = 36;
+
+ ///
+ /// The document's title, author etc., by default.
+ /// An encoding quality or raster DPI of 0 uses the value of .
+ ///
+ public SKDocumentPdfMetadata Metadata { get; set; } = SKDocumentPdfMetadata.Default;
+
+ ///
+ /// Set all 4 margins to the given value, in points.
+ ///
+ public void SetMargins(float value)
+ {
+ MarginTop = MarginBottom = MarginLeft = MarginRight = value;
+ }
+ }
+
+ ///
+ /// Common paper sizes in points, portrait.
+ ///
+ public static class PdfPageSizes
+ {
+ public static readonly SKSize A3 = new SKSize(842, 1191);
+
+ public static readonly SKSize A4 = new SKSize(595, 842);
+
+ public static readonly SKSize A5 = new SKSize(420, 595);
+
+ public static readonly SKSize Letter = new SKSize(612, 792);
+
+ public static readonly SKSize Legal = new SKSize(612, 1008);
+
+ ///
+ /// The same size turned by 90 degrees.
+ ///
+ public static SKSize Landscape(SKSize size)
+ {
+ return new SKSize(size.Height, size.Width);
+ }
+ }
+}
diff --git a/Source/HtmlRenderer.SkiaSharp/PdfGenerator.cs b/Source/HtmlRenderer.SkiaSharp/PdfGenerator.cs
new file mode 100644
index 000000000..3d6d368df
--- /dev/null
+++ b/Source/HtmlRenderer.SkiaSharp/PdfGenerator.cs
@@ -0,0 +1,226 @@
+// "Therefore those skilled at the unorthodox
+// are infinite as heaven and earth,
+// inexhaustible as the great rivers.
+// When they come to an end,
+// they begin again,
+// like the days and months;
+// they die and are reborn,
+// like the four seasons."
+//
+// - Sun Tsu,
+// "The Art of War"
+
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Threading.Tasks;
+using SkiaSharp;
+using TheArtOfDev.HtmlRenderer.Adapters.Entities;
+using TheArtOfDev.HtmlRenderer.Core;
+using TheArtOfDev.HtmlRenderer.Core.Entities;
+using TheArtOfDev.HtmlRenderer.Core.Fragments;
+using TheArtOfDev.HtmlRenderer.Core.Utils;
+
+namespace TheArtOfDev.HtmlRenderer.SkiaSharp
+{
+ ///
+ /// Creates PDF documents from HTML with SkiaSharp's PDF backend, one page per page of the paginated layout.
+ ///
+ ///
+ /// The document is laid out for @media print, links to URLs and to elements of the document stay
+ /// clickable. SkiaSharp's PDF backend embeds the complete font files, it doesn't subset them.
+ ///
+ ///
+ /// using var stream = File.Create("document.pdf");
+ /// await PdfGenerator.GeneratePdfAsync("Hello World]]>", stream);
+ ///
+ public static class PdfGenerator
+ {
+ ///
+ /// CSS pixels to points, CSS 2.1 §4.3.2 fixes 1px at 1/96 inch.
+ ///
+ private const float PointsPerPixel = 72f / 96f;
+
+ ///
+ /// Create a PDF document from the given HTML and write it to the stream.
+ ///
+ /// HTML source to create the PDF from
+ /// the stream to write the PDF to, left open
+ /// optional: page size, margins and metadata (default - A4 with 0.5 inch margins)
+ /// optional: the style to use for HTML rendering (default - use W3 default style)
+ /// optional: can be used to overwrite stylesheet resolution logic
+ /// optional: can be used to overwrite image resolution logic
+ /// the number of pages written
+ public static async Task GeneratePdfAsync(string html, Stream stream, PdfGenerateConfig config = null, CssData cssData = null,
+ EventHandler stylesheetLoad = null, EventHandler imageLoad = null)
+ {
+ ArgChecker.AssertArgNotNull(stream, "stream");
+ config = config ?? new PdfGenerateConfig();
+
+ var pageWidth = config.PageSize.Width / PointsPerPixel;
+ var pageHeight = config.PageSize.Height / PointsPerPixel;
+ var marginLeft = (int)Math.Round(config.MarginLeft / PointsPerPixel);
+ var marginTop = (int)Math.Round(config.MarginTop / PointsPerPixel);
+ var marginRight = (int)Math.Round(config.MarginRight / PointsPerPixel);
+ var marginBottom = (int)Math.Round(config.MarginBottom / PointsPerPixel);
+ var contentSize = new RSize(pageWidth - marginLeft - marginRight, pageHeight - marginTop - marginBottom);
+
+ using (var document = SKDocument.CreatePdf(stream, GetMetadata(config)))
+ {
+ var pageCount = 0;
+ if (!string.IsNullOrEmpty(html))
+ {
+ using (var container = new HtmlContainer())
+ {
+ if (stylesheetLoad != null)
+ container.StylesheetLoad += stylesheetLoad;
+ if (imageLoad != null)
+ container.ImageLoad += imageLoad;
+
+ container.MediaType = "print";
+ container.Location = new SKPoint(marginLeft, marginTop);
+ container.MaxSize = new SKSize((float)contentSize.Width, 0);
+ await container.SetHtml(html, cssData).ConfigureAwait(false);
+
+ var containerInt = container.HtmlContainerInt;
+ containerInt.PageSize = contentSize;
+ containerInt.MarginLeft = marginLeft;
+ containerInt.MarginTop = marginTop;
+ containerInt.MarginRight = marginRight;
+ containerInt.MarginBottom = marginBottom;
+ container.PerformLayout();
+
+ var fragmentainers = container.FragmentTree?.Fragmentainers ?? Array.Empty();
+ var anchors = GetAnchorDestinations(container, fragmentainers);
+
+ foreach (var fragmentainer in fragmentainers)
+ {
+ var canvas = document.BeginPage(config.PageSize.Width, config.PageSize.Height);
+ canvas.Scale(PointsPerPixel);
+ canvas.ClipRect(SKRect.Create((float)pageWidth, (float)pageHeight));
+
+ container.PerformPaint(canvas, fragmentainer);
+ DrawLinks(canvas, container, fragmentainer, anchors);
+
+ document.EndPage();
+ pageCount++;
+ }
+ }
+ }
+
+ // A PDF needs a page, an empty document gets a blank one
+ if (pageCount == 0)
+ {
+ document.BeginPage(config.PageSize.Width, config.PageSize.Height);
+ document.EndPage();
+ pageCount = 1;
+ }
+
+ document.Close();
+ return pageCount;
+ }
+ }
+
+ ///
+ /// Create a PDF document from the given HTML.
+ ///
+ /// HTML source to create the PDF from
+ /// optional: page size, margins and metadata (default - A4 with 0.5 inch margins)
+ /// optional: the style to use for HTML rendering (default - use W3 default style)
+ /// optional: can be used to overwrite stylesheet resolution logic
+ /// optional: can be used to overwrite image resolution logic
+ /// the PDF file's bytes
+ public static async Task GeneratePdfAsync(string html, PdfGenerateConfig config = null, CssData cssData = null,
+ EventHandler stylesheetLoad = null, EventHandler imageLoad = null)
+ {
+ using (var stream = new MemoryStream())
+ {
+ await GeneratePdfAsync(html, stream, config, cssData, stylesheetLoad, imageLoad).ConfigureAwait(false);
+ return stream.ToArray();
+ }
+ }
+
+ #region Private methods
+
+ ///
+ /// is a struct, so new SKDocumentPdfMetadata { Title = ... } leaves the encoding quality
+ /// and raster DPI at 0 instead of the defaults, and Skia then stores every opaque image as a quality 0 JPEG.
+ ///
+ private static SKDocumentPdfMetadata GetMetadata(PdfGenerateConfig config)
+ {
+ var metadata = config.Metadata;
+ if (metadata.EncodingQuality <= 0)
+ metadata.EncodingQuality = SKDocumentPdfMetadata.Default.EncodingQuality;
+ if (metadata.RasterDpi <= 0)
+ metadata.RasterDpi = SKDocumentPdfMetadata.Default.RasterDpi;
+ return metadata;
+ }
+
+ ///
+ /// The page and position of each element an anchor link points to, keyed by the element id.
+ ///
+ private static Dictionary GetAnchorDestinations(HtmlContainer container, IReadOnlyList fragmentainers)
+ {
+ var destinations = new Dictionary();
+ foreach (var link in container.GetLinks())
+ {
+ if (!link.IsAnchor || link.AnchorId.Length == 0 || destinations.ContainsKey(link.AnchorId))
+ continue;
+
+ var rect = container.GetElementRectangle(link.AnchorId);
+ if (!rect.HasValue)
+ continue;
+
+ var page = PageContaining(fragmentainers, rect.Value.Top);
+ if (page != null)
+ destinations[link.AnchorId] = (page, new SKPoint(rect.Value.Left, (float)(rect.Value.Top - page.LocalOriginY)));
+ }
+ return destinations;
+ }
+
+ ///
+ /// Adds the link annotations and anchor destinations that fall on the page.
+ ///
+ private static void DrawLinks(SKCanvas canvas, HtmlContainer container, FragmentainerFragment page, Dictionary anchors)
+ {
+ foreach (var anchor in anchors)
+ {
+ if (anchor.Value.Page == page)
+ canvas.DrawNamedDestinationAnnotation(anchor.Value.Point, anchor.Key);
+ }
+
+ var bandTop = page.Geometry.Top;
+ var bandBottom = bandTop + page.Geometry.Height;
+ foreach (var link in container.GetLinks())
+ {
+ var rect = link.Rectangle;
+ if (rect.Top >= bandBottom || rect.Bottom <= bandTop)
+ continue;
+
+ var pageRect = SKRect.Create(rect.Left, (float)(rect.Top - page.LocalOriginY), rect.Width, rect.Height);
+ if (link.IsAnchor)
+ {
+ if (anchors.ContainsKey(link.AnchorId))
+ canvas.DrawLinkDestinationAnnotation(pageRect, link.AnchorId);
+ }
+ else if (!string.IsNullOrEmpty(link.Href))
+ {
+ canvas.DrawUrlAnnotation(pageRect, link.Href);
+ }
+ }
+ }
+
+ private static FragmentainerFragment PageContaining(IReadOnlyList fragmentainers, double y)
+ {
+ foreach (var fragmentainer in fragmentainers)
+ {
+ var bandTop = fragmentainer.Geometry.Top;
+ if (y >= bandTop && y < bandTop + fragmentainer.Geometry.Height)
+ return fragmentainer;
+ }
+ return null;
+ }
+
+ #endregion
+ }
+}
diff --git a/Source/HtmlRenderer.SkiaSharp/README.md b/Source/HtmlRenderer.SkiaSharp/README.md
new file mode 100644
index 000000000..60cb81f67
--- /dev/null
+++ b/Source/HtmlRenderer.SkiaSharp/README.md
@@ -0,0 +1,52 @@
+# Welcome to the HTML Renderer SkiaSharp library!
+
+This library renders HTML snippets onto a SkiaSharp canvas, into images and into PDF documents, on Windows, Linux and macOS.
+For more info see HTML Renderer on GitHub: https://github.com/ArthurHub/HTML-Renderer
+
+## REQUIREMENTS
+
+- .NET Standard 2.0 or .NET 8.0 and newer
+- On Linux, references to `SkiaSharp.NativeAssets.Linux` and `HarfBuzzSharp.NativeAssets.Linux`, as the `SkiaSharp` and `HarfBuzzSharp` packages only ship the native libraries for Windows and macOS. Note that `SkiaSharp.NativeAssets.Linux.NoDependencies` works as well, but has no fontconfig, so there's no fallback font for characters the chosen font lacks, they render as boxes
+
+## LIMITATIONS
+
+- Text is shaped per word with HarfBuzz, so right-to-left words read correctly, but a line that mixes directions isn't reordered as a whole
+- PDFs embed the complete font files, SkiaSharp's PDF backend doesn't subset them, so a PDF with a few fonts easily gets a few MB. Fallback fonts count as well: a single line of Chinese or Japanese pulls in a whole system font collection such as Microsoft YaHei or Yu Gothic, which can add well over 10 MB. If the size matters, provide a small font that covers the text via `@font-face` or `HtmlRender.AddFontFamily`
+
+## FEEDBACK / RELEASE NOTES
+
+If you have problems, wish to report a bug, or have a suggestion, please open an issue on the
+HTML Renderer issue page: https://github.com/ArthurHub/HTML-Renderer/issues
+
+For full release notes and all versions see: https://github.com/ArthurHub/HTML-Renderer/releases
+
+---
+
+## Quick Start: Create image from HTML snippet
+
+```csharp
+using SKImage image = await HtmlRender.RenderToImageAsync("
Hello World
This is html rendered text
");
+using SKData png = image.Encode(SKEncodedImageFormat.Png, 100);
+File.WriteAllBytes("image.png", png.ToArray());
+```
+
+## Quick Start: Create PDF from HTML snippet
+
+```csharp
+using FileStream stream = File.Create("document.pdf");
+await PdfGenerator.GeneratePdfAsync("
Hello World
This is html rendered text", stream);
+```
+
+The page size and margins are in points, e.g. `new PdfGenerateConfig { PageSize = PdfPageSizes.Letter }`.
+
+## Quick Start: Draw onto an existing canvas
+
+```csharp
+SKSize size = await HtmlRender.RenderAsync(canvas, "
Hello World
This is html rendered text", 10, 10, 500);
+```
+
+## Quick Start: Use a font that isn't installed
+
+```csharp
+HtmlRender.AddFontFamily(SKTypeface.FromFile("CustomFont.ttf"));
+```
diff --git a/Source/HtmlRenderer.SkiaSharp/Utilities/Utils.cs b/Source/HtmlRenderer.SkiaSharp/Utilities/Utils.cs
new file mode 100644
index 000000000..618e6c337
--- /dev/null
+++ b/Source/HtmlRenderer.SkiaSharp/Utilities/Utils.cs
@@ -0,0 +1,68 @@
+// "Therefore those skilled at the unorthodox
+// are infinite as heaven and earth,
+// inexhaustible as the great rivers.
+// When they come to an end,
+// they begin again,
+// like the days and months;
+// they die and are reborn,
+// like the four seasons."
+//
+// - Sun Tsu,
+// "The Art of War"
+
+using SkiaSharp;
+using TheArtOfDev.HtmlRenderer.Adapters.Entities;
+
+namespace TheArtOfDev.HtmlRenderer.SkiaSharp.Utilities
+{
+ ///
+ /// Conversions between the core and the SkiaSharp types.
+ ///
+ internal static class Utils
+ {
+ public static RPoint Convert(SKPoint p)
+ {
+ return new RPoint(p.X, p.Y);
+ }
+
+ public static SKPoint Convert(RPoint p)
+ {
+ return new SKPoint((float)p.X, (float)p.Y);
+ }
+
+ public static RSize Convert(SKSize s)
+ {
+ return new RSize(s.Width, s.Height);
+ }
+
+ public static SKSize Convert(RSize s)
+ {
+ return new SKSize((float)s.Width, (float)s.Height);
+ }
+
+ public static SKSizeI ConvertRound(RSize s)
+ {
+ return new SKSizeI((int)System.Math.Round(s.Width), (int)System.Math.Round(s.Height));
+ }
+
+ public static RRect Convert(SKRect r)
+ {
+ return new RRect(r.Left, r.Top, r.Width, r.Height);
+ }
+
+ public static SKRect Convert(RRect r)
+ {
+ return SKRect.Create((float)r.X, (float)r.Y, (float)r.Width, (float)r.Height);
+ }
+
+ public static RColor Convert(SKColor c)
+ {
+ return RColor.FromArgb(c.Alpha, c.Red, c.Green, c.Blue);
+ }
+
+ public static SKColor Convert(RColor c)
+ {
+ return new SKColor(c.R, c.G, c.B, c.A);
+ }
+ }
+}
diff --git a/Source/HtmlRenderer.sln b/Source/HtmlRenderer.sln
index 0d7e1e03b..ed81ba6d7 100644
--- a/Source/HtmlRenderer.sln
+++ b/Source/HtmlRenderer.sln
@@ -27,6 +27,10 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Test", "Test", "{E508FA78-D
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HtmlRenderer.PdfSharp.Test", "Test\HtmlRenderer.PdfSharp.Test\HtmlRenderer.PdfSharp.Test.csproj", "{AF39851E-37B9-409E-A34D-CE091A098C86}"
EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HtmlRenderer.SkiaSharp", "HtmlRenderer.SkiaSharp\HtmlRenderer.SkiaSharp.csproj", "{B9101388-197B-424A-9B4E-CAB7D6DB1250}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HtmlRenderer.SkiaSharp.Test", "Test\HtmlRenderer.SkiaSharp.Test\HtmlRenderer.SkiaSharp.Test.csproj", "{33AFEE24-CE35-4331-A0F3-B24F15124363}"
+EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HtmlRenderer.IntegrationTest", "Test\HtmlRenderer.IntegrationTest\HtmlRenderer.IntegrationTest.csproj", "{A12F4432-337B-4030-B834-5D312A9FB16C}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HtmlRenderer.Test", "Test\HtmlRenderer.Test\HtmlRenderer.Test.csproj", "{7427E12F-1524-4405-AAD1-5AF8ACB3BBBC}"
@@ -147,6 +151,28 @@ Global
{AF39851E-37B9-409E-A34D-CE091A098C86}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{AF39851E-37B9-409E-A34D-CE091A098C86}.Release|x86.ActiveCfg = Release|Any CPU
{AF39851E-37B9-409E-A34D-CE091A098C86}.Release|x86.Build.0 = Release|Any CPU
+ {B9101388-197B-424A-9B4E-CAB7D6DB1250}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {B9101388-197B-424A-9B4E-CAB7D6DB1250}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {B9101388-197B-424A-9B4E-CAB7D6DB1250}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
+ {B9101388-197B-424A-9B4E-CAB7D6DB1250}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
+ {B9101388-197B-424A-9B4E-CAB7D6DB1250}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {B9101388-197B-424A-9B4E-CAB7D6DB1250}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {B9101388-197B-424A-9B4E-CAB7D6DB1250}.Release|Any CPU.Build.0 = Release|Any CPU
+ {B9101388-197B-424A-9B4E-CAB7D6DB1250}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
+ {B9101388-197B-424A-9B4E-CAB7D6DB1250}.Release|Mixed Platforms.Build.0 = Release|Any CPU
+ {B9101388-197B-424A-9B4E-CAB7D6DB1250}.Release|x86.ActiveCfg = Release|Any CPU
+ {33AFEE24-CE35-4331-A0F3-B24F15124363}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {33AFEE24-CE35-4331-A0F3-B24F15124363}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {33AFEE24-CE35-4331-A0F3-B24F15124363}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
+ {33AFEE24-CE35-4331-A0F3-B24F15124363}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
+ {33AFEE24-CE35-4331-A0F3-B24F15124363}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {33AFEE24-CE35-4331-A0F3-B24F15124363}.Debug|x86.Build.0 = Debug|Any CPU
+ {33AFEE24-CE35-4331-A0F3-B24F15124363}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {33AFEE24-CE35-4331-A0F3-B24F15124363}.Release|Any CPU.Build.0 = Release|Any CPU
+ {33AFEE24-CE35-4331-A0F3-B24F15124363}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
+ {33AFEE24-CE35-4331-A0F3-B24F15124363}.Release|Mixed Platforms.Build.0 = Release|Any CPU
+ {33AFEE24-CE35-4331-A0F3-B24F15124363}.Release|x86.ActiveCfg = Release|Any CPU
+ {33AFEE24-CE35-4331-A0F3-B24F15124363}.Release|x86.Build.0 = Release|Any CPU
{A12F4432-337B-4030-B834-5D312A9FB16C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A12F4432-337B-4030-B834-5D312A9FB16C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A12F4432-337B-4030-B834-5D312A9FB16C}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
@@ -193,6 +219,7 @@ Global
{F02E0216-4AE3-474F-9381-FCB93411CDB0} = {E263EA16-2E6A-4269-A319-AA2F97ADA8E1}
{C7C711A6-46AB-4FA2-89ED-D0C79978DE5B} = {E263EA16-2E6A-4269-A319-AA2F97ADA8E1}
{AF39851E-37B9-409E-A34D-CE091A098C86} = {E508FA78-D57E-492F-9BF7-23640001848A}
+ {33AFEE24-CE35-4331-A0F3-B24F15124363} = {E508FA78-D57E-492F-9BF7-23640001848A}
{A12F4432-337B-4030-B834-5D312A9FB16C} = {E508FA78-D57E-492F-9BF7-23640001848A}
{7427E12F-1524-4405-AAD1-5AF8ACB3BBBC} = {E508FA78-D57E-492F-9BF7-23640001848A}
{8E0BFCAC-F676-4EE1-B639-7D8F2F24656D} = {07C2787E-EAC7-C090-1BA3-A61EC2A24D84}
diff --git a/Source/HtmlRenderer/Core/HtmlContainerInt.cs b/Source/HtmlRenderer/Core/HtmlContainerInt.cs
index 717c82cf9..34577e4be 100644
--- a/Source/HtmlRenderer/Core/HtmlContainerInt.cs
+++ b/Source/HtmlRenderer/Core/HtmlContainerInt.cs
@@ -443,6 +443,15 @@ public bool HasFloatedBoxes
get { return _hasFloatedBoxes; }
}
+ ///
+ /// The CSS media type @media rules are evaluated against (CSS 2.1 §7.3), or null for the
+ /// adapter's . Takes effect on the next .
+ ///
+ ///
+ /// For an adapter that renders to screen and to paper, e.g. SkiaSharp's images and PDFs.
+ ///
+ public string MediaType { get; set; }
+
public RSize PageSize { get; set; }
///
@@ -608,7 +617,7 @@ public async Task SetHtml(string htmlSource, CssData baseCssData = null)
DomParser parser = new DomParser(_cssParser);
(_root, _cssData) = await parser.GenerateCssTree(htmlSource, this, _cssData).ConfigureAwait(false);
- _cascadeMedia = MediaQueryContext.FromAdapter(_adapter, _maxSize.Width, _maxSize.Height);
+ _cascadeMedia = MediaQueryContext.FromAdapter(_adapter, MediaType, _maxSize.Width, _maxSize.Height);
if (_root != null)
{
_selectionHandler = new SelectionHandler(_root);
@@ -624,7 +633,7 @@ private void RefreshMediaDependentCascade()
{
if (_root == null || string.IsNullOrEmpty(_htmlSource) || _cssData == null) return;
- var media = MediaQueryContext.FromAdapter(_adapter, _maxSize.Width, _maxSize.Height);
+ var media = MediaQueryContext.FromAdapter(_adapter, MediaType, _maxSize.Width, _maxSize.Height);
if (!_cssData.MediaOutcomeChanged(_cascadeMedia, media)) return;
// PerformLayout is synchronous, so this blocks on the async SetHtml
diff --git a/Source/HtmlRenderer/Core/MediaQueryContext.cs b/Source/HtmlRenderer/Core/MediaQueryContext.cs
index cbdeb1a31..798469c2e 100644
--- a/Source/HtmlRenderer/Core/MediaQueryContext.cs
+++ b/Source/HtmlRenderer/Core/MediaQueryContext.cs
@@ -43,10 +43,22 @@ internal static MediaQueryContext TypeOnly(string mediaType)
/// viewport height in CSS pixels, or 0 when not yet known
internal static MediaQueryContext FromAdapter(RAdapter adapter, double viewportWidth, double viewportHeight)
{
- if (adapter == null) return TypeOnly("all");
+ return FromAdapter(adapter, null, viewportWidth, viewportHeight);
+ }
+
+ ///
+ /// Builds the context from the adapter's characteristics and the container's viewport.
+ ///
+ /// supplies the colour scheme, and the media type unless one is given
+ /// the container's media type, or null for the adapter's
+ /// viewport width in CSS pixels, or 0 when not yet known
+ /// viewport height in CSS pixels, or 0 when not yet known
+ internal static MediaQueryContext FromAdapter(RAdapter adapter, string mediaType, double viewportWidth, double viewportHeight)
+ {
+ if (adapter == null) return TypeOnly(mediaType ?? "all");
return new MediaQueryContext(
- adapter.DefaultMediaType,
+ mediaType ?? adapter.DefaultMediaType,
viewportWidth > 0 ? viewportWidth : (double?)null,
viewportHeight > 0 ? viewportHeight : (double?)null,
96d,
diff --git a/Source/HtmlRenderer/Core/Parse/DomParser.cs b/Source/HtmlRenderer/Core/Parse/DomParser.cs
index 3acc5b106..70b3bd159 100644
--- a/Source/HtmlRenderer/Core/Parse/DomParser.cs
+++ b/Source/HtmlRenderer/Core/Parse/DomParser.cs
@@ -74,7 +74,7 @@ public DomParser(CssParser cssParser)
// available width/height at this point; zero means "not known yet", and geometry
// conditions then match permissively).
var media = MediaQueryContext.FromAdapter(
- htmlContainer.Adapter, htmlContainer.MaxSize.Width, htmlContainer.MaxSize.Height);
+ htmlContainer.Adapter, htmlContainer.MediaType, htmlContainer.MaxSize.Width, htmlContainer.MaxSize.Height);
CascadeApplyStyles(root, cssData, media);
diff --git a/Source/HtmlRenderer/HtmlRenderer.csproj b/Source/HtmlRenderer/HtmlRenderer.csproj
index 52d8b4385..73dc66e7b 100644
--- a/Source/HtmlRenderer/HtmlRenderer.csproj
+++ b/Source/HtmlRenderer/HtmlRenderer.csproj
@@ -41,7 +41,9 @@ For existing implementations see: HtmlRenderer.WinForms, HtmlRenderer.WPF and Ht
+
+
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/ACID 1.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/ACID 1.png
new file mode 100644
index 000000000..c62d3351f
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/ACID 1.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Anchors.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Anchors.png
new file mode 100644
index 000000000..a898187cb
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Anchors.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Background Image.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Background Image.png
new file mode 100644
index 000000000..503e3f355
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Background Image.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/BlockInInline.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/BlockInInline.png
new file mode 100644
index 000000000..4a9a0dd79
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/BlockInInline.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Blockquotes.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Blockquotes.png
new file mode 100644
index 000000000..bcc0a40d6
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Blockquotes.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Borders.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Borders.png
new file mode 100644
index 000000000..f04dff648
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Borders.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Breaking pages 1 - Paragraphs.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Breaking pages 1 - Paragraphs.png
new file mode 100644
index 000000000..db19c4536
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Breaking pages 1 - Paragraphs.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Breaking pages 2 - Tables.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Breaking pages 2 - Tables.png
new file mode 100644
index 000000000..166563cbe
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Breaking pages 2 - Tables.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Bullets.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Bullets.png
new file mode 100644
index 000000000..4b0d0bc0e
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Bullets.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/External Image.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/External Image.png
new file mode 100644
index 000000000..0410450a0
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/External Image.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Fixed position.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Fixed position.png
new file mode 100644
index 000000000..a35c3d6e8
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Fixed position.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Float wrap.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Float wrap.png
new file mode 100644
index 000000000..79921b519
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Float wrap.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Fonts decorations.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Fonts decorations.png
new file mode 100644
index 000000000..cf1b217ee
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Fonts decorations.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Header.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Header.png
new file mode 100644
index 000000000..87b4e7ed9
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Header.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Iframes.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Iframes.png
new file mode 100644
index 000000000..8cc1e134f
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Iframes.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Image in css content.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Image in css content.png
new file mode 100644
index 000000000..ea6dcfc26
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Image in css content.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Images.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Images.png
new file mode 100644
index 000000000..e218d3cf6
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Images.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Inline.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Inline.png
new file mode 100644
index 000000000..225bc5866
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Inline.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Languages.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Languages.png
new file mode 100644
index 000000000..e26b8e8b1
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Languages.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Line break.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Line break.png
new file mode 100644
index 000000000..34061a8b2
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Line break.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/LineHeight.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/LineHeight.png
new file mode 100644
index 000000000..d92e55fb6
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/LineHeight.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Many images.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Many images.png
new file mode 100644
index 000000000..ad14392cc
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Many images.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/MaxWidth.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/MaxWidth.png
new file mode 100644
index 000000000..6e98e4a39
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/MaxWidth.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Media queries and color scheme.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Media queries and color scheme.png
new file mode 100644
index 000000000..8b37282e5
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Media queries and color scheme.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Misc.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Misc.png
new file mode 100644
index 000000000..707723283
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Misc.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Paragraphs.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Paragraphs.png
new file mode 100644
index 000000000..3f5a019b8
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Paragraphs.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/RTL.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/RTL.png
new file mode 100644
index 000000000..76766165d
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/RTL.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Tables.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Tables.png
new file mode 100644
index 000000000..602cd5f1c
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Tables.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Text.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Text.png
new file mode 100644
index 000000000..b84e70460
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/Text.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/White-space.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/White-space.png
new file mode 100644
index 000000000..d4e89c00b
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Linux/White-space.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/ACID 1.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/ACID 1.png
new file mode 100644
index 000000000..68b5f3562
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/ACID 1.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Anchors.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Anchors.png
new file mode 100644
index 000000000..1b481c761
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Anchors.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Background Image.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Background Image.png
new file mode 100644
index 000000000..fb9855904
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Background Image.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/BlockInInline.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/BlockInInline.png
new file mode 100644
index 000000000..e871fa5a8
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/BlockInInline.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Blockquotes.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Blockquotes.png
new file mode 100644
index 000000000..27212742a
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Blockquotes.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Borders.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Borders.png
new file mode 100644
index 000000000..87bd63fe2
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Borders.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Breaking pages 1 - Paragraphs.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Breaking pages 1 - Paragraphs.png
new file mode 100644
index 000000000..daf21220d
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Breaking pages 1 - Paragraphs.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Breaking pages 2 - Tables.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Breaking pages 2 - Tables.png
new file mode 100644
index 000000000..6d2639506
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Breaking pages 2 - Tables.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Bullets.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Bullets.png
new file mode 100644
index 000000000..460678753
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Bullets.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/External Image.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/External Image.png
new file mode 100644
index 000000000..3e746e8a2
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/External Image.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Fixed position.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Fixed position.png
new file mode 100644
index 000000000..b36a34c6b
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Fixed position.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Float wrap.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Float wrap.png
new file mode 100644
index 000000000..986f7a849
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Float wrap.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Fonts decorations.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Fonts decorations.png
new file mode 100644
index 000000000..b12bbef06
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Fonts decorations.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Header.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Header.png
new file mode 100644
index 000000000..a33aa82c3
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Header.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Iframes.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Iframes.png
new file mode 100644
index 000000000..b246c007f
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Iframes.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Image in css content.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Image in css content.png
new file mode 100644
index 000000000..ea6dcfc26
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Image in css content.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Images.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Images.png
new file mode 100644
index 000000000..9ddc98de7
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Images.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Inline.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Inline.png
new file mode 100644
index 000000000..6a0a255a0
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Inline.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Languages.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Languages.png
new file mode 100644
index 000000000..41a72079b
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Languages.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Line break.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Line break.png
new file mode 100644
index 000000000..bde38ec74
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Line break.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/LineHeight.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/LineHeight.png
new file mode 100644
index 000000000..d6c93342b
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/LineHeight.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Many images.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Many images.png
new file mode 100644
index 000000000..367980fe3
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Many images.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/MaxWidth.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/MaxWidth.png
new file mode 100644
index 000000000..b125b88af
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/MaxWidth.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Media queries and color scheme.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Media queries and color scheme.png
new file mode 100644
index 000000000..e0666e227
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Media queries and color scheme.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Misc.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Misc.png
new file mode 100644
index 000000000..0df3cca83
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Misc.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Paragraphs.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Paragraphs.png
new file mode 100644
index 000000000..3d23f040b
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Paragraphs.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/RTL.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/RTL.png
new file mode 100644
index 000000000..6059b2d8c
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/RTL.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Tables.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Tables.png
new file mode 100644
index 000000000..b727a4dbd
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Tables.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Text.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Text.png
new file mode 100644
index 000000000..eb9e582b5
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/Text.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/White-space.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/White-space.png
new file mode 100644
index 000000000..479ee52f2
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/Windows/White-space.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/ACID 1.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/ACID 1.png
new file mode 100644
index 000000000..ff840d587
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/ACID 1.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Anchors.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Anchors.png
new file mode 100644
index 000000000..84bd430ef
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Anchors.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Background Image.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Background Image.png
new file mode 100644
index 000000000..c39d66811
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Background Image.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/BlockInInline.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/BlockInInline.png
new file mode 100644
index 000000000..eb755a3cf
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/BlockInInline.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Blockquotes.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Blockquotes.png
new file mode 100644
index 000000000..945401e66
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Blockquotes.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Borders.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Borders.png
new file mode 100644
index 000000000..0648eade4
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Borders.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Breaking pages 1 - Paragraphs.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Breaking pages 1 - Paragraphs.png
new file mode 100644
index 000000000..1a3e29d0e
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Breaking pages 1 - Paragraphs.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Breaking pages 2 - Tables.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Breaking pages 2 - Tables.png
new file mode 100644
index 000000000..384860839
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Breaking pages 2 - Tables.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Bullets.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Bullets.png
new file mode 100644
index 000000000..e65747d92
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Bullets.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/External Image.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/External Image.png
new file mode 100644
index 000000000..bc5e750e5
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/External Image.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Fixed position.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Fixed position.png
new file mode 100644
index 000000000..5fd2d45b0
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Fixed position.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Float wrap.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Float wrap.png
new file mode 100644
index 000000000..339dc330c
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Float wrap.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Fonts decorations.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Fonts decorations.png
new file mode 100644
index 000000000..b0f1e116a
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Fonts decorations.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Header.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Header.png
new file mode 100644
index 000000000..501026473
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Header.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Iframes.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Iframes.png
new file mode 100644
index 000000000..ad01096b7
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Iframes.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Image in css content.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Image in css content.png
new file mode 100644
index 000000000..ea6dcfc26
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Image in css content.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Images.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Images.png
new file mode 100644
index 000000000..8a924b826
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Images.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Inline.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Inline.png
new file mode 100644
index 000000000..2494903da
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Inline.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Languages.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Languages.png
new file mode 100644
index 000000000..f137653be
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Languages.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Line break.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Line break.png
new file mode 100644
index 000000000..bc2cd8ff3
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Line break.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/LineHeight.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/LineHeight.png
new file mode 100644
index 000000000..d35b2f595
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/LineHeight.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Many images.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Many images.png
new file mode 100644
index 000000000..c32e02d85
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Many images.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/MaxWidth.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/MaxWidth.png
new file mode 100644
index 000000000..c7616e226
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/MaxWidth.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Media queries and color scheme.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Media queries and color scheme.png
new file mode 100644
index 000000000..1f4504e29
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Media queries and color scheme.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Misc.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Misc.png
new file mode 100644
index 000000000..1674a26fd
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Misc.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Paragraphs.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Paragraphs.png
new file mode 100644
index 000000000..f4572a603
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Paragraphs.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/RTL.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/RTL.png
new file mode 100644
index 000000000..83fd6b5de
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/RTL.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Tables.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Tables.png
new file mode 100644
index 000000000..f3ff2532c
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Tables.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Text.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Text.png
new file mode 100644
index 000000000..a1e077027
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/Text.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/White-space.png b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/White-space.png
new file mode 100644
index 000000000..d89db0bbd
Binary files /dev/null and b/Source/Test/HtmlRenderer.SkiaSharp.Test/Baselines/macOS/White-space.png differ
diff --git a/Source/Test/HtmlRenderer.SkiaSharp.Test/HtmlRenderTests.cs b/Source/Test/HtmlRenderer.SkiaSharp.Test/HtmlRenderTests.cs
new file mode 100644
index 000000000..a8e904f88
--- /dev/null
+++ b/Source/Test/HtmlRenderer.SkiaSharp.Test/HtmlRenderTests.cs
@@ -0,0 +1,248 @@
+using SkiaSharp;
+using TheArtOfDev.HtmlRenderer.Core.Entities;
+using TheArtOfDev.HtmlRenderer.Demo.Common;
+using TheArtOfDev.HtmlRenderer.SkiaSharp;
+using TheArtOfDev.HtmlRenderer.SkiaSharp.Adapters;
+
+namespace HtmlRenderer.SkiaSharp.Test;
+
+// Parallel full layout passes race on the adapter singletons.
+[TestClass]
+[DoNotParallelize]
+public sealed class HtmlRenderTests
+{
+ [TestMethod]
+ public async Task RenderToImage_DrawsTheText()
+ {
+ using var image = await HtmlRender.RenderToImageAsync("