My goal is to generate a PDF from an SVG, but I am having trouble getting custom (.otf) fonts into the output document. I'm trying to load the custom fonts with an ITypefaceProvider, so that the custom fonts are reflected in the output document.
My TypefaceProvider looks like:
using SkiaSharp;
using Svg.Skia.TypefaceProviders;
namespace SomeNamespace;
public class MyCustomTypefaceProvider : ITypefaceProvider
{
private readonly SKFontManager _fontManager;
private readonly List<SKTypeface> _typefaces = new();
public MyCustomTypefaceProvider()
{
_fontManager = SKFontManager.CreateDefault();
}
public void AddTypeface(Stream stream)
{
_typefaces.Add(_fontManager.CreateTypeface(stream));
}
public SKTypeface? FromFamilyName(string fontFamily, SKFontStyleWeight fontWeight, SKFontStyleWidth fontWidth, SKFontStyleSlant fontStyle)
{
return _typefaces
.FirstOrDefault(typeface => typeface.FamilyName == fontFamily
&& typeface.FontStyle.Width == (int)fontWidth
&& typeface.FontStyle.Weight == (int)fontWeight
&& typeface.FontStyle.Slant == fontStyle);
}
}
My SVG to PDF conversion looks like:
var provider = new MyCustomTypefaceProvider();
var svgContent = "<svg>... some file...</svg>";
var fontResources = new[] { "SomeNamespace.fonts.Fonts.Font Bold.otf" };
foreach (var fontResource in fontResources)
{
using var fontStream = typeof(ThisClass).Assembly.GetManifestResourceStream(fontResource)!;
provider.AddTypeface(fontStream);
}
var svg = new SKSvg();
svg.Settings.TypefaceProviders = new List<ITypefaceProvider>{provider};
svg.FromSvg(svgContent);
var picture = svg.Picture!;
var memoryStream = new MemoryStream();
picture.ToPdf(memoryStream, SKColors.Transparent, 1f, 1f);
return memoryStream;
The SVG (for example) contains lines like:
<text fill="#2F0051" xml:space="preserve" style="white-space: pre" font-family="Font" font-size="28" font-weight="bold" letter-spacing="0em"><tspan x="866.781" y="152.6">Example text</tspan></text>
When I add a breakpoint the lines in the MyCustomTypefaceProvider.FromFamilyName method are hit and the method actually returns a fontface. This font however is not used.
Am I missing a step or is there an other way to use fonts in Svg.Skia?