Using JavaScript in PDF form fields
Table of contents
PDF form scripts can copy values, show or hide fields, validate input, and calculate totals. They run inside a compatible PDF reader, using APIs such as this.getField() and event.value. This tutorial explains where to attach each script and how to test the form in Nutrient on iOS. Reader support varies, so verify the saved PDF in your target application.
A PDF form can update a total or reveal a field when someone checks a box. JavaScript stored in the PDF supplies that behavior. These examples show how to add it and which events should run each script.
Basics
PDF JavaScript uses a reader’s document and form APIs. It isn’t JavaScript for a webpage: this.getField() refers to a PDF field, and there’s no browser document object model (DOM). Pasting these snippets into a browser console won’t update an embedded PDF viewer.
Use a copy of a PDF with named AcroForm fields. Each example below requires the exact field names shown in its code. In Adobe Acrobat’s Prepare Form tool, open a field’s properties to set its name and attach a script:
- Actions — Choose a trigger and Run a JavaScript for button and checkbox actions.
- Calculate — Add a custom calculation script to the result field.
- Validate — Add a custom validation script to the field being checked.
- Format — Choose a custom format to add the keystroke script used in the removal example.
Document-level scripts can define functions reused by those actions or run when the PDF opens. See Nutrient’s PDF JavaScript guide for authoring examples and supported APIs, and the calculator tutorial for a worked calculation form.
Understanding JavaScript in PDF documents
Nutrient iOS SDK supports a subset of the Acrobat JavaScript API reference(opens in a new tab). A script that works in Acrobat may use a feature another reader doesn’t support. Save the PDF after attaching the scripts, open it in your Nutrient application with PDF JavaScript enabled, and test each action. See Nutrient’s form validation guide for supported formatting and calculation functions.
Use cases
The examples below cover values, appearance, visibility, removal, validation, and calculations. Use the specified event for each example rather than adding every script as a document-open action.
Populating PDF form fields
Create a text field named Text Field. Attach this script to a button’s Mouse Up action to set its value when the button is activated:
this.getField('Text Field').value = 'This is a text field.';We’re using this.getField() to determine on which text field we want to set the value, and since it’s a text field, the value is a simple string.
For a checkbox named Check Box, attach this script to its Mouse Up action to update Text Field after a click:
if (this.getField('Check Box').isBoxChecked(0)) { this.getField('Text Field').value = 'Checked';} else { this.getField('Text Field').value = 'Not Checked';}isBoxChecked(0) checks the first widget belonging to the field. This example assumes a single checkbox widget. Test both checked and unchecked states, as shown below.
Changing the appearance of PDF form fields
Attach this script to a button action to change the colors of Text Field:
var textField = this.getField('Text Field');
textField.textColor = color.white;textField.fillColor = color.red;The field displays white text on a red background. For font changes in Acrobat, use the documented textFont property; fontStyle isn’t a Field property. Check your target reader’s support before adding font changes.
Hiding PDF form fields
To hide Button when Check Box is selected, use this script as the checkbox’s Mouse Up action:
if (this.getField('Check Box').isBoxChecked(0)) { this.getField('Button').display = display.hidden;} else { this.getField('Button').display = display.visible;}The display property controls visibility. Test that clearing the checkbox makes the button visible again:
Removing PDF form fields
Hiding a field keeps it in the document. Removing it deletes the field, so use a test copy. Create a separate text field named Field to remove, and attach this custom keystroke script to it:
if (event.willCommit) { this.removeField(event.value);}The event.willCommit check waits until the reader attempts to commit the text, such as when the user presses Enter or leaves the field. event.value contains the proposed field value, which this script treats as the name of the field to remove.
For example, enter Text Field1 to remove a separate field with that exact name. Don’t enter the name of the field running this script.
Let’s see this in action.
Calculating a line total
Create numeric input fields named Quantity and Price. Add this custom calculation script to a field named Total. The example accepts nonnegative decimal input with a period as the decimal separator. A blank or invalid input leaves the total empty:
var quantityText = String(this.getField('Quantity').value).trim();var priceText = String(this.getField('Price').value).trim();var decimalPattern = /^\d+(\.\d+)?$/;var total = Number(quantityText) * Number(priceText);
event.value = decimalPattern.test(quantityText) && decimalPattern.test(priceText) && isFinite(total) ? total.toFixed(2) : '';In a calculation event, set event.value to update the result field. Add validation to the input fields if your form must reject invalid values rather than leave the result blank.
Validating an email field
Add this custom validation script to Email. It checks the proposed value in event.value and sets event.rc to reject it when the check fails:
var email = String(event.value).trim();var emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;event.rc = email === '' || emailPattern.test(email);if (!event.rc) { app.alert('Enter an email address such as name@example.com.');}This is a basic format check for an optional field. It accepts blank values and doesn’t verify that the address exists. Remove the empty-string condition if your workflow requires a value. An alert alone doesn’t reject input; event.rc = false does.
Adding two amounts
For a sum instead of a product, create Item1 and Item2 fields and use this alternative calculation script on Total. It accepts signed decimals and leaves the result blank if either input is missing or malformed:
var item1 = String(this.getField('Item1').value).trim();var item2 = String(this.getField('Item2').value).trim();var decimalPattern = /^-?\d+(\.\d+)?$/;var total = Number(item1) + Number(item2);
event.value = decimalPattern.test(item1) && decimalPattern.test(item2) && isFinite(total) ? total.toFixed(2) : '';These calculation examples use JavaScript numbers and format the result to two decimal places. Adapt input validation and rounding to your form; comma decimal separators and currency symbols aren’t accepted here.
Test the saved PDF in your target reader
After saving the scripts, check these cases in Acrobat and your Nutrient iOS application:
- Toggle the checkbox both ways and confirm that values and visibility update.
- Enter blank, malformed, and valid values in calculation and validation fields.
- Save and reopen the PDF to check the retained field values and scripts.
- Test with PDF JavaScript disabled to understand which behavior stops working. Validate submitted data in your application too.
Build interactive forms with Nutrient
Use Nutrient iOS SDK’s form tools to display and fill forms in your application. Check PDF JavaScript support for the methods your scripts need, and then try Nutrient with a sample form. Verify the form’s calculations, validation messages, and saved values before using it in your workflow.
FAQ
You can populate, restyle, hide, or remove form fields based on user actions.
Use document-level scripts for shared functions, or attach scripts to field actions, calculations, and validation events. In Acrobat, use Prepare Form to configure those field scripts. Save the PDF and test it in the reader your users will use.
You can change properties such as text and fill colors. Font APIs and other appearance settings depend on the reader’s supported subset of Acrobat JavaScript.
Use the display property to toggle visibility based on conditions.
It depends on the PDF reader. Nutrient iOS SDK supports a subset of PDF JavaScript for form actions, calculations, and validation. Test the required methods and events; don’t assume every iOS PDF viewer executes the scripts.