From 016a95a11154d40c20cd08a7d582b240f623c530 Mon Sep 17 00:00:00 2001 From: swmal <{ID}+username}@users.noreply.github.com> Date: Sat, 21 Nov 2026 09:17:36 +0100 Subject: [PATCH 1/3] Embed subset fonts in SVG export: @font-face, font stacks, textLength, per-font glyph fallback spans --- .../EPPlus.DrawingRenderer.Tests.csproj | 7 + .../FontTestBase.cs | 115 +++ .../Fonts/EmbedFontsMeasurementTests.cs | 216 ++++++ .../Fonts/SvgFontEmbeddingTests.cs | 422 +++++++++++ .../Fonts/SvgFontFamilyStackTests.cs | 224 ++++++ .../Fonts/WebFontSubstitutionSvgTests.cs | 22 +- .../Text/TextRunWidthInvariantTests.cs | 292 ++++++++ .../Text/WrapExcelComparisonTests.cs | 205 ++++++ src/EPPlus.DrawingRenderer/RenderContext.cs | 76 +- .../Textbox/ParagraphRenderItem.cs | 11 +- .../Svg/Core/SvgBasicShapesRenderer.cs | 11 +- .../Svg/Core/SvgShapeRenderer.cs | 70 +- .../Svg/ItemRenderers/SvgGroupRenderer.cs | 3 +- .../Svg/ItemRenderers/SvgParagraphRenderer.cs | 7 +- .../Svg/ItemRenderers/SvgTextRunRenderer.cs | 51 +- .../Svg/Options/SvgRenderOptions.cs | 19 +- src/EPPlus.DrawingRenderer/Svg/SvgFontPlan.cs | 339 +++++++++ .../EPPlus.Fonts.OpenType.Tests.csproj | 6 + .../FontResolver/FallbackChainTests.cs | 119 ++++ .../FontResolver/GenericFontFamilyTests.cs | 182 +++++ .../Fonts/Mulish-Regular-GsubExtension.ttf | Bin 0 -> 107032 bytes .../Helpers/FontTestHelper.cs | 91 +++ .../CoreTableSerializationTests.cs | 4 +- .../Subsetting/BasicSubsettingTests.cs | 6 +- .../Subsetting/FontEmbeddingPolicyTests.cs | 2 + .../Subsetting/LayoutLookupIndexTests.cs | 96 +++ .../Subsetting/OtsSubsetMatrixTests.cs | 75 ++ .../PassThroughTableSubsetProcessorTests.cs | 199 ++++++ .../Subsetting/WebEmbeddingPolicyTests.cs | 369 ++++++++++ .../WebFontPlanCodePointStackTests.cs | 157 +++++ .../Subsetting/WebFontSubsetPlannerTests.cs | 382 ++++++++++ .../Tables/Cmap/CmapTableTests.cs | 47 ++ .../Tables/Name/LicenseDetectionTests.cs | 163 +++++ .../Tables/Os2/Os2TableTests.cs | 65 ++ src/EPPlus.Fonts.OpenType/FontStore.cs | 31 +- .../GenericFontFamilyClassifier.cs | 69 ++ .../DataHolders/TextLineCollection.cs | 2 +- .../Integration/TextLayoutEngine.RichText.cs | 11 +- .../Integration/WrapStateRichText.cs | 3 +- src/EPPlus.Fonts.OpenType/OpenTypeFont.cs | 8 +- .../OpenTypeFontEngine.cs | 124 +++- .../OpenTypeFontSerializer.cs | 2 +- .../PassThroughTableSubsetProcessor.cs | 55 ++ .../Subsetting/SubsetFontBuilder.cs | 3 +- .../Subsetting/SubsetPostProcessor.cs | 2 +- .../Subsetting/WebFontFace.cs | 73 ++ .../Subsetting/WebFontPlan.cs | 104 +++ .../Subsetting/WebFontSubsetPlanner.cs | 653 ++++++++++++++++++ .../Tables/Cmap/CmapTable.cs | 79 +-- .../Layout/Lookups/ILookupRecordContainer.cs | 19 + .../Common/Layout/Lookups/LookupListTable.cs | 32 +- .../Tables/Gpos/GposTableLoader.cs | 4 + .../Lookups/ChainingContextualSubstFormat3.cs | 67 +- .../Data/Lookups/ExtensionSubstSubTable.cs | 27 +- .../Gsub/Handlers/ExtensionSubstHandler.cs | 124 ++-- .../IO/ExtensionSubstSubTableDeserializer.cs | 42 +- .../Tables/Name/NameTable.cs | 59 +- .../Tables/Name/OpenFontLicenses.cs | 72 ++ .../Tables/Os2/Os2Table.cs | 51 +- .../Tables/Os2/Os2TableLoader.cs | 47 +- .../Tables/RawFontTable.cs | 55 ++ .../Tables/TableNames.cs | 4 + .../Fonts/FontEmbeddingInfo.cs | 78 ++- .../Fonts/FontEmbeddingPermission.cs | 18 + .../Fonts/GenericFontFamily.cs | 36 + src/EPPlus/Drawing/Chart/ExcelChart.cs | 2 +- src/EPPlus/Drawing/ExcelDrawing.cs | 6 +- src/EPPlus/Drawing/ExcelPicture.cs | 2 +- src/EPPlus/Drawing/ExcelShape.cs | 8 +- .../Renderer/Chart/ChartAxisRenderer.cs | 6 +- src/EPPlus/Drawing/Renderer/ChartRenderer.cs | 4 +- .../Drawing/Renderer/DrawingRenderer.cs | 14 +- src/EPPlus/Drawing/Renderer/ShapeRenderer.cs | 13 +- src/EPPlusTest/ConfigureFontsTests.cs | 7 +- 74 files changed, 5781 insertions(+), 288 deletions(-) create mode 100644 src/EPPlus.DrawingRenderer.Tests/FontTestBase.cs create mode 100644 src/EPPlus.DrawingRenderer.Tests/Fonts/EmbedFontsMeasurementTests.cs create mode 100644 src/EPPlus.DrawingRenderer.Tests/Fonts/SvgFontEmbeddingTests.cs create mode 100644 src/EPPlus.DrawingRenderer.Tests/Fonts/SvgFontFamilyStackTests.cs create mode 100644 src/EPPlus.DrawingRenderer.Tests/Text/TextRunWidthInvariantTests.cs create mode 100644 src/EPPlus.DrawingRenderer.Tests/Text/WrapExcelComparisonTests.cs create mode 100644 src/EPPlus.DrawingRenderer/Svg/SvgFontPlan.cs create mode 100644 src/EPPlus.Fonts.OpenType.Tests/FontResolver/FallbackChainTests.cs create mode 100644 src/EPPlus.Fonts.OpenType.Tests/FontResolver/GenericFontFamilyTests.cs create mode 100644 src/EPPlus.Fonts.OpenType.Tests/Fonts/Mulish-Regular-GsubExtension.ttf create mode 100644 src/EPPlus.Fonts.OpenType.Tests/Subsetting/LayoutLookupIndexTests.cs create mode 100644 src/EPPlus.Fonts.OpenType.Tests/Subsetting/OtsSubsetMatrixTests.cs create mode 100644 src/EPPlus.Fonts.OpenType.Tests/Subsetting/PassThroughTableSubsetProcessorTests.cs create mode 100644 src/EPPlus.Fonts.OpenType.Tests/Subsetting/WebEmbeddingPolicyTests.cs create mode 100644 src/EPPlus.Fonts.OpenType.Tests/Subsetting/WebFontPlanCodePointStackTests.cs create mode 100644 src/EPPlus.Fonts.OpenType.Tests/Subsetting/WebFontSubsetPlannerTests.cs create mode 100644 src/EPPlus.Fonts.OpenType.Tests/Tables/Cmap/CmapTableTests.cs create mode 100644 src/EPPlus.Fonts.OpenType.Tests/Tables/Name/LicenseDetectionTests.cs create mode 100644 src/EPPlus.Fonts.OpenType.Tests/Tables/Os2/Os2TableTests.cs create mode 100644 src/EPPlus.Fonts.OpenType/GenericFontFamilyClassifier.cs create mode 100644 src/EPPlus.Fonts.OpenType/Subsetting/PassThroughTableSubsetProcessor.cs create mode 100644 src/EPPlus.Fonts.OpenType/Subsetting/WebFontFace.cs create mode 100644 src/EPPlus.Fonts.OpenType/Subsetting/WebFontPlan.cs create mode 100644 src/EPPlus.Fonts.OpenType/Subsetting/WebFontSubsetPlanner.cs create mode 100644 src/EPPlus.Fonts.OpenType/Tables/Common/Layout/Lookups/ILookupRecordContainer.cs create mode 100644 src/EPPlus.Fonts.OpenType/Tables/Name/OpenFontLicenses.cs create mode 100644 src/EPPlus.Fonts.OpenType/Tables/RawFontTable.cs create mode 100644 src/EPPlus.Interfaces/Fonts/FontEmbeddingPermission.cs create mode 100644 src/EPPlus.Interfaces/Fonts/GenericFontFamily.cs 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..237d6435e0 --- /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 + { + /// + /// 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..c488f001c1 --- /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, "]*?font-family=\"([^\"]*)\""); + 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/SvgFontEmbeddingTests.cs b/src/EPPlus.DrawingRenderer.Tests/Fonts/SvgFontEmbeddingTests.cs new file mode 100644 index 0000000000..e7db67788d --- /dev/null +++ b/src/EPPlus.DrawingRenderer.Tests/Fonts/SvgFontEmbeddingTests.cs @@ -0,0 +1,422 @@ +using System.Globalization; +using System.Text.RegularExpressions; +using EPPlus.DrawingRenderer.Svg; +using EPPlus.Fonts.OpenType; +using OfficeOpenXml; +using OfficeOpenXml.Drawing; +using OfficeOpenXml.Drawing.Chart; +using OfficeOpenXml.Interfaces.Fonts; + +namespace EPPlus.DrawingRenderer.Tests.Fonts +{ + /// + /// Step 5: fonts embedded in the svg as subsets (@font-face), font-family stacks that start with + /// the subsets, textLength on every text run, xml:space on text elements, the root text style, + /// and text runs split where measurement used a glyph fallback that is written by name. + /// The font engine only sees the test fonts, so the output does not depend on installed fonts. + /// + [TestClass] + public class SvgFontEmbeddingTests : FontTestBase + { + private const string JapaneseText = "Sales あいう"; + + [TestInitialize] + public void Initialize() + { + ExcelPackage.License.SetNonCommercialOrganization("EPPlus Project"); + } + + private OpenTypeFontEngine? _engine; + + [TestCleanup] + public void Cleanup() + { + _engine?.Dispose(); + _engine = null; + } + + private ExcelPackage CreatePackage(Action? configure = null) + { + _engine = new OpenTypeFontEngine(cfg => + { + cfg.FontDirectories.Add(FontFolder); + cfg.SearchSystemDirectories = false; + configure?.Invoke(cfg); + }); + var p = new ExcelPackage(); + p.Workbook.UseFontEngine(_engine); + return p; + } + + private static ExcelShape AddShape(ExcelPackage p, string text, string fontName, bool bold = false) + { + var ws = p.Workbook.Worksheets.Add("Sheet" + (p.Workbook.Worksheets.Count + 1)); + var shape = ws.Drawings.AddShape("Shape1", eShapeStyle.Rect); + shape.SetSize(300, 200); + shape.TextBody.Paragraphs.Add(text).TextRuns[0].SetFromFont(fontName, 11, bold); + return shape; + } + + /// Hiragana is drawn with BIZ UDGothic, which an OnFontEmbedding callback may forbid. + private static void JapaneseFallback(IEpplusFontConfiguration cfg, bool embedFallback) + { + RequireFont(TestFolderEngine, "BIZ UDGothic"); + cfg.SetScriptFallback(UnicodeScript.Hiragana, "BIZ UDGothic", "Yu Gothic", "Meiryo"); + if (!embedFallback) + { + cfg.OnFontEmbedding(info => info.FontName.StartsWith("BIZ UDGothic", StringComparison.OrdinalIgnoreCase) + ? FontEmbeddingDecision.Skip + : FontEmbeddingDecision.Default); + } + } + + private static List FontFaceFamilies(string svg) + { + return Regex.Matches(svg, "@font-face\\{font-family:'([^']*)'") + .Cast().Select(m => m.Groups[1].Value).ToList(); + } + + private static string[] Families(string fontFamilyAttribute) + { + return System.Net.WebUtility.HtmlDecode(fontFamilyAttribute) + .Split(',').Select(f => f.Trim().Trim('\'')).ToArray(); + } + + /// The innermost tspans, the ones that hold text. + private static MatchCollection TextTspans(string svg) + { + return Regex.Matches(svg, "]*)>([^<]+)"); + } + + private static string? Attribute(string attributes, string name) + { + var m = Regex.Match(attributes, "\\s" + Regex.Escape(name) + "=\"([^\"]*)\""); + return m.Success ? m.Groups[1].Value : null; + } + + /// The width in pixels, measured with the engine of the package the test created. + private double MeasurePixels(string text, string family, FontSubFamily subFamily, float size) + { + var points = _engine!.GetMeasurementShaper(family, subFamily).ShapeLight(text).GetWidthInPoints(size); + return points / 72d * 96d; + } + + // ----------------------------------------------------------------------------------------- + // @font-face + // ----------------------------------------------------------------------------------------- + + [TestMethod] + public void EmbedFonts_WritesFontFaceWithDataUriInDefs() + { + RequireFont(TestFolderEngine, "Roboto"); + using (var p = CreatePackage()) + { + var svg = AddShape(p, "Hello", "Roboto").ToSvg(); + + var m = Regex.Match(svg, + ""); + + foreach (var shape in cases) + { + var svg = shape.ToSvg(o => o.FontTarget = FontRenderTarget.Document); + var svgFile = GetOutputFile(OutputFolder, shape.Name + ".svg"); + File.WriteAllText(svgFile.FullName, svg); + + html.AppendLine($"{WebUtility.HtmlEncode(shape.Name)}"); + + dump.AppendLine(shape.Name); + foreach (var tspan in GetTspans(engine, svg)) + { + dump.AppendLine(" " + tspan); + } + dump.AppendLine(); + } + + html.AppendLine("