将 JSON 转换为 XML 以传递给 FillXfaForm

Convert JSON to XML to pass to FillXfaForm

我想将我的 JSON 对象转换为 XML 以便在 FillXfaForm 中使用以使用 iText 填充我的 pdf 表单。

public void PopulatePDF(String src, string jsonString, String dest) 
{
    PdfDocument pdf = new PdfDocument(new PdfReader(src), new PdfWriter(dest));
    PdfAcroForm form = PdfAcroForm.GetAcroForm(pdf, true);
     XfaForm xfa = form.GetXfaForm();
    XmlDocument xmlDoc = (XmlDocument)JsonConvert.DeserializeXmlNode(jsonString, "root");
    String xmlString = xmlDoc.OuterXml;
    xfa.FillXfaForm(XmlReader.Create(new StringReader(xmlString)));
    xfa.Write(pdf);
    pdf.Close();
}

它给我一个错误 "An exception of type 'System.NullReferenceException' occurred in itext.forms.dll but was not handled in user code"。它在行 xfa.FillXfaForm(XmlReader.Create(new StringReader(xmlString))) 上给出错误。

JSON字符串如下:

{ "id": 278,  "clientID": 0,  "Number": null  "Amount": 0.0 }

结果XML字符串如下:

<root><id>278</id><clientID>0</clientID><Number /><Amount>0</Amount></root>

这是一个 link 表单:(它有一个名为 id 的字段) https://www.dropbox.com/s/3dkb4ry5gu8m74e/TestForm.pdf?dl=0

您的 PDF 文档中的表单不是 XFA 表单。它是一个普通的 AcroForm。 XfaForm#FillXfaForm 仅适用于 XFA 表单。

为了在 AcroForm 中填写普通字段,您必须知道其字段的名称。例如,在您附加的文档中,有一个字段名称为 id

此代码用 278 值填充 id 字段:

PdfAcroForm form = PdfAcroForm.GetAcroForm(pdf, true);
form.GetField("id").SetValue("278");

当然,您将不得不自己处理解析 XML/JSON。