【发布时间】: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