【问题标题】:Null Reference Exception when calling iText7 PdfAcroForm.GetAcroForm() in .Net Core 3.1 class library在 .Net Core 3.1 类库中调用 iText7 PdfAcroForm.GetAcroForm() 时出现空引用异常
【发布时间】:2020-10-01 00:25:24
【问题描述】:

我正在将应用程序转换为 .Net Core 3.1,在我的类库中,我正在从现有模板生成 PDF 表单,并用数据填充该表单。在 IText7 的前身 ITextSharp 中,PdfAcroForm 静态方法“.GetAcroForm()”运行良好,但在当前版本的 iText7 (7.1.12) 中会引发空引用异常。我已尽我所能遵循文档,但我不确定如何继续。任何建议将不胜感激。

注意:模板路径存在,新建文档显示已正确填写,无法“新建”一个PdfAcroForm,需要使用静态的.GetAcroForm()方法。

空检查不能解决这个问题,因为对象永远不应该为空。文档表明,如果参数“createNotExist”设置为 true,.GetAcroForm() 方法将创建一个新表单,我在这里做了。

我已经研究并在 iText GitHub 上找到了一个问题,表明该问题大约在一年前已“修复”:https://github.com/itext/itext7/pull/44#issue-351612749

以下是准备表格的方法:

public string DocumentGenerator(string templatePath, FormFieldSet[] formFieldSet, bool useSpecailOutputPath)
        {
            if(!File.Exists(templatePath))
            {
                throw new Exception("The template file provided does not exist: MC-071(iText)"); 
            }

            string newFile = useSpecailOutputPath ? 
                m_SpecialOutputPath : 
                Path.GetTempPath() + Guid.NewGuid().ToString() + ".pdf";
            try
            {

                PdfDocument newDocument = new PdfDocument(new PdfReader(templatePath), new PdfWriter(newFile));
                PdfAcroForm acroForm = PdfAcroForm.GetAcroForm(newDocument, true); // <=== Exception Thrown Here

                foreach (FormFieldSet fs in formFieldSet)
                {
                    acroForm.GetField(fs.FieldName).SetValue(fs.FillValue);
                }

                // Sets form flattening
                acroForm.FlattenFields();

                // Closes and writes the form
                newDocument.Close();

                return newFile;
            }
            catch { return string.Empty; }; 
        }

任何建议将不胜感激

【问题讨论】:

    标签: c# pdf .net-core itext itext7


    【解决方案1】:

    只是对任何寻找此问题的人的更新。这是一个已知问题,已在当前开发分支中修复。您可以安全地绕过 Visual Studio 中的异常,直到它被纠正。这对功能没有负面影响,并且是原始 iText7 源中错误返回的结果。

    【讨论】:

    • 你拯救了我的一天。从 7.1.15 回滚到 7.1.7,一切又开始工作了。谢谢!
    【解决方案2】:

    我也遇到了同样的问题,一路深挖到iText7的内部对象和方法,终于“解决”了我的问题。

    显然 iText 有一些内部错误/异常,它们只是一种“跳过”和“推过去”,因为我偶然意识到我在 Visual Studios 中禁用了“仅启用我的代码”,所以我的系统是尝试调试 iText7 的代码以及我的代码。当我在 Visual Studio 设置中重新启用它时(工具 > 选项 > 调试 > 常规 > 启用我的代码复选框),问题就神奇地消失了。

    所以我花了四个小时试图解决他们代码中的问题,但他们显然找到了一些解决方法,并且即使在空引用失败的情况下也可以通过该方法。

    我的转换为 PDF 功能现在可以正常工作了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-18
      • 2020-12-07
      • 2012-08-19
      • 1970-01-01
      • 2021-10-02
      相关资源
      最近更新 更多