PdfSharp - 获取自定义 FontResolver 以包含标准/已安装的字体

问题描述 投票:0回答:1

上下文

在我的 C# 应用程序中,我使用 PdfSharp 创建自定义 PDF 文档。我必须使用一些自定义字体,这些字体事先没有安装在系统上,而是可以通过资源文件作为字节数组使用。实现这一目标的最简单方法似乎是使用自定义字体解析器在 GetFont-Function 中加载这些字体。然而,一旦我为 GetFont 实现了我自己的逻辑,我就无法再使用任何其他标准字体,如 Verdana,它们没有明确加载到 GetFont 中。

代码

以下代码是我现在使用的代码的简化版本。

    public class CustomFontResolver : IFontResolver
    {
        public string DefaultFontName => throw new NotImplementedException();

        public byte[] GetFont(string faceName)
        {
            switch (faceName)
            {
                case "MyCustomFont":
                    return Resources.MY_CUSTOM_FONT;
            }

            // This is the part where I would implement the "standard font loading"-logic

            return null;
        }

        public FontResolverInfo ResolveTypeface(string familyName, bool isBold, bool isItalic)
        {
            if(familyName.Equals("MyCustomFont", StringComparison.CurrentCultureIgnoreCase))
            {
                return new FontResolverInfo("MyCustomFont");
            }

            return PlatformFontResolver.ResolveTypeface(familyName, isBold, isItalic);
        }
    }

这意味着,在设置

GlobalFontSettings.FontResolver = new CustomFontResolver();
后,以下行将正常工作:

var font = new XFont("MyCustomFont", 20, XFontStyle.Regular);

但是加载像 Verdana 这样的标准字体将失败并出现异常,因为我的 GetFont 函数返回 null:

var font = new XFont("Verdana", 20, XFontStyle.Regular);

问题

如何在我的代码中将标准/已安装的字体作为字节数组加载,或者以另一种方式修改 FontResolver 以处理这些字体本身?

我之前尝试过使用其他方式而不是编写自定义字体解析器,但这没有成功,因为 PdfSharp 不允许将字体添加到其标准解析器。

我也找过加载字体并将它们转换为字节数组的方法,但找不到任何方法。

c# .net fonts pdfsharp
1个回答
0
投票

PdfSharp 的来源有一个 if 语句来检查是否设置了

GlobalFontSettings.FontResolver
。如果没有,它将退回到它自己的平台相关实现。

你该做的,在你的心中

// This is the part where I would implement the "standard font loading"-logic

调用相同的回退方法:

PlatformFontResolver.ResolveTypeface(string familyName, bool isBold, bool isItalic)
© www.soinside.com 2019 - 2024. All rights reserved.