C#使用iTextSharp创建PDF时PdfWriter.GetInstance行报NullReferenceException求助
iTextSharp导出PDF空引用异常解决方案
触发异常的核心原因排查方向
- 所使用的iTextSharp版本存在已知的
PdfWriter.GetInstance方法空引用bug PageSize.A4.Rotate()调用返回异常导致Document初始化后内部属性为空- 未拆分参数初始化逻辑,无法确认
Document或FileStream实例是否在创建时就已为空 - 导出路径权限不足或被占用,导致
FileStream初始化异常触发内部空引用
修复代码示例
private void button4_Click(object sender, EventArgs e) { using (SaveFileDialog sfd = new SaveFileDialog() { Filter = "PDF file|*.pdf", ValidateNames = true }) { if (sfd.ShowDialog() == DialogResult.OK) { iTextSharp.text.Document doc = null; FileStream fs = null; try { // 先初始化基础大小,后续单独设置旋转避免初始化异常 doc = new iTextSharp.text.Document(PageSize.A4); doc.SetPageSize(PageSize.A4.Rotate()); // 单独创建文件流,指定读写权限避免异常 fs = new FileStream(sfd.FileName, FileMode.Create, FileAccess.Write, FileShare.None); if(doc == null || fs == null) { MessageBox.Show("初始化参数为空", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } PdfWriter.GetInstance(doc, fs); doc.Open(); // 增加空值判断避免文本框为空时报错 doc.Add(new iTextSharp.text.Paragraph(richTextBox1?.Text ?? string.Empty)); MessageBox.Show("PDF导出成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { // 增加判断避免未初始化时调用Close触发二次空引用 if (doc != null && doc.IsOpen()) { doc.Close(); } fs?.Dispose(); } } } }
额外注意事项
- 优先通过Nuget安装iTextSharp官方稳定版本,避免使用来历不明的第三方编译版本
- 导出前确认目标路径没有被其他PDF阅读器、编辑器占用,避免文件流创建失败
- 如果不需要页面旋转,可直接删除
doc.SetPageSize(PageSize.A4.Rotate());代码行
内容的提问来源于stack exchange,提问作者Monk
相关产品推荐
相关产品推荐

