More Custom Formatting for PDF Fields
The built-in number formats in Acrobat contain a custom format script and a custom keystroke script that you can’t see but work behind the scenes.
In my last article I outlined how to make non-printable text appear in a form field before a value is entered, by using a custom format script, and also maintaining the built-in date formatting.
This article’s custom formatting script can be entered as a custom format script, a custom validation script, or a custom calculation script. Calculation scripts run every time any field value changes. Validation scripts run only when the value of the field in which they are embedded changes. I’m going to stick with the custom format script so I can show you how to maintain number formatting of the field, and leave the calculation script open for a math calculation of the field.
The built-in number formats in Acrobat contain a custom format script and a custom keystroke script that you can’t see but work behind the scenes. The easiest way to obtain these scripts is to create a PDF with only one form field, format the field manually in the format tab of the field properties, then browse the internal PDF structure for the scripts. This method is explained in detail with screenshots in Using JavasScript to Add Javascript to a PDF Part 2.
Example
Suppose you have a field that is formatted as a number with a comma seperators and two decimal places. The field is calculated based on values of other fields (I’ll ignore the calculation. It doesn’t matter for this exercise.)
The scripts to enter to obtain the same result are:
//Custom Format Script:
AFNumber_Format(2,0,0,0,"",true);
//Custom Keystroke Script:
AFNumber_Keystroke(2,0,0,0,"",true);
You can test this by selecting Custom from the Format tab dropdown and entering the above scripts. After you save the keystroke script the formatting tab should revert to the image above. Now suppose you want the field’s appearance to change conditionally based on its value as follows:
No value: Fill color is transparent. Text color is black.
Value less than zero: Fill color is red. Text color is white.
Value less than or equal to 10: Fill color is yellow. Text color is black.
Value greater than 10: Fill color is green. Text color is black.
Enter the custom format script from above and add to it for the following result:
AFNumber_Format(2,0,0,0,"",true);
if(!event.value)
{
event.target.fillColor=color.transparent;
event.target.textColor=color.black;
}
else if (event.value<0)
{
event.target.fillColor=color.red;
event.target.textColor=color.white;
}
else if (event.value<=10)
{
event.target.fillColor=color.yellow;
event.target.textColor=color.black;
}
else
{
event.target.fillColor=color.green;
event.target.textColor=color.black;
}
Enter the custom keystroke script from above:
AFNumber_Keystroke(2,0,0,0,"",true);
The field does not yet contain a calculation, so you can test it by entering numbers into the field.