Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,13 @@
<Using Include="Microsoft.VisualStudio.TestTools.UnitTesting" />
</ItemGroup>

<ItemGroup>
<!-- Test fonts, linked from the font test project so text layout tests do not depend on installed fonts. -->
<None Include="..\EPPlus.Fonts.OpenType.Tests\Fonts\**\*.ttf;..\EPPlus.Fonts.OpenType.Tests\Fonts\**\*.otf" Link="TestFonts\%(RecursiveDir)%(Filename)%(Extension)">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>


<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" />
Expand Down
115 changes: 115 additions & 0 deletions src/EPPlus.DrawingRenderer.Tests/FontTestBase.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
using EPPlus.Fonts.OpenType;
using OfficeOpenXml.Interfaces.Fonts;

namespace EPPlus.DrawingRenderer.Tests
{
/// <summary>
/// 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.
/// </summary>
public abstract class FontTestBase : TestBase
{
/// <summary>
/// Folder holding the test fonts in the output directory.
/// </summary>
protected static string FontFolder
{
get { return Path.Combine(AppContext.BaseDirectory, "TestFonts"); }
}

// -----------------------------------------------------------------------------------------
// Engines
// -----------------------------------------------------------------------------------------

private static readonly Lazy<OpenTypeFontEngine> _testFolderEngine =
new Lazy<OpenTypeFontEngine>(() => new OpenTypeFontEngine(cfg =>
{
cfg.FontDirectories.Add(GetExistingFontFolder());
cfg.SearchSystemDirectories = false;
}));

private static readonly Lazy<OpenTypeFontEngine> _systemFontsEngine =
new Lazy<OpenTypeFontEngine>(() => new OpenTypeFontEngine(cfg =>
{
cfg.FontDirectories.Add(GetExistingFontFolder());
cfg.SearchSystemDirectories = true;
}));

private static readonly Lazy<RenderContext> _testFolderContext =
new Lazy<RenderContext>(() => new RenderContext(() => TestFolderEngine));

private static readonly Lazy<RenderContext> _systemFontsContext =
new Lazy<RenderContext>(() => new RenderContext(() => SystemFontsEngine));

/// <summary>
/// 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).
/// </summary>
protected static OpenTypeFontEngine TestFolderEngine
{
get { return _testFolderEngine.Value; }
}

/// <summary>
/// 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 <see cref="RequireFont"/> so the test is Inconclusive on
/// machines that lack the font.
/// </summary>
protected static OpenTypeFontEngine SystemFontsEngine
{
get { return _systemFontsEngine.Value; }
}

/// <summary>
/// Render context over <see cref="TestFolderEngine"/>.
/// </summary>
protected static RenderContext TestFolderContext
{
get { return _testFolderContext.Value; }
}

/// <summary>
/// Render context over <see cref="SystemFontsEngine"/>.
/// </summary>
protected static RenderContext SystemFontsContext
{
get { return _systemFontsContext.Value; }
}

/// <summary>
/// Marks the test Inconclusive unless the font is available in the engine with the
/// requested subfamily.
/// </summary>
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;
}
}
}
216 changes: 216 additions & 0 deletions src/EPPlus.DrawingRenderer.Tests/Fonts/EmbedFontsMeasurementTests.cs
Original file line number Diff line number Diff line change
@@ -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
{
/// <summary>
/// Step 4: <see cref="SvgRenderOptions.EmbedFonts"/> decides whether text is measured with the
/// requested font or with its web substitute. <see cref="RenderContext.SubstituteWebFonts"/>
/// carries the decision down to measurement.
/// </summary>
[TestClass]
public class EmbedFontsMeasurementTests : FontTestBase
{
[TestInitialize]
public void Initialize()
{
ExcelPackage.License.SetNonCommercialOrganization("EPPlus Project");
}

private static ExcelPackage CreatePackage(Action<IEpplusFontConfiguration>? 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, "<tspan[^>]*?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<SvgRenderOptions> 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}).");
}
}
}
Loading
Loading