How do I get a TextField from AcroFields using iTe

2019-08-09 10:23发布

问题:

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;