升级PDFsharp-MigraDoc后NewFontResolver未找到及Debian字体配置问题
问题修复与字体使用方案
一、修复NewFontResolver找不到的错误
NewFontResolver并非PDFsharp-MigraDoc的内置类型,你需要自定义实现IFontResolver接口来创建这个类,具体步骤如下:
- 先引入必要的命名空间:
using PdfSharp.Fonts; using System.IO; using System.Collections.Generic;
- 编写自定义的字体解析器类:
public class NewFontResolver : IFontResolver { private readonly string _fontDirectory; public NewFontResolver(string fontDir) { _fontDirectory = fontDir; } // 匹配字体名称与对应样式的ttf文件 public FontResolverInfo ResolveTypeface(string familyName, bool isBold, bool isItalic) { string fileName = familyName switch { "Times New Roman" when !isBold && !isItalic => "times.ttf", "Times New Roman" when isBold && !isItalic => "timesbd.ttf", "Times New Roman" when !isBold && isItalic => "timesi.ttf", "Times New Roman" when isBold && isItalic => "timesbi.ttf", "Arial" when !isBold && !isItalic => "arial.ttf", "Arial" when isBold && !isItalic => "arialbd.ttf", "Arial" when !isBold && isItalic => "ariali.ttf", "Arial" when isBold && isItalic => "arialbi.ttf", _ => null }; return fileName == null ? null : new FontResolverInfo(familyName); } // 读取对应字体文件的字节内容 public byte[] GetFont(string faceName) { string fileName = faceName switch { "Times New Roman" => "times.ttf", "Times New Roman Bold" => "timesbd.ttf", "Times New Roman Italic" => "timesi.ttf", "Times New Roman Bold Italic" => "timesbi.ttf", "Arial" => "arial.ttf", "Arial Bold" => "arialbd.ttf", "Arial Italic" => "ariali.ttf", "Arial Bold Italic" => "arialbi.ttf", _ => null }; if (fileName == null) return null; string fullPath = Path.Combine(_fontDirectory, fileName); return File.ReadAllBytes(fullPath); } }
- 修改静态构造函数,传入Debian上的字体目录:
static ReportTemplateBase() { string fontDir = "/usr/share/fonts/winfonts"; GlobalFontSettings.FontResolver = new NewFontResolver(fontDir); }
二、在Debian下使用指定目录的字体生成PDF
- 确保字体文件权限正常
执行命令让程序能读取字体文件:
sudo chmod -R 644 /usr/share/fonts/winfonts sudo chown -R root:root /usr/share/fonts/winfonts
- 更新系统字体缓存(可选但推荐)
让Debian识别新增的字体,避免系统层面的字体识别问题:
fc-cache -fv /usr/share/fonts/winfonts
- 在PDF生成代码中直接调用字体
编写PDF内容时,直接指定字体名称即可,示例:
var document = new MigraDoc.DocumentObjectModel.Document(); var section = document.AddSection(); var paragraph = section.AddParagraph("测试内容"); paragraph.Format.Font.Name = "Times New Roman"; paragraph.Format.Font.Size = 14; paragraph.Format.Font.Bold = true;
内容的提问来源于stack exchange,提问作者Andrus
相关产品推荐
相关产品推荐

