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

使用iText生成SQL数据库PDF报表遇NotSupportedException报错求助

解决iText7生成PDF时的BouncyCastle依赖错误

错误原因

你遇到的NotSupportedException已经明确指出问题:iText7的核心组件需要依赖BouncyCastle加密库的适配包才能正常初始化PDF写入器,你的项目中缺少了这个必要依赖,导致PdfWriter实例化失败,进而触发了外层的PdfException。

解决步骤

1. 安装必要的NuGet包

打开项目的NuGet包管理器,搜索并安装以下两个包:

  • iText7.Core:iText7的核心PDF处理库(如果尚未安装)
  • iText7.BouncyCastle:iText7与BouncyCastle加密库的适配包

也可以通过Package Manager Console执行命令安装:

Install-Package iText7.Core
Install-Package iText7.BouncyCastle

或者使用.NET CLI命令:

dotnet add package iText7.Core
dotnet add package iText7.BouncyCastle

2. 优化代码避免空值异常(可选但推荐)

原代码中直接调用cell.Value.ToString(),如果单元格值为null会触发NullReferenceException,建议添加空值判断:

private void generateReportsToPDFToolStripMenuItem_Click(object sender, EventArgs e)
{
    using (PdfDocument pdfDoc = new PdfDocument(new PdfWriter("output.pdf")))
    {
        using (Document doc = new Document(pdfDoc))
        {
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                if (row.IsNewRow) continue; // 跳过DataGridView的空行
                foreach (DataGridViewCell cell in row.Cells)
                {
                    string cellContent = cell.Value?.ToString() ?? string.Empty;
                    doc.Add(new Paragraph(cellContent));
                }
                doc.Add(new AreaBreak());
            }
        }
    }

    MessageBox.Show("Data exported to PDF successfully!");
}

完成上述操作后,重新运行代码即可正常生成PDF报表。

内容的提问来源于stack exchange,提问作者SYNYSTERG

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 04:03:18