NejCommon.NET/Utils/ClosedXMLSetup.cs
2024-10-21 21:36:51 +02:00

80 lines
2.4 KiB
C#

using System.Diagnostics;
using ClosedXML.Excel;
using ClosedXML.Excel.Drawings;
using ClosedXML.Graphics;
namespace NejCommon.Utils;
public class FakeGraphicsEngine : IXLGraphicEngine
{
private static double PointsToPixels(double points, double dpi)
{
return points / 72.0 * dpi / 10.0;
}
public double GetDescent(IXLFontBase font, double dpiY)
{
return PointsToPixels(font.FontSize, dpiY);
}
public GlyphBox GetGlyphBox(ReadOnlySpan<int> graphemeCluster, IXLFontBase font, Dpi dpi)
{
int num = graphemeCluster.ToArray().Sum();
double value = PointsToPixels(font.FontSize, dpi.X);
double value2 = PointsToPixels((double)num * font.FontSize, dpi.X);
return new GlyphBox(descent: (float)Math.Round(GetDescent(font, dpi.Y), MidpointRounding.AwayFromZero), advanceWidth: (float)Math.Round(value2, MidpointRounding.AwayFromZero), emSize: (float)Math.Round(value, MidpointRounding.AwayFromZero));
}
public double GetMaxDigitWidth(IXLFontBase font, double dpiX)
{
return PointsToPixels(font.FontSize, dpiX);
}
public XLPictureInfo GetPictureInfo(Stream imageStream, XLPictureFormat expectedFormat)
{
return DefaultGraphicEngine.Instance.Value.GetPictureInfo(imageStream, expectedFormat);
}
public double GetTextHeight(IXLFontBase font, double dpiY)
{
return PointsToPixels(font.FontSize, dpiY);
}
public double GetTextWidth(string text, IXLFontBase font, double dpiX)
{
return PointsToPixels(text?.Length ?? 0 * font.FontSize, dpiX);
}
}
public static class ClosedXMLSetup
{
public static void Setup()
{
var font = GetFont();
if (font != null)
{
Console.WriteLine("ClosedXML: Using: " + font);
LoadOptions.DefaultGraphicEngine = new DefaultGraphicEngine(font);
}
else
{
Console.WriteLine("ClosedXML: Using stub GE");
LoadOptions.DefaultGraphicEngine = new FakeGraphicsEngine();
}
}
static string GetFont()
{
foreach (var orderFont in new string[] { "Calibri", "Microsoft Sans Serif", "Carlito", "Liberation Sans" })
{
foreach (var fontFamily in SixLabors.Fonts.SystemFonts.Collection.Families)
{
if (fontFamily.Name == orderFont)
return fontFamily.Name;
}
}
return null;
}
}