调用iText的ShowTextAligned时抛出System.NullReferenceException求助
解决iText添加页眉时的System.NullReferenceException异常
问题重现
添加PDF页眉时触发空引用异常,错误信息如下:
System.NullReferenceException
HResult=0x80004003
Message=Object reference not set to an instance of an object.
Source=itext.kernel
StackTrace:
at iText.Kernel.Pdf.PdfDictionary.Get(PdfName key, Boolean asDirect)
触发代码:
document.ShowTextAligned(header, x, y, i, TextAlignment.CENTER, VerticalAlignment.BOTTOM, 0);
页眉段落定义:
Paragraph header = new Paragraph("ABCD inc." ) .SetFont(PdfFontFactory.CreateFont(StandardFonts.HELVETICA)) .SetFontSize(8);
可能的原因及解决方案
1. Document对象未正确初始化或已被释放
如果document实例为null,或者对应的PdfDocument已被关闭,调用ShowTextAligned时会触发底层字典操作的空引用。
- 确保初始化顺序正确:先创建
PdfWriter,再创建PdfDocument,最后实例化Document:using var writer = new PdfWriter("output.pdf"); using var pdfDoc = new PdfDocument(writer); using var document = new Document(pdfDoc); - 调用
ShowTextAligned时,确保document和pdfDoc都处于未关闭状态。
2. 页码参数i无效
ShowTextAligned的第4个参数是目标页码,必须是文档中已存在的有效页码(从1开始)。如果传入的页码不存在(比如文档还未创建任何页面,或页码小于1),会导致获取对应页面字典时为空。
- 如果是在创建页面后添加页眉,确保页码
i与已创建的页面数匹配; - 推荐使用页面事件处理器添加页眉(iText标准做法),避免手动管理页码:
public class HeaderFooterEventHandler : PdfPageEventHelper { private readonly Paragraph _header; public HeaderFooterEventHandler(Paragraph header) { _header = header; } public override void EndPage(PdfDocument pdfDoc, PdfPage page) { var document = new Document(pdfDoc); // 设置页眉位置,比如页面顶部下方10单位 document.ShowTextAligned(_header, pdfDoc.GetDefaultPageSize().GetWidth() / 2, pdfDoc.GetDefaultPageSize().GetTop() - 10, page.GetPageNumber(), TextAlignment.CENTER, VerticalAlignment.BOTTOM, 0); } } // 使用方式 var header = new Paragraph("ABCD inc.") .SetFont(PdfFontFactory.CreateFont(StandardFonts.HELVETICA)) .SetFontSize(8); pdfDoc.AddEventHandler(PdfDocumentEvent.END_PAGE, new HeaderFooterEventHandler(header));
3. 字体创建异常(罕见)
虽然使用StandardFonts.HELVETICA一般不会出问题,但如果PdfFontFactory.CreateFont返回null,会导致段落的字体属性为空,间接引发异常。
- 可以添加空值检查:
var font = PdfFontFactory.CreateFont(StandardFonts.HELVETICA); if (font == null) { throw new InvalidOperationException("Failed to create font."); } Paragraph header = new Paragraph("ABCD inc." ) .SetFont(font) .SetFontSize(8);
内容的提问来源于stack exchange,提问作者Durgesh Awasthi
相关产品推荐
相关产品推荐

