You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.Net Core环境下iText7的Document.Add添加Paragraph时抛空引用异常

iText7 调用document.Add触发空引用异常解决方案

核心原因

iText 7 内部处理字体元数据逻辑依赖System.Text.Encoding.CodePages提供的编码支持,.NET Core/.NET 5+ 环境默认未注册该编码提供程序,相关调用返回空值后触发空引用异常。

解决步骤

  1. 安装必要NuGet包
    除了已安装的itext7 7.1.16外,还需要安装System.Text.Encoding.CodePages包,可通过NuGet包管理器搜索安装,或者使用包管理控制台执行命令:
    Install-Package System.Text.Encoding.CodePages
  2. 入口处注册编码提供程序
    在Main方法的第一行添加编码注册代码,确保iText调用编码相关逻辑时可以正常获取实例。
  3. 可选:修改文件输出路径为当前运行目录,避免磁盘根目录写入权限不足的问题

修正后完整代码

using System;
using System.IO;
using System.Text;
using iText.Kernel.Geom;
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;

class Program
{
    static void Main(string[] args)
    {
        // 注册编码提供程序,必须放在业务逻辑前
        Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
        
        // 输出到程序运行目录,避免权限问题
        string outputPath = Path.Combine(AppContext.BaseDirectory, "hello.pdf");
        PdfDocument pdfDocument = new PdfDocument(new PdfWriter(new FileStream(outputPath, FileMode.Create, FileAccess.Write)));
        Document document = new Document(pdfDocument, PageSize.A4);

        String line = "Hello! Welcome to iTextPdf";
        document.Add(new Paragraph(line));

        document.Close();
        Console.WriteLine("Awesome PDF just got created.");
        Console.WriteLine("Hello World!");
    }
}

其他排查点

如果修改后仍然报错,请检查:

  • 所有命名空间是否正确导入,不要引用其他第三方封装的iText类
  • 项目目标框架是否符合iText 7.1.16的支持范围,.NET Core 3.1及以上版本均可正常兼容
  • 清理项目缓存后重新编译运行,避免旧编译文件导致的异常

内容的提问来源于stack exchange,提问作者B.Balamanigandan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 03:03:02