PDFSharp WPF 1.32 专用字体不适用于 Azure Blob 存储

PDFSharp WPF 1.32 private fonts will not work with Azure Blob storage

我有一些代码可以使用 PDFSharp 将使用私有字体的文本添加到 PDF 文件。如果字体位于本地文件系统上,这会成功,但当我向它提供 url 存储在 Azure 博客存储上的字体时,它不起作用。我还尝试在他们的 CDN 上使用 google 字体,但也没有用。从网络加载字体有问题吗url?

示例代码如下。请注意,我已经解决了 Azure blob 存储上的 CORS issue,所以不是那样。

private readonly XPdfFontOptions _fontOptions = 
    new XPdfFontOptions(PdfFontEncoding.Unicode, PdfFontEmbedding.Always);
private static readonly XPrivateFontCollection PrivateFontCollection =
    XPrivateFontCollection.Global;

[Test]
public async Task Test01RawPdfSharp()
{
    //SETUP 
    var account = "labelapptest";
    var fs = new FileStore(account);
    var fontUrl =
        "http://labelapptest.blob.core.windows.net/designernospamcom/justyna sokolowska - erazm-regular.otf";
    var pdfUrl =
        "https://labelapptest.blob.core.windows.net/label-highrez-blank/blank-label00001.pdf";
    var fontFamily = "Erazm Regular";
    var localFontPath = Path.Combine(TestFileHelpers.GetTestDataFileDirectory(@"\TestFonts"),
        "Justyna Sokolowska - Erazm-Regular.otf");

    //ATTEMPT
    var sFontFamilyname = "./#" + fontFamily;
    var uri = new Uri(fontUrl);
    PrivateFontCollection.Add(uri, sFontFamilyname);

    var readDirStatus = await fs.GetDirHandleAsync(FileStorageTypes.LabelHighRezBlank);
    using (var readStream = new MemoryStream())
    {
        await readDirStatus.Result.ReadFileAsync(readStream, pdfUrl);
        readStream.Seek(0, SeekOrigin.Begin);
        var document = PdfReader.Open(readStream);
        var gfx = XGraphics.FromPdfPage(document.Pages[0]);

        var font = new XFont(fontFamily, new XUnit(12, XGraphicsUnit.Point), XFontStyle.Regular, _fontOptions);
        var brush = new XSolidBrush(XColor.FromKnownColor(XKnownColor.Red));
        gfx.DrawString("Hello world", font, brush, 10, 10);
    }
    //VERIFY
}    

在上面的示例中,如果我在 uri 中使用 fontUrl 来添加字体,那么代码会在创建 XFont 的行(从底部开始第 6 个)处失败。另一方面,如果我使用 localFontPath 那么它就可以工作。

错误是:Cannot get a matching glyph typeface for font 'Erazm Regular' at line at PdfSharp.Drawing.XFont.Initialize() in XFont.cs: line 234.

注意:我已经下载并编辑了 1.32 PDFSharp 代码以替换 Debugger.Break 语句,此时出现异常。 NuGet 版本有一个 Debugger.Break 会导致已发布的代码挂起 - 请参阅 关于该问题。

更新

最后我换成了 PDFsharp WPF 1.50 beta,因为它的字体处理要好得多,而且我也没有解决通过 http link 加载字体的问题。看起来效果很好。

PrivateFontCollection.Add(uri, sFontFamilyname) 的调用只是将 URI 传递给 new System.Windows.Media.FontFamily(baseUri, familyName)。我不知道 Media.FontFamily 是否可以处理 Azure 存储的 URI。

我们将 PrivateFontCollection 与来自资源的字体一起使用 - 从资源加载字体是 FontFamily Constructor (Uri, String) 的帮助中给出的唯一示例。这是已知可与 PDFsharp 一起使用的 URI 类型。

FontFamily Constructor (Uri, String) 的语法有些神秘,最小的错误都会导致 "not found"。