在.Net Core 3.1类库中调用iText7 PdfAcroForm.GetAcroForm()时出现空引用异常

问题描述 投票:0回答:2

我正在努力将应用程序转换为 .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
2个回答
8
投票

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

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

所以我花了四个小时尝试解决他们代码中的问题,但他们显然找到了一些方法来解决并推动该方法,即使在空引用失败的情况下也是如此。

我的转换为 PDF 功能现在工作得很好。


4
投票

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

更新:2023 年 8 月 9 日 - 此错误仍然存在于 iText 库中。此问题不会在生产应用程序中导致运行时异常,并且“仅”在附加调试器时抛出。如果 Visual Studio 在测试生成 PDF 的应用程序时抛出异常,您可以通过按 F5 绕过它,您的应用程序将继续执行,不会出现问题。

© www.soinside.com 2019 - 2024. All rights reserved.