C#中使用iText7转换HTML到PDF时出现NullReferenceException错误
iText Html2Pdf 转换时触发 System.NullReferenceException(FontCache 初始化失败)
问题代码
using iText.Html2pdf; // 省略其他引用 public bool HtmlToPDF(string folderName, string htmlFilePath, string otherNum) { Console.WriteLine("Running HtmltoPDF\n"); string outputPath = new Uri(folderName + "\\" + otherNum.pdf).LocalPath; try { FileStream htmlSource = File.Open(htmlFilePath, FileMode.Open); FileStream pdfDest = File.Open(outputPath, FileMode.Create); ConverterProperties converterProperties = new ConverterProperties(); HtmlConverter.ConvertToPdf(htmlSource, pdfDest, converterProperties); } catch (Exception ex) { Console.WriteLine(ex.Message); return false; } Console.WriteLine("Successfully completed HtmltoPDF and returned true\n"); return true; }
报错信息
System.NullReferenceException HResult=0x80004003 Message=Object reference not set to an instance of an object. Source=itext.io StackTrace: at iText.IO.Font.FontCache..cctor()
解决方案
统一iText相关NuGet包版本
所有iText系列包(itext.html2pdf、itext.io、itext.kernel等)必须使用完全相同的版本,版本不一致会导致底层组件初始化冲突,直接引发此类空引用异常。打开NuGet包管理器,检查并同步所有iText包的版本。修复路径拼接错误
当前输出路径拼接存在语法错误,otherNum.pdf会被解析为未定义的变量,正确写法建议用Path.Combine(避免路径分隔符兼容问题):// 替换原outputPath代码 string outputPath = Path.Combine(folderName, $"{otherNum}.pdf");确保字体缓存目录权限正常
FontCache在静态构造时会尝试访问系统临时目录或系统字体目录,如果程序运行账户权限不足(比如Windows服务使用Local Service账户),会导致初始化失败。可以手动指定字体提供器,绕过系统字体目录的依赖:ConverterProperties converterProperties = new ConverterProperties(); // 使用默认字体提供器,允许加载系统字体、嵌入字体 converterProperties.SetFontProvider(new DefaultFontProvider(true, true, true)); // 若需要自定义字体,可添加指定字体文件 // DefaultFontProvider fontProvider = new DefaultFontProvider(); // fontProvider.AddFont(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "fonts", "simhei.ttf")); // converterProperties.SetFontProvider(fontProvider);重置NuGet包缓存
如果NuGet包存在损坏或缺失,卸载所有iText相关包,清理NuGet缓存后重新安装:- 右键项目 → 管理NuGet包 → 卸载所有iText开头的包
- 打开工具 → NuGet包管理器 → 程序包管理器设置 → 清除所有NuGet缓存
- 重新安装对应版本的itext.html2pdf包(会自动安装依赖的itext.io、itext.kernel等)
内容的提问来源于stack exchange,提问作者Genetic1989
相关产品推荐
相关产品推荐

