Search code examples
androidxamarin.formspdfsharp

Loading a Font with PdfSharp .Net Standard preview from Xamarin.Forms fails: No appropriate font found


I am currently assessing how to generate a PDF from Xamarin.Forms (currently running the app on Android, only) and checking the .NET Standard port of PdfSharp.

Drawing to the PDF and showing it works, but I'm having issues writing text to the document. When I am trying to load an XFont with the following code

var font = new XFont("sans-serif", 20);

it fails with the exception

System.InvalidOperationException: No appropriate font found.

According to these samples, it is supposed to work this way, but they are for PdfSharp.Xamarin and not the PdfSharp .NET Standard. According to this answer the "sans-serif" font family should be correct, but I've desperately tried other options, like "Roboto", but to no avail.

Is PdfSharp for .NET Standard compatible with Xamarin at all? (It lists PdfSharp.Xamarin as a source it has been created from, hence I assumed it.) Is there anything else I have missed?

EDIT

I tried PdfSharp.Xamarin and it did work. Obviously this is an issue with the .NET Standard port.


Solution

  • I had similar issue and i resolved it by writing my own implementation of IFontResolver and assigning it to GlobalFontSettings.FontResolver.

    public class FileFontResolver : IFontResolver // FontResolverBase
    {
        public string DefaultFontName => throw new NotImplementedException();
    
        public byte[] GetFont(string faceName)
        {
            using (var ms = new MemoryStream())
            {
                using (var fs = File.Open(faceName, FileMode.Open))
                {
                    fs.CopyTo(ms);
                    ms.Position = 0;
                    return ms.ToArray();
                }
            }
        }
    
        public FontResolverInfo ResolveTypeface(string familyName, bool isBold, bool isItalic)
        {
            if (familyName.Equals("Verdana", StringComparison.CurrentCultureIgnoreCase))
            {
                if (isBold && isItalic)
                {
                    return new FontResolverInfo("Fonts/Verdana-BoldItalic.ttf");
                }
                else if (isBold)
                {
                    return new FontResolverInfo("Fonts/Verdana-Bold.ttf");
                }
                else if (isItalic)
                {
                    return new FontResolverInfo("Fonts/Verdana-Italic.ttf");
                }
                else
                {
                    return new FontResolverInfo("Fonts/Verdana-Regular.ttf");
                }
            }
            return null;
        }
    }
    

    Then tell PDFSharp to use it:

    GlobalFontSettings.FontResolver = new FileFontResolver();