This article was first published in December 2020 and was updated in November 2024.
JavaScript isn’t necessarily what most people think of when they hear iOS, but there are a few places where it can come in handy, especially when working with form fields in a PDF. For example, you can hide, create, and change PDF form fields. You can even populate form fields, depending on the value of other form elements.
The official Acrobat JavaScript documentation is more than 700 pages in length, and it offers nearly endless possibilities for interacting with your PDF. In this blog post, I’ll show you some nice things you can do with it in iOS!
Basics
There are a few ways to add JavaScript to your document. One way is with document JavaScripts, and another is with JavaScript actions attached to form elements. The former can be used when you’re likely to reuse functions a few times in your document, but it can also be used for running scripts when a document is open (for example, when showing an alert explaining the interactivity of a PDF). Meanwhile, the latter are just used on the form elements they’re added to.
To learn how to add JavaScript to a document and/or form elements, we have a great guide about utilizing JavaScript in our iOS PDF viewer. A lot of the basics were already covered in our blog post about programming a calculator in a PDF, so be sure to check that out as well!
Understanding JavaScript in PDF documents
JavaScript is a powerful tool for creating interactive and dynamic PDF documents. By embedding JavaScript code within a PDF file, developers can add custom functionality, validate user input, and perform calculations, all of which significantly enhance the user experience. Whether you’re looking to create a simple example of a form field that responds to user interactions, or a complex document with multiple interactive elements, JavaScript provides the flexibility and control needed to achieve your goals.
Use cases
As mentioned above, there is a variety of things you can accomplish with JavaScript in your PDFs, so let’s look at a few examples.
Populating PDF form fields
To start, we’ll see how to set the value of a text field. We’ll assume the name of the text field is Text Field:
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.
Now let’s go a bit further and set the value of the text field depending on if a checkbox is checked or not:
if (this.getField('Check Box').isBoxChecked(0)) { this.getField('Text Field').value = 'Checked'; } else { this.getField('Text Field').value = 'Not Checked'; }
Here, we’re using isBoxChecked(0)
to see whether or not the checkbox is checked, and we’re setting the value of the text field accordingly. The zero parameter determines which checkbox or radio button from the group should be used. In this case, we use “0” since we only have one button. This is better for radio buttons, since at least two are required per group. Let’s see how our first example behaves.
Changing the appearance of PDF form fields
Now that we know how to populate a form field, let’s see how to change its appearance:
var textField = this.getField('Text Field'); textField.textColor = color.white; textField.fillColor = color.red; textField.textSize = 18; textField.fontStyle = 'italic';
Since we’re using the text field quite a bit in the code above, we can save it in a variable just like in any other language. Then we change a few things to make the text field more prominent. Now, let’s see how this will look.
Hiding PDF form fields
Now that populating and changing form fields works, why not try to hide or even delete them via JavaScript?
if (this.getField('Check Box').isBoxChecked(0)) { this.getField('Button').display = display.hidden; } else { this.getField('Button').display = display.visible; }
Checkboxes are the easiest way to hide other fields. We simply use a checkbox again, and depending on its state, we either hide or show a button. This can be done via the display
property. In practice, it’ll look like what’s shown below.
Hidden form fields can easily be shown again by setting the display
property to display.visible
, while removing a form field is a permanent change that can’t easily be reverted via the API. Removing a form field can be achieved in the following way:
if (event.willCommit) { this.removeField(event.value); }
Removing PDF form fields
The script above is a custom keystroke script attached to a text field. We only execute the action if event.willCommit
returns true
. This only happens if the text field is currently selected and we tap outside the text field, select another form field, or tap the Enter key — the last one being the most practical way to confirm we want to execute the script. We then remove the form field with the name that matches event.value
. This is the value of the form field after the event has been executed.
So, for example, if you write “Text Field1” into your text field and press Enter, the field with the name “Text Field1” will be removed from the document. You need to know the exact field names of the form fields for this to work, but it can be a nice and easy way to remove unnecessary form fields from your document on the fly.
Let’s see this in action.
Creating interactive PDF documents with JavaScript
JavaScript can transform static PDF documents into interactive experiences by adding form fields, buttons, and other dynamic elements. These can collect user input, perform calculations, and trigger actions within the document, making the PDF more engaging and functional. Below is a list of some common applications.
1. Adding interactivity
-
Form fields and buttons — Add elements that allow users to input data directly within the PDF.
-
Calculations and dynamic content — Use JavaScript to perform calculations based on user input and dynamically update fields in real time.
Example:
const quantity = this.getField('Quantity').value; const price = this.getField('Price').value; this.getField('Total').value = quantity * price;
-
This code retrieves values from the Quantity and Price fields, multiplies them, and sets the result in the Total field.
2. Validating user input
JavaScript helps ensure data integrity by validating user input against predefined rules, which is particularly useful in form-heavy PDFs.
Example:
const email = this.getField('Email').value; const emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/; if (!emailPattern.test(email)) { app.alert('Please enter a valid email address.'); }
-
This script checks if the Email field matches the expected pattern. If not, an alert prompts the user to enter a valid email address.
3. Performing calculations
JavaScript can automate calculations within PDF forms, which is valuable for documents requiring mathematical operations (e.g. invoices, purchase orders).
Example:
const item1 = this.getField('Item1').value; const item2 = this.getField('Item2').value; const total = parseFloat(item1) + parseFloat(item2); this.getField('Total').value = total.toFixed(2);
-
This code adds the values from the Item1 and Item2 fields, then updates the Total field with a result rounded to two decimal places.
Best practices for PDF documents
To create effective and user-friendly PDFs, consider these best practices:
-
Clarity and structure
-
Use clear, concise language for easy comprehension.
-
Organize content with headings, subheadings, and lists for improved readability.
-
-
Interactive elements
-
Incorporate form fields and JavaScript-based actions to enhance interactivity.
-
Use JavaScript for validation (e.g. email format checks) and calculations within forms.
-
-
Security and accessibility
-
Security — Protect sensitive information using encryption and password protection.
-
Accessibility — Include alt text for images and closed captions for multimedia, enabling accessibility for all users.
-
-
Compatibility with PDF readers
-
Ensure compatibility with popular PDF readers, like Adobe Reader, which supports JavaScript and interactive elements.
-
-
Document design
-
Highlight annotations — Use highlights to emphasize important information.
-
Images and graphics — Integrate visuals to illustrate complex information and maintain engagement.
-
JavaScript actions — Add custom JavaScript actions for dynamic, user-triggered responses.
-
-
Ease of use
-
Provide simple examples and tutorials to guide users through the interactive elements in your PDFs.
-
Consider using word-processing software like Microsoft Word for initial content creation, leveraging its built-in PDF export features.
-
Conclusion
In this post, we populated PDF form fields, changed their appearance, hid them, and even removed them entirely from a PDF with just a few simple scripts. But although we went over some interesting examples of what can be done with JavaScript in a PDF on iOS, we’ve only just begun to scratch the surface.
To learn a bit more about the full capabilities of our iOS PDF library check out some of our most popular guides:
-
PDF viewer — Rendering engine that’s fast, precise, and feature-rich.
-
15+ out-of-the-box annotations — Mark up, draw on, add comments to documents.
-
PDF editing — Merge, split, rotate, and crop documents.
-
PDF forms — Create, fill, and capture PDF form data.
-
Digital signatures — Validate the authenticity and integrity of a PDF.
At Nutrient, we offer a commercial, feature-rich, and completely customizable iOS PDF SDK that’s easy to integrate and comes with well-documented APIs. To get started, try it for free.
FAQ
Here are a few frequently asked questions about using JavaScript in PDF form fields.
What can I do with JavaScript in PDF form fields?
You can populate, change the appearance, hide, or remove form fields based on user actions.How do I add JavaScript to a PDF document?
You can add it using document JavaScripts for global functions or JavaScript actions attached to form elements.Can I change the appearance of a PDF form field using JavaScript?
Yes, you can adjust text color, fill color, text size, and font style.How can I hide or show a PDF form field using JavaScript?
Use the `display` property to toggle visibility based on conditions.Can JavaScript be used in PDFs on iOS devices?
Yes, it works similarly to other platforms, enabling interactive form elements.Christoph loves experimenting, learning new things, and working with our customers. He enjoys working out with weights; playing volleyball, football, and tennis; and playing video games.