我正在开发一个 C# .NET WPF 桌面应用程序,该应用程序将生成一个 PDF,该 PDF 需要非常特定的字体,而系统上不会安装该字体。我正在使用 PdfSharp-WPF v1.32。文件
importantSc.ttf
位于项目资源文件夹中。
我最好的选择是我的 URI 路径是错误的,但我认为我的路径是正确的。我的字体系列名称确实正确,因为它在我的开发计算机上安装字体时有效。
using System;
using PdfSharp.Drawing;
using PdfSharp.Pdf;
using PdfSharp.Pdf.IO;
using Microsoft.Win32;
using PdfSharp.Drawing.Layout;
using System.Collections.Generic;
using System.Windows.Input;
using System.Windows;
namespace MyProject
{
public class MyPdfFile
{
private PdfDocument doc;
public void MakePdf()
{
Double x1, y1;
XBrush brush = XBrushes.Black;
XGraphics xgf = XGraphics.FromPdfPage(page);
doc = new PdfDocument();
PdfPage page = doc.AddPage();
// Load in a private font to use.
XPrivateFontCollection privateFontCollection = new XPrivateFontCollection();
String fontFamilyName = "Important Script AM";
String fontUriPath = @"pack://application:,,,/importantSc.ttf";
Uri fontUri = new Uri( fontUriPath );
privateFontCollection.Add(fontUri, "./#" + fontFamilyName);
XFont font = new XFont(fontFamilyName, 9, XFontStyle.Regular); // <-- the error happens here
//Add text to page
x1 = 1.96 * 72;
y1 = 3.25 * 72;
String printString = "I wish this would work!";
xgf.DrawString(printString, font, brush, x1, y1);
xgf.Dispose();
}
}
}
我收到以下错误:
PdfSharp-WPF.dll 中发生“System.InvalidOperationException”类型的未处理异常
其他信息:无法获取字体“重要脚本 AM”的匹配字形字体。
这里有一些注意事项。
PDFsharp 1.50(当前为 beta 3b)的字体处理变得更好。我会使用 1.50,因为我认为新的测试版比旧的“稳定”版本更好。
使用
IFontResolver
,您可以避免处理“pack:”资源语法。
您可以使用 JetBrains 的 DotNetPeek 等工具来检查 TTF 是否真正嵌入到程序集中以及以什么名称嵌入。
可以使用PDFsharp的源码包,通过
privateFontCollection.Add
调试,看是否找到字体,如果找到,是哪些字体。