Search code examples
pdfitextacrofields

Can I find bordercolor of a field in PDF using iText?


Is there anyway of finding the bordercolor of a specific field in my PDF using iText latest version? I could get AcroField.Item, but I dont see an option to get bordercolor from there.


Solution

  • Please take a look at this PDF: text_fields.pdf. This PDF was created using the TextFields example. The following code snippet was used to set the border of the field with name text_2:

    text.setBorderStyle(PdfBorderDictionary.STYLE_SOLID);
    text.setBorderColor(BaseColor.BLUE);
    text.setBorderWidth(2);
    

    Now when we look inside the PDF using iText RUPS, and we take a look at the field dictionary / widget annotation for this field, we see the following structure:

    Internal structure of a form field

    We see a /BS dictionary that defines a solid border style (the value for the /S key is /S) and a border width (/W) with value 2.

    We also see that the border color (/BC) entry of the /MK entry is an array with three values: [ 0 0 1 ]. This means that the border color is an RGB color where the value for Red is 0, the value for Green is 0, and the value for Blue is 1. This is consistent with us setting the color to BaseColor.BLUE when we created the file.

    You say that you have the AcroField.Item object for a field. Now you need to get the merged field / widget annotation dictionary and follow the path shown by iText RUPS:

    AcroFields.Item item = acroFields.getFieldItem(fldName); 
    PdfDictionary merged = item.getMerged(0); 
    PdfDictionary mk = merged.getAsDict(PdfName.MK);
    PdfArray bc = mk.getAsArray(PdfName.BC);
    

    The values stored in the array bc will inform you about the background color. If the array has only one value, you have a gray color, if there are three, you have an RGB color, if there are four, you have a CMYK color.

    Warning: some values may not be present (e.g. there may be no /BC entry). In that case you can get NullPointerExceptions.