78 lines
2.2 KiB
C#
78 lines
2.2 KiB
C#
using System;
|
|
using System.IO;
|
|
using PdfSharp.Drawing;
|
|
using PdfSharp.Fonts;
|
|
|
|
namespace spplus;
|
|
|
|
/// <summary>
|
|
/// Custom font resolver for PdfSharp that loads fonts from the res/fonts directory.
|
|
/// </summary>
|
|
public class CustomFontResolver : IFontResolver
|
|
{
|
|
private static string? _fontPath;
|
|
|
|
public CustomFontResolver()
|
|
{
|
|
// Try to locate the fonts directory
|
|
var basePath = AppDomain.CurrentDomain.BaseDirectory;
|
|
var possiblePaths = new[]
|
|
{
|
|
Path.Combine(basePath, "res", "fonts"),
|
|
Path.Combine(basePath, "fonts"),
|
|
Path.Combine(Directory.GetCurrentDirectory(), "res", "fonts"),
|
|
Path.Combine(Directory.GetCurrentDirectory(), "fonts"),
|
|
};
|
|
|
|
foreach (var path in possiblePaths)
|
|
{
|
|
if (Directory.Exists(path))
|
|
{
|
|
_fontPath = path;
|
|
break;
|
|
}
|
|
}
|
|
|
|
if (_fontPath == null)
|
|
{
|
|
throw new DirectoryNotFoundException(
|
|
$"Font directory not found. Searched: {string.Join(", ", possiblePaths)}");
|
|
}
|
|
}
|
|
|
|
public FontResolverInfo ResolveTypeface(string familyName, bool isBold, bool isItalic)
|
|
{
|
|
// Map family name to font file
|
|
var fileName = familyName switch
|
|
{
|
|
"Cantarell" => isBold
|
|
? isItalic ? "Cantarell-BoldItalic.ttf" : "Cantarell-Bold.ttf"
|
|
: isItalic ? "Cantarell-Italic.ttf" : "Cantarell-Regular.ttf",
|
|
_ => isBold
|
|
? isItalic ? "Cantarell-BoldItalic.ttf" : "Cantarell-Bold.ttf"
|
|
: isItalic ? "Cantarell-Italic.ttf" : "Cantarell-Regular.ttf"
|
|
};
|
|
|
|
var fontPath = Path.Combine(_fontPath, fileName);
|
|
|
|
if (!File.Exists(fontPath))
|
|
{
|
|
throw new FileNotFoundException($"Font file not found: {fontPath}");
|
|
}
|
|
|
|
// Return a FontResolverInfo with the font path
|
|
return new FontResolverInfo(fontPath);
|
|
}
|
|
|
|
public byte[]? GetFont(string faceName)
|
|
{
|
|
// faceName is the path returned by ResolveTypeface
|
|
if (File.Exists(faceName))
|
|
{
|
|
return File.ReadAllBytes(faceName);
|
|
}
|
|
|
|
return null;
|
|
}
|
|
}
|