应使用 iText 7(NuGet 包名 itext7),而非已停更的 iTextSharp;生成 PDF 必须调用 document.Close(),且需注册支持 UTF-8 的中文字体并指定 PdfEncodings.IDENTITY_H 编码。

用 iTextSharp 7 生成 PDF 前先确认版本和包名
iTextSharp 已在 2016 年停止维护,官方明确不再支持 .NET Framework 的旧版(如 iTextSharp 5.x);现在主流是 iText 7(对应 NuGet 包名 iText7 和 iText7.pdfhtml 等),且需注意许可证变化:免费使用仅限 AGPL,商用必须购买授权。
如果你项目仍用 .NET Framework 4.7+ 或 .NET 5/6/7/8,应安装:
Install-Package itext7
而不是 iTextSharp —— 后者在 NuGet 上已下架,强行引用老 DLL 可能导致 MissingMethodException 或签名验证失败。
最简 PDF 生成代码:别漏掉 Document.Close()
新手常写完 document.Add() 就结束,结果生成空文件或损坏 PDF。iText 7 是流式写入,必须显式关闭文档才能刷出内容。
典型正确流程:
- 用
FileStream或MemoryStream构造PdfWriter - 用
PdfWriter构造PdfDocument - 再用
PdfDocument构造Document - 调用
document.Add(new Paragraph("Hello"))等添加内容 -
最后必须调用
document.Close()(或pdfDoc.Close()),否则文件无内容
示例片段:
using var fs = new FileStream("out.pdf", FileMode.Create);
using var writer = new PdfWriter(fs);
using var pdf = new PdfDocument(writer);
using var document = new Document(pdf);
document.Add(new Paragraph("测试中文"));
document.Close(); // 这行不能少
中文字体支持:不注册字体就显示方框
iText 7 默认不带中文字体,直接写中文会变成空白或方块。必须手动注册一个支持 UTF-8 的 TrueType 字体(如 simhei.ttf、msyh.ttc 或开源的 NotoSansCJKsc-Regular.otf)。
关键步骤:
- 把字体文件放在项目里,设为
Copy to Output Directory - 用
PdfFontFactory.CreateFont("simhei.ttf", PdfEncodings.IDENTITY_H, true)加载 - 创建
Paragraph时传入该字体:new Paragraph("你好").SetFont(font) - 或者全局设置默认字体:
document.SetFont(font)
注意:PdfEncodings.IDENTITY_H 是必需参数,用错成 WINANSI 会导致乱码;路径错误会抛 IOException:“Cannot read font file”。
表格、图片、页眉页脚这些进阶功能,别从零手写布局
iText 7 的 Table、Image、Canvas 都是底层 API,自由度高但易出错:比如 Table 宽度设为 UnitValue.CreatePercentValue(100) 才占满页面,设成 100 是 100pt 宽;Image 忘记调用 ScaleToFit() 会溢出页面。
更稳的做法:
- 简单报表优先用
HtmlConverter.ConvertToPdf()+ HTML 模板(需装iText7.pdfhtml包) - 页眉页脚用
DocumentRenderer+HeaderFooterEventHandler,而不是在每页手动画 - 避免在循环里反复新建
PdfFont实例——字体对象可复用,重复创建影响性能
真实项目里,90% 的 PDF 需求(合同、订单、导出列表)用 HTML 转换更快更可控,手写 iText 代码只适合需要像素级控制或动态水印等场景。
字体注册、Close() 调用、编码参数这三处,线上环境最容易漏,一漏就是静默失败。










