当字段名称有两个英镑符号时,iTextSharp会抛出XML错误

时间:2013-05-10 07:14:26

标签: c# itextsharp

我在尝试设置包含两个磅符号的字段名称的值时遇到iText的奇怪错误。问题是我无法控制原始表单字段名称。

任何人都碰巧知道怎么解决这个问题?我已经尝试重命名字段,但它没有进行字段重命名。

这会出错

form.SetField("form1[0].#subform[8].#area[12].Line4_FirstName3[4]", "Bill");

但是如果字段名称相似但只有一个符号,那么

form.SetField("form1[0].#subform[8].Line4_FirstName3[4]", "Bill");

抛出了类型'System.Web.HttpUnhandledException'的异常。 ---> System.Xml.XmlException:'#'字符,十六进制值0x23,不能包含在名称中。    在System.Xml.XmlDocument.CheckName(String name)    在System.Xml.XmlElement..ctor(XmlName name,Boolean empty,XmlDocument doc)    at System.Xml.XmlDocument.CreateElement(String prefix,String localName,String namespaceURI)    在System.Xml.XmlDocument.CreateElement(String name)    在iTextSharp.text.pdf.XfaForm.Xml2SomDatasets.InsertNode(XmlNode n,String shortName)    at iTextSharp.text.pdf.AcroFields.SetField(String name,String value,String display)    at iTextSharp.text.pdf.AcroFields.SetField(String name,String value)

这是来自iText 4.1.2.0。

当我尝试重命名字段以删除“#area [12]”周围的第二个英镑符号类型测试时,它不会重命名。

PdfReader reader2 = new PdfReader(pdfTemplate);
using (FileStream fs = new FileStream(TemporaryFile, FileMode.Create)) {
PdfStamper stamper = new PdfStamper(reader2, fs);
AcroFields pdfForm = stamper.AcroFields;
//Dim de As New DictionaryEntry
foreach (DictionaryEntry de in pdfForm.Fields) {
    pdfForm.RenameField(de.Key.ToString(), Guid.NewGuid().ToString("N"));
}

stamper.Close();

}

2 个答案:

答案 0 :(得分:1)

我知道这个问题已经过时了。但也许我的回答会帮助别人。 在问题中,ReplaceField函数不起作用,因为它只能更改名称的最后部分(全部在字段名称中的最后一个doth之后)。 对于这种情况,以下代码将起作用:

Dictionary<string, string> changedFields = new Dictionary<string, string>();
foreach (string fieldName in formFields.Fields.Keys)
{
    if (fieldName.Contains("#"))
    {
        if (fieldName.Contains("."))
        {
            string[] names = fieldName.Split(new string[] { "." }, StringSplitOptions.RemoveEmptyEntries);
            if (names.Last().Contains("#"))
            {
                changedFields.Add(fieldName, String.Format("{0}.{1}", String.Join(".", names, 0, names.Length - 1), names.Last().Replace("#", "")));
            }
        }
        else
        {
            changedFields.Add(fieldName, fieldName.Replace("#", ""));
        }
    }
}
foreach (string oldName in changedFields.Keys)
{
    stamper.AcroFields.RenameField(oldName, changedFields[oldName]);
}

答案 1 :(得分:0)

我遇到了同样的问题,我一直在努力,为字段所属的MasterPage设置一个名称(在LiveCycle中)。 这样我就不再拥有第二个&#34;#&#34;在字段名称上,所以我更改名称问题不再存在。

在您的情况下,请尝试获取该字段的全名。

PdfReader reader2 = new PdfReader(pdfTemplate);
using (FileStream fs = new FileStream(TemporaryFile, FileMode.Create)) 
{
   PdfStamper stamper = new PdfStamper(reader2, fs);
   AcroFields pdfForm = stamper.AcroFields;

   //Dim de As New DictionaryEntry
   foreach (DictionaryEntry de in pdfForm.Fields) {
       //try this...
       var fullname= fields.GetTranslatedFieldName(de.Key.ToString());
       pdfForm.RenameField(fullname, Guid.NewGuid().ToString("N"));
   }

   stamper.Close();