How do I get a TextField from AcroFields using iText/Sharp?

风格不统一 提交于 2020-01-06 02:30:10

问题


I am using iTextSharp to loop through the fields in the AcroFields collection so I can set a various properties on an annotation. I have worked out how to pull most of the properties for each of the annotation fields, but would like to be able to cast the individual annotation to the correct field object (i.e., TextField, PushButtonField, RadioCheckField, etc.).

Short of creating a new TextField, reading and then setting all of the settings/properties associated with it, is there a concise way of getting to:

int index = 0;
AcroFields acroFields = stamper.AcroFields;
TextField tf = acroFields.GetTextField(acroField.Key.ToString(), index);

I am using a very old version of iTextSharp (4.0.6.0). I am unable to upgrade to the latest version as there are breaking changes between 4 and 5.

Additional Information: My PDF files have multiple repeated fields (e.g., two pages have the customer name), so setting a property by using just a key name can have unintended side effects. One field might be left justified while another is centered.


回答1:


Unfortunately no, TextField, PushButtonField and others are all part of iText's abstraction for document creation and there's no built-in way to reverse an AcroFields.Item object back to one of these.




回答2:


You can use the GetFieldType() while iterating the AcroFields. But not all properties are available to change. Let me know if there are any questions.

AcroFields acroFields = reader.AcroFields;
foreach (KeyValuePair<String, AcroFields.Item> field in acroFields.Fields)
{
    // Check to see if it is the type we want.
    Boolean isTextField = (AcroFields.FIELD_TYPE_TEXT == acroFields.GetFieldType(field.Key));

    if (isTextField)
    {
        // Change the text.
        acroFields.SetField(field.Key, "new  string");
    }
}

The constant int field types available are:

public const int FIELD_TYPE_CHECKBOX = 2;
public const int FIELD_TYPE_COMBO = 6;
public const int FIELD_TYPE_LIST = 5;
public const int FIELD_TYPE_NONE = 0;
public const int FIELD_TYPE_PUSHBUTTON = 1;
public const int FIELD_TYPE_RADIOBUTTON = 3;
public const int FIELD_TYPE_SIGNATURE = 7;
public const int FIELD_TYPE_TEXT = 4;


来源:https://stackoverflow.com/questions/33113255/how-do-i-get-a-textfield-from-acrofields-using-itext-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!