How to change the text color of an AcroForm field?

Tags: colored textfontsfont colorformsfield propertiesiText 7

I have a PDF with named fields I created with Adobe LifeCycle. I am able to fill the fields using iTextSharp but when I change the text color for a field it does not change. I really don't know why this is so. Here is my code:

form.SetField("name", "Michael Okpara");
form.SetField("session", "2014/2015");
form.SetField("term", "1st Term");
form.SetFieldProperty("name", "textcolor", BaseColor.RED, null);
form.RegenerateField("name");
Posted on StackOverflow on Nov 21, 2014 by Okolie Solomon

If your form is created using Adobe LifeCycle, then there are two options:

  • You have a pure XFA form. XFA stands for the XML Forms Architecture and your PDF is nothing more than a container of an XML stream. There is hardly any PDF syntax in the document and there are no AcroForm fields. I don't think this is the case, because you are still able to fill out the fields (which wouldn't work if you had a pure XFA form).
  • You have a hybrid form. In this case, the form is described twice inside the PDF file: once using an XML stream (XFA) and once using PDF syntax (AcroForm). iText will fill out the fields in both descriptions, but the XFA description gets preference when rendering the document. Changing the color of a field (or other properties) would require changing the XML and iText(Sharp) can not do that.

If I may make an educated guess, I would say that you have a hybrid form and that you are only changing the text color of the AcroForm field without changing the text color in the XFA field (which is really hard to achieve).

Please try adding this line in iText 7:

form.removeXfaForm();

This will remove the XFA stream, resulting in a form that only keeps the AcroForm description.

I have written a small example named RemoveXFA using the form you shared to demonstrate this:

PdfDocument pdfDoc = new PdfDocument(new PdfReader(src), new PdfWriter(dest));
PdfAcroForm form = PdfAcroForm.getAcroForm(pdfDoc, true);
form.removeXfaForm();
Map<String, PdfFormField> fields = form.getFormFields();
for (Map.Entry<String, PdfFormField> name : fields.entrySet()) {
    if (name.getKey().indexOf("Total") > 0) {
        name.getValue().getWidgets().get(0).setColor(Color.RED);
    }
    name.getValue().setValue("X");
}
pdfDoc.close();

It won’t take much time to port this code to C#. As you can see, I remove the XFA stream and I look over all the remaining PdfFormFields. I change the textcolor of all the fields with the word "Total" in their name, and I fill out every field with an "X".

Resulting PDF
Resulting PDF

All the fields show the letter "X", but the fields in the TOTAL column are written in red.

Click this link if you want to see how to answer this question in iText 5.