感谢指针@PDFSharp团队。这里是我的PdfSharp 1.5 beta3b实现:
添加你想你的项目的字体 - 在我下面的例子,我把Arial
在MyProject\fonts\arial\arial.ttf
等设置每个字体文件作为嵌入资源(属性 - >生成操作)。
应用的字体解析只有一次使用这样的静态调用:
MyFontResolver.Apply(); // Ensures it's only applied once
这里的字体解析类:
class MyFontResolver : IFontResolver
{
public FontResolverInfo ResolveTypeface(string familyName, bool isBold, bool isItalic)
{
// Ignore case of font names.
var name = familyName.ToLower().TrimEnd('#');
// Deal with the fonts we know.
switch (name)
{
case "arial":
if (isBold)
{
if (isItalic)
return new FontResolverInfo("Arial#bi");
return new FontResolverInfo("Arial#b");
}
if (isItalic)
return new FontResolverInfo("Arial#i");
return new FontResolverInfo("Arial#");
}
// We pass all other font requests to the default handler.
// When running on a web server without sufficient permission, you can return a default font at this stage.
return PlatformFontResolver.ResolveTypeface(familyName, isBold, isItalic);
}
/// <summary>
/// Return the font data for the fonts.
/// </summary>
public byte[] GetFont(string faceName)
{
switch (faceName)
{
case "Arial#":
return FontHelper.Arial;
case "Arial#b":
return FontHelper.ArialBold;
case "Arial#i":
return FontHelper.ArialItalic;
case "Arial#bi":
return FontHelper.ArialBoldItalic;
}
return null;
}
internal static MyFontResolver OurGlobalFontResolver = null;
/// <summary>
/// Ensure the font resolver is only applied once (or an exception is thrown)
/// </summary>
internal static void Apply()
{
if (OurGlobalFontResolver == null || GlobalFontSettings.FontResolver == null)
{
if (OurGlobalFontResolver == null)
OurGlobalFontResolver = new MyFontResolver();
GlobalFontSettings.FontResolver = OurGlobalFontResolver;
}
}
}
/// <summary>
/// Helper class that reads font data from embedded resources.
/// </summary>
public static class FontHelper
{
public static byte[] Arial
{
get { return LoadFontData("MyProject.fonts.arial.arial.ttf"); }
}
public static byte[] ArialBold
{
get { return LoadFontData("MyProject.fonts.arial.arialbd.ttf"); }
}
public static byte[] ArialItalic
{
get { return LoadFontData("MyProject.fonts.arial.ariali.ttf"); }
}
public static byte[] ArialBoldItalic
{
get { return LoadFontData("MyProject.fonts.arial.arialbi.ttf"); }
}
/// <summary>
/// Returns the specified font from an embedded resource.
/// </summary>
static byte[] LoadFontData(string name)
{
var assembly = Assembly.GetExecutingAssembly();
// Test code to find the names of embedded fonts
//var ourResources = assembly.GetManifestResourceNames();
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;
}
}
}
这是基于这两个单一的,完整的和工人阶级几乎相同的帖子:this blog和this forum。
看看这些链接中的代码,它看起来像我仍然需要将字体文件附加到我的项目,即使它可能存在于服务器上 - 是否正确? – noelicus
PDFsharp必须能够访问字体文件。如果它驻留在服务器上的受保护系统文件夹中,那么它仍然无法到达。使用PDFsharp 1.50,您需要一个字节数组,因此您可以将其作为资源添加到您的程序集或作为内容文件添加到您的项目中。 –