69
ted padova
ted@west.net
31
writing javascripts
Summing Data with JavaScript
You may want to sum data in a column or row and add a sales tax to
the sum, a shipping charge, apply a discount, or some other math
function as part of the field calculation.
If you use the built-in formula described in Tip #52 you can't add a
second calculation. If you use a Simplified Field Notation script, you
need to name each field separately in the formula —something
that could be very tedious with long columns or rows.
In order to extend the formula to calculate a total and apply the
total to another calculation, your best option is to use JavaScript.
Open the Calculate tab on a field to hold the data calculation
and click Edit for Custom Calculation Script.
In the JavaScript Editor, type the following code:
1. var f = this.getField("amount");
2. var a = f.getArray();
3. var sum = 0;
4. for (i =0; i < a.length; i++)
5. sum += a[i].value;
6. event.value = sum + (sum * .08);
Line 1 sets up an array with a field having a parent name of
amount. The form contains several fields named amount.0,
amount.1, amount.2, etc. The loop is executed and picks up
the value for each field and adds it to a variable called sum.
The last line adds the sum to the sum * a sales tax of 8%.
55
56
Calculating a Sales Tax
Sales tax calculations can be handled easily
with built-in formulas, Simplified Field
Notation, and JavaScript when you have
separate fields for a subtotal and a tax field.
Using JavaScript the following script would
be used to calculate a sales tax:
Open the Calculate tab on a field to hold the data calculation
and click Edit for Custom Calculation Script.
Type the following script in the JavaScript Editor:
1. var f = this.getField("subtotal");
2. event.value = Math.round(f.value * 7.25) / 100;
The above script assigns a variable to a field called subTotal
where the sum of data in a row or column has been calcu-
lated. The second line of code calculates a sales tax of 7.25%.
Calculating a Shipping Charge
A shipping charge might be calculated based
on the total cost of items purchased. The fol-
lowing formula calculates a shipping charge
of 12% of the total purchase amount.
Open the Calculate tab on a field to hold
the data calculation and click Edit for
Custom Calculation Script.
Type the following script in the JavaScript Editor:
1. var g = this.getField("subtotal");
2. event.value = Math.max(2, Math.floor(g.value /
12));
The above script assigns a variable to a field called subTotal
where the sum of data in a row or column is calculated. The
second line of code calculates a shipping charge of 12%.
71
ted padova
ted@west.net
32
writing javascripts
Importing Images
You may want to add a photo or logo to a form and enable the user
to import an image on a button action.
Here's how to do it:
Create a button field and choose Icon only in the Options tab.
Click the Actions tab and add a JavaScript.
In the JavaScript Editor, type the following code:
1. event.target.buttonImportIcon();
When the user clicks the button, the Select Icon dialog opens.
Note: to make this work in Adobe Reader see Tip # 88.
Showing/Hiding Fields
Acrobat provides you an action to show and hide fields. If you
have many fields to show/hide, you need to check each item in the
Show/Hide Field dialog box. An easier way to handle the task is to
use JavaScript. Be certain to use hierarchical names before writing
the script.
Create a button field and click the Actions tab and add a
JavaScript.
In the JavaScript Editor, type the following code:
1. var f = this.getField("myField");//parent name
2. f.hidden=true;//hides all fields with the same
parent name
59
Resetting a Form
Acrobat has a built-in function for resetting a
form that was described in Tip #21. This action
works fine when you want to reset all fields or
all fields with a few exceptions on a form.
You may have different sections of a form that
you don't want to reset such as the identify-
ing information or fields that contain fixed data that you use for
calculations.
Using JavaScript the following script would be used to reset form
fields having the same parent name:
Create a button and add a JavaScript.
Type the following script in the JavaScript Editor:
1. var resetFields = this.getField("customerData");
2. this.resetForm(resetFields);
The above script resets the fields with the parent name of
customerData.
To show hidden fields use the
following script in line 2:
2. f.hidden=false;
ted’s ti
p
If you want to reset all fields on a form, use
the following script:
this.resetForm();
This kind of script might be added as a
Document Level JavaScript or Page Action
script along with an Application Response
dialog box that prompts the user to reset a
form.
If a user partially completes an order form,
the user would say no to resetting a form.
If the user starts anew, then perhaps all the
data might be reset on the form.
ted’s ti
p
61
ted padova
ted@west.net
33
writing javascripts
Setting Fields to Read Only
Fields that are set to Read Only in the General tab of the field prop-
erties dialog box, prevent data entry or changing the field data by
an end user. If the form is secured with Acrobat Security, the user
won't be able to edit the fields and change the data.
You might set fields to Read Only that have fixed price values and
calculations.
To set a field for Read Only, do the following:
Open the properties dialog box on any field.
Click the General tab.
Check the box for Read Only.
61
Deleting Fields
Deleting fields can provide another level of
security on a form. When a user submits a
form or prints a form, you can delete all fields
with no data. Something like a travel reim-
bursement form might be one example of
a form where deleting fields could be em-
ployed.
If there are no fields to add data, the form can't be changed by
another user.
Using JavaScript the following script would be used to delete a
series of fields containing no data:
Add a JavaScript to a Signature Field, a Document Action, or
a Submit button.
Type the following script in the JavaScript Editor:
1. for (var i = 0; i < 5;i++)
2. {var f = this.getField("amount."+i);
3. if (f.value == "")
4. removeField("amount."+i);
5. }
The above script deletes all fields with the parent name of
amount that have no data.
You might start with fields that are marked
for reading and writing and later, after the
user executes certain actions, you might
want to lock the fields to prevent data entry.
To handle this task add a JavaScript in the
Calculate tab where you want the field
marked as Read Only.
Here's a sample:
1. var f = this.getField("item")
2. f.readonly=true;
All fields with the same parent name are
marked as Read Only.
To disable Read Only, use the following in a
script like the above:
2. f.readonly=false;
ted’s ti
p
70
ted padova
ted@west.net
34
writing javascripts
Deleting Zeros from Calculation Fields
If you have a table and the last column or row of data is a calculated
field (something like price * qty), the default result is 0.00 until data
are added for the fields within the calculation.
You can eliminate default zeros in calculated fields with JavaScript.
Example script:
1. var f = this.getField("price.0");
2. var g = this.getField("qty.0");
3. if (g.value !=0)
4. event.value = f.value * g.value;
5. else
6. event.value ="";
In lines 1 and 2 the variables are assigned for a price and
quantity field. The result of the calculation is an amount
determined by multiplying the price * the quantity.
Line 3 checks the qty field and if it's not zero, the calculation
is performed. If the result is zero, line 6 is executed where no
value is entered in the field resulting in eliminating default
zeros.
63
64
Adding URLs to Text
Text added to a background design that con-
tains a URL or email address is automatically
recognized in Acrobat viewers 7 and above.
There's no need to add links or buttons to
navigate to a URL or open your default email
client on a button click.
However, if you ask a user to add a URL to a text field, the text field
isn't recognized as a URL link. Using JavaScript, you can create the
link by doing the following:
Create a Text field.
Open the Actions tab and choose Mouse Up for the Mouse
Trigger. This trigger will execute the action when a user clicks
on the text field.
Add a JavaScript in the Actions tab and type the following in
the JavaScript Editor:
1. if ( !/^\s*$/.test(event.target.value) )
app.launchURL(event.target.value);
The next time a user clicks in the text field, the URL opens in
the user's default Web browser.
URL Links in New Windows
By default, a URL link opens in the same
window if the browser is open and displays
a web page. Using JavaScript you can force a
URL link to open in a second window:
On a link button or any field containing a
URL link use the following script:
1. app.launchURL(“http://www.mycompany.com/file.
pdf”, true);
The true statement in the above code triggers opening the
link in a new browser window.
Note that you cannot eliminate
zeros using the built-in formulas
or Simplified Field Notation. You
must use JavaScript in order to
eliminate the zeros.
ted’s ti
p
How to C#: Basic SDK Concept of XDoc.PDF for .NET You may add PDF document protection functionality into your C# program. To be specific, you can edit PDF password and digital signature, and set PDF file
create a pdf form; cannot save pdf form in reader VB.NET PDF: Basic SDK Concept of XDoc.PDF You may add PDF document protection functionality into your VB.NET program. To be specific, you can edit PDF password and digital signature, and set PDF file
change font in pdf form; change font pdf fillable form
63
ted padova
ted@west.net
35
writing javascripts
Adding Annotations Using JavaScript
You might have a need for a user to add a comment note, add a
Stamp comment, or a Text Box comment based on a conditional
response.
Perhaps clicking a check box where the item is Other among a list of
other options is one example where you might use this feature.
If the check box is clicked, a Text Box is added to the document
page or some such other type of condition.
Note that the file must be enabled with Adobe Reader usage rights
for this to work in Adobe Reader.
Add a JavaScript to a button, a check box, or radio button
and click the Actions tab.
Type the following in the JavaScript Editor:
1. var annot = this.addAnnot(
2. {page: this.pageNum,
3. type: "FreeText",
4. rect: [396,298,629,406],
5. strokeColor: color.white,
6. fillColor: ["RGB", .85, .85, .85],
7. }
8. );
Line 3 identifies the type of annotation to be added to the
page. In this example FreeText is a Text Box comment.
Line 4 specifies the Text Box rectangle coordinates. You need
to precisely determine where the coordinates are for the
annotation you want to add using the script (See Tip #68 for
how to determine x,y coordinates).
Lines 5 and 6 set attributes for the border color and the fill
color of the Text Box.
66
Adding Fields Using
JavaScript
You can add fields using JavaScript. You
might add a field for user input based on
a user response.
This task cannot be performed in Adobe
Reader when forms are created in Acro-
bat. However, you can create dynamic forms in Adobe LiveCycle
Designer that enable Adobe Reader users to spawn fields on a page.
Example script:
1. var f = this.addField("newField", "text",
2. page = this.pageNum,[100,100,200,200])
3. f.textSize = 9;
4. f.textfont = font.Helvtica;
5. f.textColor = color.white;
6. f.fillColor = new Array("RGB", .9, .9, .9);
7. f.alignment = "left";
8. f.multiline = true;
9. f.readonly = false;
Line 2 identifies the x,y coordinates for the field rectangle.
Before writing the script, be certain to identify the exact coor-
dinates where you want the field to appear.
See Tip #67 for an easy method for identifying x,y
coordinates.
65
ted padova
ted@west.net
36
writing javascripts
Determining x,y Coordinates
Tips #65 and #66 use x,y coordinates to determine the bounding
area for annotations and fields. Before you start writing a script you
need to know the coordinates for where you want the object to ap-
pear on the page.
To easily determine the coordinates you'll use in your JavaScript
code, do the following:
Open the Comment and Markup toolbar.
Click the Rectangle Comment tool.
Draw a Rectangle comment in the area of your form where
you want to create an annotation or field.
Open the JavaScript Console (Command/CTRL + J).
Enter the following code in the Console.
1. this.getAnnots()[0].rect;
Press the NumPad Enter key on your keyboard.
The JavaScript Console reports back to you the coordinates.
Ignore all digits after the decimal point and use the whole
numbers for the x,y coordinates in your script.
68
Changing Text Colors
By default, Acrobat permits you to iden-
tify negative values with a red color in the
Format tab. If you want to emphasize a value
that's not a negative value or use another
color other than red, you can do so using
JavaScript.
Example script in the Format tab in a text field:
1. var f = this.getField("fieldName");
2. if (event.value >50)
3 f.textColor = color.red;
4. else
5. f.textColor = color.black
The above script sets the text color to red if the value in a
field named fieldName is greater than 50.
Acrobat provides you with some default colors
that you can assign to text and objects. If you
want to create a custom color look up a color in
a program like Adobe Photoshop and record the
RGB (or CMYK) values. The colors in Photoshop
use whole numbers to express color.
In Acrobat you define a color by using something
like ["RGB", .503, .982, .495]
To convert the color values from Photoshop to
Acrobat, take a Photoshop color and divide by
255. Therefore a color like a red value of 149
in Photoshop would be a red value of .584 in
Acrobat. The syntax for changing a color in a field
would be something like:
event.target.textColor = ["RGB",
.503, .982, .495];
ted’s ti
p
75
ted padova
ted@west.net
37
writing javascripts
Limiting Character Strings
You can limit the number of characters added
to a text field with a JavaScript. To do so, use the
example below:
Open the Text field properties on a field.
Click the Format tab.
Click the Custom Keystroke Script radio button.
Click Edit and add the following script in the JavaScript
Editor.
1. var f = this.getField("myField");
2. if (event.value.length > 10)
3. {
4. var msg = "Your entry is too long
(limit 10 chars).";
5. app.alert(msg);
6. }
70
71
Changing OCG States
Optional Content Groups are layers in a PDF
document. You have available an action to Set
Layer Visibility, but there are conditions where
the action won't work and you need to use a
JavaScript to change layer visibility.
To examine scripts that change layer visibility open the
Attachments panel and open the file attachment: housePlansForm.
pdf. Look over the JavaScripts in this document to discover how to
change layer visibility using JavaScript.
Spawning Pages From Templates
Spawning pages from templates provides you with options for
many uses. PDF files can be made more dynamic by adding content
on-the-fly through new pages added to a document.
Add a page to a document that you want to use for a
template and navigate to that page.
Click the Edit Layout tool in the Forms toolbar.
Choose Forms | Page Templates.
Type a name in the Page Templates dialog and click Add.
To hide the template from view, click the Eye icon.
Add a JavaScript to a button field and enter the following
code in the JavaScript Editor.
1. var a = this.getTemplate(“myTemplate”);
2. a.spawn ({
3. nPage:this.numPages,
4. bRename:true,
5. bOverlay:false
6. })
Be certain that you use the name you assigned to the tem-
plate in Line 1. When you click the button, a new page is
spawned from the template.
By default the bOverlay switch is
off meaning new pages are ap-
pended to the document. If you
want to overlay the new page on
an existing page (like adding a
watermark), set the toggle to true
as shown below:
bRename:true,
ted’s ti
p
70
ted padova
ted@west.net
38
writing javascripts
Popup Menus for URL Navigation
Popup menus provide you with navigation options that can be used
when viewing PDF files in Full Screen views. The following popup
menu item opens different URLs in your default Web browser.
Add the following script to a button:
1. // Declare pop-up menu properties as an
array.
2. var aParams = [
3. {cName: "Acrobat User Community", cReturn:
"www.acrobatusers.com"},
4. {cName: "-"},
5. {cName: "Acrobat User Blogs", cReturn:
"http://www.acrobatusers.com/blogs"},
7. {cName: "Ted's Blog Site", cReturn: "http://
www.acrobatusers.com/blogs/tedpadova"}
9. ];
10. var cChoice = app.popUpMenuEx.apply( app,
aParams );
11. if ( cChoice != null ) app.
launchURL(cChoice);
The above popup menu works much better than bookmarks if you
intend to display your form in Full Screen mode.
73
Popup Menus for Page Views
The app.popUpMenuEx object is the preferred
way to write a script for application popup
menus. However, you can get by with a much
easier script that works well in all Acrobat view-
ers.
The following example uses a simple method
for navigating pages in PDF.
Navigate to a view you want for a page link to a popup menu
item.
Choose View | Navigation Panels | Destinations.
Click the Create new destination tool in the Destinations
panel.
Repeat the steps for creating destinations to all views you
want to link to in a popup menu.
Create a button field and add a JavaScript with the following
code:
1. var cChoice = app.popUpMenu
2. (["First Page", "Home"],
3. ["Second Page", "Samples"],
4. ["Third Page", "JavaScripts"],
5. ["Fourth Page","URL Links"],
6. ["Fifth Page","Sample Forms"]);
7. this.gotoNamedDest(cChoice);
The first item in steps 2-6 is a parent name that shows a child
name when the menu is opened. The child names are the
same exact names as the destination names and a click on
the name in the menu opens the destination view.
You can add an unobtrusive pop-
up menu to a form that provides
URLs where users can explore
more product information, con-
tact info, company brochures, etc.
One button can open many links
and not disturb the form design.
ted’s ti
p
57
ted padova
ted@west.net
39
writing javascripts
Popup Menus for Opening Files
To create a popup menu that opens files, be certain to place the
files in the same folder as the document containing the popup
menu.
Add the following JavaScript to a button:
1. var cChoice = app.popUpMenu
2. (["Human Resource Forms", "hrForm.pdf", "va-
cationLeave.pdf"],
3. ["Sales Forms", "salesOrder.pdf", "custom-
erID.pdf", "purchaseForm.pdf"],
4. ["Administration Forms", "creditApplication-
Form.pdf", "creditApprovalLetter.pdf"]);
5. this.slave = app.openDoc((cChoice), this);
Each of the items (2-4) has multiple submenu items that open the
respective PDF documents.
Don't forget the semicolon (;) at the end of line 4. Each of the other
lines of code (2-3) end with a comma.
Emailing a PDF
From a button or a JavaScript assigned to another action you can
attach the open PDF document to an email message.
On a button field, add the following script:
1. // use mailDoc in this routine
2. this.mailDoc(true, "yourname@address.com",
"cc goes here", "bcc goes here","Subject goes
here");
Emailing Form Data
From a button or a JavaScript assigned to
another action you can attach just the form
data from the open document to an email
message.
On a button field, add the following script:
1. // use mailForm in this routine
2. // gets the user address from a field
3. var f = this.getField("useraddress");
4. this.mailForm(true, f.value, "", "","Subject");
The above script attaches an FDF form data file to an email mes-
sage. Line 3 picks up an email address from the form that the PDF
author added to a text field and uses that address for the To field in
a new email message.
76
Note that if you want to reference
fields on a page that have been filled
in by you and you don't want them to
be visible to the end user, you can fill
in a field and hide the field.
Open the General tab in the field
properties dialog box and choose
Hidden from the Form Field drop
down menu.
JavaScript will pick up the field
data even when the field is hidden.
ted’s ti
p
48
ted padova
ted@west.net
40
writing javascripts
Checking for Empty Fields
Before a document is submitted, you might want to have the form
checked to be certain that all fields have been filled in. The script to
perform such a function has two parts. The first part is a function
added as a document level JavaScript. The second part is the script
that executes when the Submit a Form button is clicked.
Add the following function as a Document Level JavaScript and
name the function aField:
Choose Advanced | Document Processing | Document
JavaScripts.
Type aField in the Script Name text box and click Add.
Type the following code in the JavaScript Editor.
1. function checkField(aField)
2. {
3. if (aField.value == "") // empty field
4. {
5. var msg = "No fields can be left empty.";
6. app.alert(msg);
7. return 0;
8. }
9. } // end of function
Click Close in the JavaScript Functions dialog box.
On a submit button, add the following script:
1. // the procedure begins here
2. var okToSubmit = true;
3. // loop over all fields:
4. for (var j = 0; j < this.numFields; j++)
5. {
6. var fieldname =
7. this.getNthFieldName(j);
8. var theField = this.getField(fieldname);
9. if (theField.type != 'text')
10. continue; // get past the button fields
11. var valid = checkField( theField );
12. if (!valid) // valid == 0? Halt!
13. {
14. okToSubmit = false; // set flag
15. break; // exit loop prematurely
The above routine checks all text fields to be certain some data
exist in the fields. If a field is left empty, the app.alert dialog box
described in the aField function reports the error.
Documents you may be interested
Documents you may be interested