diff --git a/src/EPPlus.DrawingRenderer.Tests/EPPlus.DrawingRenderer.Tests.csproj b/src/EPPlus.DrawingRenderer.Tests/EPPlus.DrawingRenderer.Tests.csproj
index 95caaa366d..c4e5e83ea4 100644
--- a/src/EPPlus.DrawingRenderer.Tests/EPPlus.DrawingRenderer.Tests.csproj
+++ b/src/EPPlus.DrawingRenderer.Tests/EPPlus.DrawingRenderer.Tests.csproj
@@ -22,6 +22,13 @@
+
+
+
+ PreserveNewest
+
+
+
diff --git a/src/EPPlus.DrawingRenderer.Tests/FontTestBase.cs b/src/EPPlus.DrawingRenderer.Tests/FontTestBase.cs
new file mode 100644
index 0000000000..9983e9e724
--- /dev/null
+++ b/src/EPPlus.DrawingRenderer.Tests/FontTestBase.cs
@@ -0,0 +1,115 @@
+using EPPlus.Fonts.OpenType;
+using OfficeOpenXml.Interfaces.Fonts;
+
+namespace EPPlus.DrawingRenderer.Tests
+{
+ ///
+ /// Base class for renderer tests that lay out or measure text.
+ ///
+ /// Mirrors FontTestBase in EPPlus.Fonts.OpenType.Tests: tests use one of the exposed engines,
+ /// TestFolderEngine (test fonts only) or SystemFontsEngine (test fonts and system fonts), and
+ /// the render context built on it. The test fonts are linked from
+ /// EPPlus.Fonts.OpenType.Tests/Fonts and copied to the TestFonts folder in the output
+ /// directory (see the csproj).
+ ///
+ /// The engines and contexts are shared by all tests. Do not dispose them.
+ ///
+ public abstract class FontTestBase : TestBase
+ {
+ ///
+ /// Folder holding the test fonts in the output directory.
+ ///
+ protected static string FontFolder
+ {
+ get { return Path.Combine(AppContext.BaseDirectory, "TestFonts"); }
+ }
+
+ // -----------------------------------------------------------------------------------------
+ // Engines
+ // -----------------------------------------------------------------------------------------
+
+ private static readonly Lazy _testFolderEngine =
+ new Lazy(() => new OpenTypeFontEngine(cfg =>
+ {
+ cfg.FontDirectories.Add(GetExistingFontFolder());
+ cfg.SearchSystemDirectories = false;
+ }));
+
+ private static readonly Lazy _systemFontsEngine =
+ new Lazy(() => new OpenTypeFontEngine(cfg =>
+ {
+ cfg.FontDirectories.Add(GetExistingFontFolder());
+ cfg.SearchSystemDirectories = true;
+ }));
+
+ private static readonly Lazy _testFolderContext =
+ new Lazy(() => new RenderContext(() => TestFolderEngine));
+
+ private static readonly Lazy _systemFontsContext =
+ new Lazy(() => new RenderContext(() => SystemFontsEngine));
+
+ ///
+ /// Engine that searches only the test font folder. Use this for tests that can rely on
+ /// the fonts bundled with the font test project (BIZUDGothic, CrimsonText, EBGaramond,
+ /// Mulish, NotoEmoji, NotoSansMath, Oi, OpenSans, PinyonScript, Roboto, SourceSans3,
+ /// UnicaOne, Archivo Narrow).
+ ///
+ protected static OpenTypeFontEngine TestFolderEngine
+ {
+ get { return _testFolderEngine.Value; }
+ }
+
+ ///
+ /// Engine that searches both the test font folder and the system font directories. Use
+ /// this only in tests that need fonts not bundled with the tests (e.g. Aptos Narrow,
+ /// Calibri), together with so the test is Inconclusive on
+ /// machines that lack the font.
+ ///
+ protected static OpenTypeFontEngine SystemFontsEngine
+ {
+ get { return _systemFontsEngine.Value; }
+ }
+
+ ///
+ /// Render context over .
+ ///
+ protected static RenderContext TestFolderContext
+ {
+ get { return _testFolderContext.Value; }
+ }
+
+ ///
+ /// Render context over .
+ ///
+ protected static RenderContext SystemFontsContext
+ {
+ get { return _systemFontsContext.Value; }
+ }
+
+ ///
+ /// Marks the test Inconclusive unless the font is available in the engine with the
+ /// requested subfamily.
+ ///
+ protected static void RequireFont(
+ OpenTypeFontEngine engine,
+ string fontName,
+ FontSubFamily subFamily = FontSubFamily.Regular)
+ {
+ var avail = engine.GetFontAvailability(fontName, subFamily);
+ if (avail != FontAvailability.Exact)
+ {
+ Assert.Inconclusive(
+ "Test requires " + fontName + " " + subFamily +
+ " which is not available (availability: " + avail + ").");
+ }
+ }
+
+ private static string GetExistingFontFolder()
+ {
+ var folder = FontFolder;
+ if (!Directory.Exists(folder))
+ throw new DirectoryNotFoundException("Test font folder not found: " + folder);
+ return folder;
+ }
+ }
+}
diff --git a/src/EPPlus.DrawingRenderer.Tests/Fonts/EmbedFontsMeasurementTests.cs b/src/EPPlus.DrawingRenderer.Tests/Fonts/EmbedFontsMeasurementTests.cs
new file mode 100644
index 0000000000..11d5ef5164
--- /dev/null
+++ b/src/EPPlus.DrawingRenderer.Tests/Fonts/EmbedFontsMeasurementTests.cs
@@ -0,0 +1,216 @@
+using System.Text.RegularExpressions;
+using EPPlus.DrawingRenderer.Svg;
+using EPPlus.Fonts.OpenType;
+using EPPlusImageRenderer;
+using OfficeOpenXml;
+using OfficeOpenXml.Drawing;
+using OfficeOpenXml.Drawing.Chart;
+using OfficeOpenXml.Interfaces.Fonts;
+
+namespace EPPlus.DrawingRenderer.Tests.Fonts
+{
+ ///
+ /// Step 4: decides whether text is measured with the
+ /// requested font or with its web substitute.
+ /// carries the decision down to measurement.
+ ///
+ [TestClass]
+ public class EmbedFontsMeasurementTests : FontTestBase
+ {
+ [TestInitialize]
+ public void Initialize()
+ {
+ ExcelPackage.License.SetNonCommercialOrganization("EPPlus Project");
+ }
+
+ private static ExcelPackage CreatePackage(Action? configure = null)
+ {
+ var p = new ExcelPackage();
+ p.Workbook.UseFontEngine(new OpenTypeFontEngine(cfg =>
+ {
+ cfg.FontDirectories.Add(FontFolder);
+ cfg.SearchSystemDirectories = false;
+ configure?.Invoke(cfg);
+ }));
+ return p;
+ }
+
+ private static string FirstTspanFamily(string svg)
+ {
+ var m = Regex.Match(svg, "]*?style=\"[^\"]*?font-family:((?:&[#\\w]+;|[^;\"])*)");
+ Assert.IsTrue(m.Success, "No text run with a font-family was rendered.");
+ return System.Net.WebUtility.HtmlDecode(m.Groups[1].Value).Split(',')[0].Trim();
+ }
+
+ private static string ShapeSvg(ExcelPackage p, string fontName, Action options)
+ {
+ var ws = p.Workbook.Worksheets.Add("Sheet1");
+ var shape = ws.Drawings.AddShape("Shape1", eShapeStyle.Rect);
+ shape.SetSize(300, 200);
+ shape.TextBody.Paragraphs.Add("Some text").TextRuns[0].SetFromFont(fontName, 11);
+ return shape.ToSvg(options);
+ }
+
+ // -----------------------------------------------------------------------------------------
+ // RenderContext
+ // -----------------------------------------------------------------------------------------
+
+ [TestMethod]
+ [DataRow(FontRenderTarget.Web, true, "Calibri")]
+ [DataRow(FontRenderTarget.Web, false, "Aptos Narrow")]
+ [DataRow(FontRenderTarget.Document, true, "Aptos Narrow")]
+ [DataRow(FontRenderTarget.Document, false, "Aptos Narrow")]
+ public void RenderContext_SubstitutesOnlyForWebWithFlag(FontRenderTarget target, bool substitute, string expected)
+ {
+ using (var engine = new OpenTypeFontEngine(cfg => cfg.SearchSystemDirectories = false))
+ {
+ var rc = new RenderContext(() => engine).ForTarget(target, substitute);
+
+ Assert.AreEqual(target, rc.Target);
+ Assert.AreEqual(substitute, rc.SubstituteWebFonts);
+ Assert.AreEqual(expected, rc.GetFamilyForTarget("Aptos Narrow"));
+ }
+ }
+
+ [TestMethod]
+ public void RenderContext_ForTargetWithoutFlag_SubstitutesForWebOnly()
+ {
+ using (var engine = new OpenTypeFontEngine(cfg => cfg.SearchSystemDirectories = false))
+ {
+ var root = new RenderContext(() => engine);
+
+ Assert.IsTrue(root.ForTarget(FontRenderTarget.Web).SubstituteWebFonts);
+ Assert.IsFalse(root.ForTarget(FontRenderTarget.Document).SubstituteWebFonts);
+ Assert.AreEqual("Calibri", root.ForTarget(FontRenderTarget.Web).GetFamilyForTarget("Aptos Narrow"));
+ }
+ }
+
+ [TestMethod]
+ public void RenderContext_Views_ShareTheRootEngineAndReturnRootWhenEqual()
+ {
+ using (var engine = new OpenTypeFontEngine(cfg => cfg.SearchSystemDirectories = false))
+ {
+ var root = new RenderContext(() => engine);
+ var web = root.ForTarget(FontRenderTarget.Web, true);
+ var webNoSubstitution = web.ForTarget(FontRenderTarget.Web, false);
+
+ Assert.AreSame(root, web.ForTarget(FontRenderTarget.Document, false));
+ Assert.AreSame(web, web.ForTarget(FontRenderTarget.Web, true));
+ Assert.AreSame(root.FontEngine, webNoSubstitution.FontEngine);
+ }
+ }
+
+ // -----------------------------------------------------------------------------------------
+ // SvgRenderOptions.EmbedFonts
+ // -----------------------------------------------------------------------------------------
+
+ [TestMethod]
+ public void SvgRenderOptions_EmbedFonts_DefaultsToTrue()
+ {
+ Assert.IsTrue(new SvgRenderOptions().EmbedFonts);
+ }
+
+ [TestMethod]
+ public void Shape_EmbedFonts_MeasuresAndWritesRequestedFont()
+ {
+ using (var p = CreatePackage())
+ {
+ var svg = ShapeSvg(p, "Aptos Narrow", o => o.EmbedFonts = true);
+ Assert.AreEqual("'Aptos Narrow'", FirstTspanFamily(svg));
+ }
+ }
+
+ [TestMethod]
+ public void Shape_NoEmbedFonts_WebTarget_UsesSubstitute()
+ {
+ using (var p = CreatePackage())
+ {
+ var svg = ShapeSvg(p, "Aptos Narrow", o => o.EmbedFonts = false);
+ Assert.AreEqual("'Calibri'", FirstTspanFamily(svg));
+ }
+ }
+
+ [TestMethod]
+ public void Shape_NoEmbedFonts_DocumentTarget_KeepsRequestedFont()
+ {
+ using (var p = CreatePackage())
+ {
+ var svg = ShapeSvg(p, "Aptos Narrow", o =>
+ {
+ o.EmbedFonts = false;
+ o.FontTarget = FontRenderTarget.Document;
+ });
+ Assert.AreEqual("'Aptos Narrow'", FirstTspanFamily(svg));
+ }
+ }
+
+ [TestMethod]
+ public void Chart_EmbedFonts_MeasuresAndWritesRequestedFont()
+ {
+ using (var p = CreatePackage())
+ {
+ var chart = AddColumnChart(p, "Aptos Narrow");
+ Assert.AreEqual("'Aptos Narrow'", FirstTspanFamily(chart.ToSvg(o => o.EmbedFonts = true)));
+ Assert.AreEqual("'Calibri'", FirstTspanFamily(chart.ToSvg(o => o.EmbedFonts = false)));
+ }
+ }
+
+ // -----------------------------------------------------------------------------------------
+ // Axis width is measured with the same font as the axis labels
+ // -----------------------------------------------------------------------------------------
+
+ private static ExcelChart AddColumnChart(ExcelPackage p, string axisFont)
+ {
+ var ws = p.Workbook.Worksheets.Add("Sheet" + (p.Workbook.Worksheets.Count + 1));
+ ws.Cells["A1:A4"].FillNumber(1, 1);
+ ws.Cells["B1"].Value = 1000000;
+ ws.Cells["B2"].Value = 2500000;
+ ws.Cells["B3"].Value = 4000000;
+ ws.Cells["B4"].Value = 5500000;
+ var chart = ws.Drawings.AddChart("Chart1", eChartType.ColumnClustered);
+ chart.Series.Add(ws.Cells["B1:B4"], ws.Cells["A1:A4"]);
+ chart.SetSize(500, 300);
+ chart.XAxis.Font.LatinFont = axisFont;
+ chart.YAxis.Font.LatinFont = axisFont;
+ return chart;
+ }
+
+ private static double VerticalAxisWidth(string substitute)
+ {
+ using (var p = CreatePackage(cfg =>
+ {
+ cfg.WebFontSubstitutions["Aptos Narrow"] = substitute;
+ // Measure from serialized metrics, so the result does not depend on installed fonts.
+ cfg.MetricsFallback = MetricsFallbackMode.Always;
+ }))
+ {
+ var chart = AddColumnChart(p, "Aptos Narrow");
+ var renderer = new ChartRenderer(chart, new SvgRenderOptions { EmbedFonts = false });
+ Assert.IsNotNull(renderer.VerticalAxis, "Test setup: the chart has no vertical axis.");
+ return renderer.VerticalAxis.Rectangle.Width;
+ }
+ }
+
+ [TestMethod]
+ public void Chart_VerticalAxisWidth_FollowsTheSubstitutedFont()
+ {
+ // Verdana is much wider than Calibri. Before the fix the axis width was measured with the
+ // unsubstituted font, so it was the same in both cases.
+ using (var engine = new OpenTypeFontEngine(cfg =>
+ {
+ cfg.SearchSystemDirectories = false;
+ cfg.MetricsFallback = MetricsFallbackMode.Always;
+ }))
+ {
+ if (engine.GetMeasurementShaper("Verdana").HasGlyphIds || engine.GetMeasurementShaper("Calibri").HasGlyphIds)
+ Assert.Inconclusive("Test setup: Verdana and Calibri are expected to have serialized metrics.");
+ }
+
+ var verdana = VerticalAxisWidth("Verdana");
+ var calibri = VerticalAxisWidth("Calibri");
+
+ Assert.IsTrue(verdana > calibri,
+ $"Expected the axis to be wider with Verdana than with Calibri (Verdana {verdana}, Calibri {calibri}).");
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/EPPlus.DrawingRenderer.Tests/Fonts/SvgBrowserCheckTests.cs b/src/EPPlus.DrawingRenderer.Tests/Fonts/SvgBrowserCheckTests.cs
new file mode 100644
index 0000000000..a834fe8398
--- /dev/null
+++ b/src/EPPlus.DrawingRenderer.Tests/Fonts/SvgBrowserCheckTests.cs
@@ -0,0 +1,205 @@
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using OfficeOpenXml.Interfaces.Fonts;
+using OfficeOpenXml.Style;
+using System;
+using System.Collections.Generic;
+using System.Drawing;
+using System.IO;
+using System.Net;
+using System.Text;
+
+namespace EPPlus.DrawingRenderer.Tests.Fonts
+{
+ ///
+ /// Step 7: generates a page for checking the svg export in browsers. Not a regression test.
+ ///
+ [TestClass]
+ public class SvgBrowserCheckTests : SvgExportTestBase
+ {
+ // The folder under the test output folder (TestBase), written the way TestBase builds paths.
+ private const string OutputFolder = "svg\\SvgBrowserCheck\\";
+
+ ///
+ /// Writes svg files and a page for checking the svg export in browsers to svg\SvgBrowserCheck
+ /// under the test output folder (TestBase). Open index.html in Chrome, Firefox, Edge and Safari
+ /// and go through the checks on the page. A screenshot from Excel named <case>.excel.png
+ /// placed in the folder is shown next to its case the next time the page is written.
+ /// Where files cannot be written, as in some build environments, the test is inconclusive.
+ ///
+ [TestMethod]
+ [TestCategory("Manual")]
+ public void WriteBrowserCheckPage()
+ {
+ RequireFont(TestFolderEngine, "Roboto");
+
+ var html = new StringBuilder();
+ AppendPageStart(html);
+
+ foreach (var c in GetCases())
+ {
+ var svg = c.Render();
+ // TestBase writes to the configured output folder and turns a failed write into Inconclusive.
+ SaveTextFileToWorkbook(OutputFolder + c.File + ".svg", svg);
+ AppendCaseRow(html, c, svg);
+ }
+
+ html.AppendLine("