为了解决这个问题,我将问题交叉发布到 PDFSharp 论坛 Post,答案为我指明了创建要使用的 字体解析器 的正确方向:
- 从NuGet 安装 PDFsharp 1.50 beta 2 的 WPF 版本
- 使用字体解析器选择字体Using private fonts with PDFsharp 1.50 beta 2 or MigraDoc
- 将 unicode 字体添加为项目中的嵌入资源。
我将此部署到 Azure 云服务并确认正确使用了 unicode 字体。
PDFSharp 的文档不完整,因为它声明 GDI 构建是用于 .NET 网站的正确构建,但实际上并非如此。相反,使用 FontResolver 的 WPF 构建工作。
示例
在Global.asax.cs 中设置FontResolver:
PdfSharp.Fonts.GlobalFontSettings.FontResolver = new MyFontResolver();
创建一个名为 MyFontResolver 的新类,它使用嵌入资源中包含的额外字体系列来扩展默认实现。
字体本身应通过 build action = Embedded Resource 添加到字体目录。
public class MyFontResolver : IFontResolver
{
public FontResolverInfo ResolveTypeface(string familyName,
bool isBold,
bool isItalic)
{
// Ignore case of font names.
var name = familyName.ToLower();
// Add fonts here
switch (name)
{
case "arial unicode ms":
return new FontResolverInfo("ArialUnicodeMS#");
}
//Return a default font if the font couldn't be found
//this is not a unicode font
return PlatformFontResolver.ResolveTypeface("Arial", isBold, isItalic);
}
// Return the font data for the fonts.
public byte[] GetFont(string faceName)
{
switch (faceName)
{
case "ArialUnicodeMS#": return FontHelper.ArialUnicodeMS; break;
}
return null;
}
}
从嵌入式资源中读取字体数据的助手类。
public static class FontHelper
{
public static byte[] ArialUnicodeMS
{
//the font is in the folder "/fonts" in the project
get { return LoadFontData("MyApp.fonts.ARIALUNI.TTF"); }
}
/// Returns the specified font from an embedded resource.
static byte[] LoadFontData(string name)
{
var assembly = Assembly.GetExecutingAssembly();
using (Stream stream = assembly.GetManifestResourceStream(name))
{
if (stream == null)
throw new ArgumentException("No resource with name " + name);
int count = (int)stream.Length;
byte[] data = new byte[count];
stream.Read(data, 0, count);
return data;
}
}
}
在生成PDF的时候像往常一样定义字体,例如:
var style = document.Styles["Normal"];
style.Font.Name = "Arial Unicode MS";
style.Font.Size = 8;