The information in this document is furnished for informational use only, is subject t change
without notice, and should not be construed a s a commitment by Adobe Systems Incorporated.
Adobe Syst ems Incorporated assumes no responsibility or liability for any err ors or inaccuracies that may appear in this document. The software described in this document is f urnished
under licens e and may only be used or copied in accordance with the terms of such license.
Adobe, the Adobe logo, Acr obat, Acrobat Capture, Acrobat Exchange, and Distiller are trademarks of Adobe Syste ms Incorporated. Microsoft and Windows are registered trademarks and
ActiveX is a t rademark of Microsoft in the U.S. and other countries. Macintosh is a trademark
of Apple Computer, Inc. registered in the U.S. and other countries. P owerPC is a trademark of
International Business Machines Corporation. UNIX is a registered trademark in the U.S. and
other countr ies, licensed exclusively through X/Open Co. Ltd. All other pr oducts or name
brands a re trademarks of their respective holders.
JavaScript, the scripting language developed by Netscape C ommunications, enables you to
easily create interactive We b pages .
JavaScript v1.2 comes with six predef ined classes: Boolean, Number, Date, Math, String,and
Array . As part of the integration with Adobe® Acrobat® Forms, we have defined additional
classes and objects to allow acces s to portions of the PDF file.
This document describ es these classes, as wel l as details the load and e xecution of JavaScripts
in the Adobe Acrobat environment. Of particular note is the Field Object section which handles
all pr ocessing of Acrobat Form fields including their formatting, calculation, and validation.
The intended audience of this document is assumed to be f amiliar with Adobe Acrobat, the
Acrobat Forms plug-in a nd the Adobe Ac robat plug-in API.
Other useful documents
For more information on JavaScript, please see Netscape’s JavaScript Refere nce Manual for
details on J avaScript objects and on language syntax.
Portable Document Format Reference Manual, v ersion 1.2 or later, describes the PDF
representation of a form and its fields. Appendix H , describes the Forms Data Format, which is
one of the formats of da ta exported f rom an Ac robat form. This document is available with the
Adobe A crobat Plug-ins SDK CD-ROM or on the Adobe Web site http://www.adobe.com/
supportservice/devrelations/PDFS/TN/PDFSPEC.PDF.
Technical Note #5166, Acrobat Viewer plug-in API Overview . Gives an overview of the objec ts
and methods provided by the Acrobat viewers’ plug-in API. This document is available with
the Adobe Acr obat Plug-ins SDK CD-ROM or on the Adobe Web site http://beta1.adobe.com/
ada/acrosdk/DOCS/VWRPIOVR. PDF.
Technical Note #5167, Acrobat Viewer plug-in API Development. Tells how to develop
Acrobat viewer plug-ins on the various platforms available. This document is available with
the Adobe Acr obat Plug-ins SDK CD-ROM or on the Adobe Web site http://beta1.adobe.com/
ada/acrosdk/DOCS/VWRP IDEV.PDF
Technical Note #5168, Acrobat Viewer plug- in A PI On-Line Refer ence. Describes in detail the
objects and methods provided by the Acrobat viewer’s plug-in API. This document is a vailable
Acrobat Forms - JavaScript Object Specification
7
with the Adobe Acrobat Plug-ins SDK CD-ROM or on the Adobe Web site http://
beta1.adobe.com/ada/acrosdk/DOCS/VWRPIREF.PDF.
Document Conventions
As this document pertains to Acrobat Forms version 3.5 and greater, there exists s ome
compatibility issues with older versions of the software. If a property, method, or object is
marked with asymbol, then it is available only in ver sions of the Acrobat Forms sof tware
#.#
greater than or equal to #.#. Before accessing this object, proper ty, or method, the script should
check that the application version is greater than or equal to #.# if backwards compatibility is
desired.
Example:
if (typeof app.formsVersion != "undefined" && app.formsVersion >= 4.0) {
// Perform version specific operations.
}
As the JavaScr ipt extensions to Acrobat Forms have evolved, some properties or methods have
been superseded by other, mor e flexible or appropriate properties or methods. The use of these
older m ethods are discouraged and marked by Mr. Unhappy.
Acrobat Forms - JavaScript Object Specification
8
What’s New for 4.0
ObjectPropertiesMethods
App Object
Colo r O b j e ct
Doc Objectcalculate, delay,
Field Object
Util Object
formsVersion,
numPlugIns
openInPlace
toolbarHori z ontal
toolbarV ertical
viewerVersion
Note:Items shown in italics are not new to this release but they have been
modified or added t o.
New sections of the documentation for 4. 0:
New SectionDescription
Working With The
Date Object
Acrobat Forms
and Security
Working with
Signature Fields
Describes the proper methods for formatting
and parsing dates and performing date
arithmetic.
Shows how to properly define security settings
in a form so that it cannot be tampered with.
Details the proper usage of scripts when
signing documents includ ing inverse
operations upon form reset
Acrobat Forms - JavaScript Object Specification
9
Acrobat Forms JavaScript Object Model
Acrobat Forms de fines an object model on top of JavaScript 1.2. These objects are only
defined within the Adobe Acr obat realm and are specific to Acrobat Forms. They basically
mirror the Acrobat Forms components and give the forms developer a way to access these
components programmatically in or der to query and change their properties. In addition to
defining forms specific objects, ther e are additional generic objects that allows the developer
to ac cess the underlying document and perform certain actions on it.
App Object
The App object is a static JavaScript object that defines a number of Acrobat specific functions
plus a variety of utility routines and convenience functions.
App Object Properties
calculate
Type: BooleanAccess: R/W
If this property is s et to true, it will allow calculations to be performed. If set to false,this
property prevents all calculations in all documents from happening. Its default value is true.
See a lso the document calculate property which supersedes this property in later versions.
formsVersion
Type: NumberAccess: R
This property indicates the version number of the forms software running inside the view er.
Use this method to determine whethe r objects , properties, or methods in newer ver sions of the
software are available if you wish to maintain backwards compatibility in your scr ipts. See
Document Conventions for more details.
Example:
if (typeof app.formsVersion != "undefined" && app.formsVersion >= 4.5) {
// Perform version specific operations here.
}
4.0
fullscreen
Type: BooleanAccess: R/W
Acrobat Forms - JavaScript Object Specification
10
This pr operty puts the Acrobat viewer in fullscreen mode vs. regular viewing mode.
Example:
// on mouse up, set to fullscreen mode
app.fullscreen = true;
In the above example, the Adobe Acrobat viewer is set to fullscreen mode when app.fullscreen
is set to tr u e .Ifapp.fullscreen was false then def ault viewing mode would be set. The default
viewing mode is defined as the original mode the Acrobat application was in before full s creen
mode wa s initiated.
language
Type: StringAccess: R
This property defines the language of the running Acrobat Viewer. It returns the following
strings:
StringLanguage, Country
DEUGerman, Germany
ENUEnglish, The United States of Am erica
ESPSpanish, Spain
FRAFrench, France
ITAItalian, Italy
JPNJapanese, Japan
NLDDutch, The Netherlands
SVESwedish, Sweden
numPlugIns
4.0
Type: NumberAccess: R
This property indicates the number of plug-ins that have been loa ded by Acr obat. See als o the
getNthPlugInName method.
openInPlace
4.0
Type: NumberAccess: R/W
This property determines whether cross-document links are opened in the same window or
opened in a new window.
Acrobat Forms - JavaScript Object Specification
11
platform
Type: StringAccess: R
This propert y returns the pla tform that the script is currently executing on. Valid values
include “WIN”, “MAC”, and “UNIX ”.
toolbar
Type: BooleanAccess: R/W
This pr operty allows a script to show or hide both the horizontal and ve rtical Acrobat tool bars.
It does not hide the tool bar in external windows (i.e. in an Acrobat window within a Web
browser).
Example:
// Opened the document, now remove the toolbar.
app.toolbar = false;
toolbarHorizontal
Type: BooleanAccess: R/W
This pr operty allows a script to show or hide the Acr obat horizontal tool bar. It does not hide
the tool bar i n external windows (i.e. in an Acrobat window within a Web browser).
toolbarVertical
Type: BooleanAccess: R/W
This property allows a script to show or hide the Ac robat ve rtical tool bar. It does not hide the
tool bar in external windows ( i.e. in an Acrobat window within a Web browser).
viewerType
Type: StringAccess: R
This property determines if the r unning Acrobat Viewer is the Rea der vs. Exchange. Its value
is “Reader” or “Exchange” r espectivel y.
4.0
4.0
viewerVersion
Type: NumberAccess: R
This pr operty indicates the version number of the current viewer (i.e. Reader or Exchange) .
This method displays an alert dialog on the screen. The minimum required parameter is a string
containing the message to be displayed. Optionally, an icon type can be specified by using t he
nIcon par ameter. The following is a list of icons and their associated values:
IconValue
Error (default)0
Warning1
Question2
Status3
Additionally, a button group type can be specified:
Button GroupValue
OK (default)0
OK, Cancel1
Yes, No2
Yes, No, Cancel3
This method returns the type of the button that was pressed by the user:
Button TypeValue
Error0
OK1
Cancel2
No3
Yes4
beep
Parameters: [nType]
Return s: n one
Acrobat Forms - JavaScript Object Specification
13
This method causes the system to play a s ound. The various sounds and the values used are as
follows:
On Apple Ma cintosh a nd UNIX systems the beep type is ignored.
execMenuItem
4.0
Parameters: cMenuItem
Returns: nothing
This method executes the spe cified menu item. To find out the exact menu item name, see the
Acrobat Viewer Plug-in API On-line Reference under § Lists: Menu item names. The menu
item name is case sensitive and has to exactly match strings in the list.
Example:
/* This example executes File->Open menu item. It will display a dialog to the
user asking for the file to be opened. */
app.execMenuItem("Open");
Note:For s ecurity reasons, we will not allow the script to execute t he SaveAs and
Close menu items. If either of those two menu items is passed as cMenuItem,
this function will do nothing.
getNthPlugInName
4.0
Parameters: nIndex
Returns: cName
This method returns the name of the Nth plug-in that has bee n loaded by the view er. See also
the numPlugIns property.
Acrobat Forms - JavaScript Object Specification
14
goBack
Parameters: None
Returns: nothing
Use this function to go to the previous view on the view stac k. This is equivalent to pressing
the go back button on the Acrobat tool bar.
goForward
Parameters: None
Returns: nothing
Use t his function to go to the next view on the view stack. This is equivalent to pressing the go
forward button on the Acrobat tool ba r.
hideMenuItem
Parameters: cName
Returns: nothing
This method only works in the Config.js Plug-i n fo lder l evel script. It allows a forms integrator
to customize the look of the Acrobat viewer by removing the m enu item specified by cName .
Language independent names for toolbar buttons can be obtaine d fr om the Acrobat ViewerPlug-In API On-line Reference (Technical Note #5168).SeeO ther use ful docum ents for more
details.
hideTo olbarButt on
Parameters: cName
Returns: nothing
This method only works in the Config.js Plug-i n fo lder l evel script. It allows a forms integrator
to customize the look of the Acrobat viewer by removing the toolbar button specified by
cName. Language independe nt names for toolbar buttons can be obtained from the Acrobat
Viewer Plug-In API On-line Reference (Technical Note #5168).SeeOther use ful doc um ent s for
This method sends out an e-mail message with or without user interaction depending on the
value of bUI. I f it is set to true then the rest parame ters are used to seed the compose new
message window that is displayed to the user.
Acrobat Forms - JavaScript Object Specification
4.0
15
If bUI is set to false, the cTo para meter is required and others are optional. You must use a
semicolon “;” to separate multiple recipients in cTo, cCc, cBcc parameters. The length limit for
cSubject and cMsgBody is 64k bytes.
Example:
/* This will pop up the compose new message window */
app.mailMsg(true);
/* This will send out the mail to fun1@fun.com and fun2@fun.com */
app.mailMsg(false,
"fun1@fun.com; fun2@fun.com", "", "", "This is the subject",
"This is the body of the mail.");
Note:This is a Windows-only feature. In addition, the client machine must have its
default mail program configured to be MAPI enabled in order to use this
method.
response
Parameters: cQuestion [cTitle], [cOldValue]
Returns: cResponse or null on cancel
This method displays a dialog box containing a question and an entry field for the user to reply
to the question. Optionally, the dialog may have a title or a de fault value for the answer to the
question. The return va lue is a string c ontaining the user’s response. I f the user presses the
cancel button on the dialog the r esponse is the null object.
Acrobat Forms - JavaScript Object Specification
16
Color Arrays
A color is represented in JavaScript as an array containing 1, 2, 4, or 5 elements corresponding
to a transpar ent, gray, RGB, or CMYK color space, respectively. The first element in the arr ay
is a string denoting the color space type. The subsequent elements are numbers that range
between zero and one inclusive. The following table illustrates this:
Color SpaceString#of Additional
Elements
Transparent“T”0
Gray“G”1
RGB“RGB”3
CMYK“CMYK”4
For example, the color red can be represent ed as [“RGB” 1 0 0].
Invalid strings or ins ufficient elements in a color array cause the color to be interpreted as the
color black.
A transparent color spa ce indicates a complete absence of color and will allow those portions
of the document underlying the current field to show through.
Colors in the gray color space are represented by a single value—the intensity of achromatic
light. In this color space, 0 is black, 1 is white, and intermediate values represent shades of
gray (i.e. “.5”, “.7” etc.).
Colors in the RGB colo r space are represented by three values: the intens ity of the r ed, green,
and blue components in the output. RGB is commonly used f or video displays bec ause they are
generally bas ed on red, green, and blue phosphors.
Colors in the CMYK color spa ce are represented by four values. These va lues are the amounts
of the cyan, magenta, yellow, and black components in the output. This color space is
commonly used for color printers, where they are the colors of the inks traditionally us ed in
four-color printing. Only cya n, magenta, and yellow are necessary, but black is generally us ed
in printing because black ink produces a better black than a mixture of cyan, magenta, and
yellow inks , and because black ink is less expensive than the other inks.
Color Object
The colo r object is a convenience static object that defines the basic colors . These colors are
accessed in JavaScr ipts via the color obj ect. Use t his objec t whene ver you want to set a
property or call a method tha t require a color array. T he color object is defined in AForm.js.
Acrobat Forms - JavaScript Object Specification
17
Color Properties
The color object defines the following color s and there associated keywords:
// This example sets the text color of the field to red
// if the value of the field is negative, else it sets it
// to black.
var f = event.target; /* field that the event occurs at */
if (event.value < 0)
else
Dark Graycolor.dkGray
Graycolor.gray
Light Graycolor.ltGray
f.textColor = color.red;
f.textColor = color.black;
4.0
4.0
4.0
Acrobat Forms - JavaScript Object Specification
18
Console Object
The Console objec t is a static object to acces s the JavaScript console for displaying debug
messages. I t functions only within Acrobat Exchange.
Console Methods
show
Parameters: none
Return s: n one
This method shows the console window.
hide
Parameters: none
Return s: n one
This method closes the console window.
println
Parameters: cMessage
Return s: n one
This method prints the string value of cMessage to the console window with an accompanying
carriage return.
Example:
// This example prints the value of a field to the console window
var f = event.target;
console.println("Field value="+f.value);
clear
Parameters: none
Returns: nothing
This method clears the cons ole windows buffer of any output.
Acrobat Forms - JavaScript Object Specification
19
Doc Object
The JavaScript Doc objec t provides the interfaces between a PDF document open in the viewer
and the J avaScript interpreter. It provides methods and properties of the PDF document.
Doc Access from JavaScript
Accessing the Doc object f rom JavaScript can be done either through the this Object , which
usually points to the Doc object of the underlying document. The target event property points
to the field that initiated the event for all mouse, calculate, validate, and format events. For all
other events, it directly points to the Doc object. The examples below illustrates the use of the
Event object to access the Doc object of the underlying document.
// In Mouse, calculate, validate, format events
var doc = event.target.doc;
// In all other events
var doc = event.target;
Doc Object Properties
author
Type: StringAccess: R/W
This property defines the author of the document.
this.author = "Robert Frost";
calculate
Type: BooleanAccess: R/W
If this property is set to true, it will allow calculations to be performed for this document. If
set to false, this property prevents all calculations from happening for this document. Its
default value is true. This property supersedes the application level calculate property whose
use is now discouraged.
creator
Type: StringAccess: R
4.0
This property defines the creator of the document (e.g. “Adobe FrameMaker”,“Adobe
PageMaker”, etc.).
Acrobat Forms - JavaScript Object Specification
20
creationDate
Type: DateAc cess: R
This pr operty defines the documents creation date.
delay
4.0
Type: BooleanAccess: R/W
This pr operty delays the redrawing of any appearance cha nges to every field in the document.
It is generally used to buffer a series of changes to f ields before r equesting that the fields
regenerate their appearance. Setting the property to true forces all changes to be queued until
delay is reset to false.Oncesettofalse the n all the field s on the page a re re-dr aw n. See a ls o
the field level delay property.
dirty
Type: BooleanAccess: R/W
This property identifies whethe r the document has been dirtied as the result of a changes to the
document (and therefore needs to be s aved). I t is usef ul to r eset the dirty flag in a document
when performing changes that do not warrant saving, for example, updating a status field in the
document.
var f = this.getField("Status");
var b = this.dirty;
f.value = "Press the reset button to clear the form.";
this.dirty = b;
external
4.0
Type: BooleanAccess: R
This property indicates whether the current document is being viewed in the Acrobat
application or in an e xternal window (such as a web browser).
filesize
Type: IntegerAccess: R
This pr operty determines the file size of the document in bytes.
Acrobat Forms - JavaScript Object Specification
21
keywords
Type: StringAccess: R/W
This pr operty specifies the document’s keywords in the Adobe Acrobat File->Document Info>General dialog box.
modDate
Type: DateAc cess: R
This pr operty contains the date the document was last modified.
numFields
Type: IntegerAccess: R
This property r eturns the total number of fields in the document. See also the getNthFieldName
method.
numPages
Type: IntegerAccess: R
This proper ty contains the number of pages in the document.
numTemplates
Type: IntegerAccess: R
This property returns the number of templates in the document (see also getNthTemplate and
spawnPageFromTemplate methods).
4.0
path
Type: StringAccess: R
This property defines the device independent path of the document, for example /Acrobat3/
Exchange/doc.pdf
pageNum
Type: IntegerAccess: R/W
Acrobat Forms - JavaScript Object Specification
22
Use this property to ge t or s et a page of the document. When setting the pageNum to a specif ic
page, remember that the values are “0” based.
// This example will go to the first page of the document.
this.pageNum=0;
Or pageNum can be used to advance “n” page s in the document:
// This example will advance the document to the next page
this.pageNum++;
producer
Type: StringAccess: R
This pr operty contains producer of the document (e.g. “Acrobat Distiller”, “PDFWriter”, etc.).
subject
Type: StringAccess: R/W
This proper ty defines the document’s subject.
title
Type: StringAccess: R/W
This property specifies the document’s title
zoom
Type: IntegerAccess: R/W
Use this property it to get or s et the current page z oom level. The values allowed a re 12% and
800% spec ified as an integer.
Example:
// This example will zoom in to twice the current zoom level.
this.zoom *= 2;
// This now sets the zoom to 200%
this.zoom = 200;
Acrobat Forms - JavaScript Object Specification
23
zoomType
Type: StringAccess: R/W
This property s pecifies the current z oom type of the document. Valid zoom types ar e: none, fit
page, fit width, fit height, and fit visible width. A convenience zoomType object that defines all
the valid zoom types is provided for use from JavaScript. It provides the following zoom types:
Use t his method to export an FDF file to the local hard drive. Upon invocation, a dialog will be
shown to let the us er select the file to expor t to.
The optional bAllFields parameter indicates, if true, that all fields are exported, including those
that have no value, and if f alse (the default) to exclude those that currently have no va lue.
The optional bNoPassword parameter indicates, if true (the default), not to include in the
exported FDF text fields that have the “password” flag set.
4.0
Acrobat Forms - JavaScript Object Specification
24
The optional aFields parameter is the array of field names to submit or a string containing a
single f ield name. If this parameter is present then only the f ields indicated are exported,
except those excluded b y par ameter bEmpty or bNoPassword. If this parameter is omitted or is
null then all f ields in the f orm are exported (again subject to the restrictions of bEmpty).
You can include non-terminal fields in the array or the str ing passed as a parameter: this is a
simple shortcut for having a whole subtree exported.
Example:
/* Export the entire form (including empty fields) with flags. */
this.exportAsFDF(true, true, null, true);
/* Export the name subtree with no flags. */
this.exportAsFDF(false, true, “name”);
The example above illustrates a shortcut to exporting a whole subtree. Pas sing “name” as part
of the aFields parameter, exports “name.title”, “name.first”, “name.middle” and “name.last”,
etc.
The optional aFlags parameter indicates, if true, that field flags should be included in the
exported F DF. The default is false.
This method does not wor k in the Acrobat Reader.
getField
Parameters: cName
Return s: o bje ct
Use this function to map a field object in the PDF document to a JavaScript variable. T he
cName parameter is the name of the field of interest. This function returns a Field JavaScript
object r epresenting the form field in the P DF document.
getNthFieldName
4.0
Parameters: nIndex
Returns: cName
Use t his function to obtain the nth field name in the document (see the numFieldsproper ty).
Example:
// Enumerate through all of the fields in the document.
for(vari=0;i<this.numFields; i++) {
Use this function to retrieve the name of a template within in the document. ( See also the
numTemplates property and spawnPageFromTemplate method.)
getURL
Parameters: cURL, [bAppend]
Returns: nothing
This method retrieves the specified URL over the internet using a GET. If the current
document is being viewed inside the browser or Acrobat Web Capture is not available, it uses
the Weblink plug-in to retrieve the requested URL. If bAppend is true (the default) and Acrobat
Web Capture is available, the resulting pages are appended to the current document.
gotoNamedDest
Parameters: cName
Returns: nothing
Use this method to go to a named destination within the PDF document. For more details on
named destinations and how to create them, se e the PDF Reference Manual Version 1.3
importAnFDF
Parameters: [cFile]
Returns: nothing
4.0
4.0
This method imports the specified FDF file. The cFile par ameter specifies the deviceindependent pathname to the FDF file. See Section 7.4 of the PDF Reference Manual for a
description of the device-indepe ndent pathname f ormat (it should look like the value of the /F
key in an FDF exporte d via the exportAsFDF method or via the “File->Export->Form Da ta”
menu item). The pathname may be relative to the loca tion of the current document. If the
parameter is omitted a dialog will be shown to let the user select the file. This method does not
work in t he Acrobat Reader .
This method saves the current PDF document and mails it as an attachment to all recipients
with or without user interaction depending on the value of bUI. If it is set to true then the rest
Acrobat Forms - JavaScript Object Specification
4.0
26
of the parameters are used to seed the compose new message window that is displayed to the
user.
If bUI is set to false, th e cTo parameter is required and all others are optional. You must use a
semicolon “;” to separate multiple recipients in cTo, cCc, cBcc parameters. The length limit for
cSubject and cMsgBody is 64k bytes.
Example:
/* This will pop up the compose new message window */
this.mailDoc(true);
/* This will send out the mail with the attached PDF file to fun1@fun.com and
fun2@fun.com */
this.mailDoc(false, "fun1@fun.com", "fun2@fun.com", "", "This is the subject",
"This is the body.");
Note:This is a Windows-only feature. In addition, the client machine must have its
default mail program configured to be MAPI enabled in order to use this
method.
This method exports the form data and mails the resulting FDF file as a n attachment to all
recipients, with or without user interaction depending on the value of bUI.Ifitissettotrue
then the rest of the parameters are used to se ed the compose new message window that is
displayed to t he user.
If bUI is set to false, th e cTo parameter is required and all others are optional. You must use a
semicolon “;” to separate multiple recipients in cTo, cCc, cBcc parameters. The length limit for
cSubject and cMsgBody is 64k bytes.
Example:
/* This will pop up the compose new message window */
this.mailForm(true);
/* This will send out the mail with the attached FDF file to fun1@fun.com and
fun2@fun.com */
this.mailForm(false, "fun1@fun.com; fun2@fun.com", "", "", "This is the
subject", "This is the body of the mail.");
Acrobat Forms - JavaScript Object Specification
27
Note:This is a Windows-only feature. In addition, the client machine must have its
default mail program configured to be MAPI enabled in order to use this
method.
print
Paramet ers: b In terac tiv e, [nF irst Pag e], [ nLa stP age], [ bS ilent]
Returns: nothing
Use t his function to pr int all or a specific number of pages of the document. If bInteractive is
true, Acr obat displays the s tandard print dialog and all other parameters are ignored. Theoptional nFirstPage and nLastPage parameters specify the range of pages to print. If using
nFirstPage and nLastPage parameters bInteractive must be false. Set the optional bSilent flag
to true if you don’t want to display the cancel dialog box while the document is printing. The
default value for bSilent fla g is false.
Example:
// This Example will print current page the document is on
this.print(false, this.pageNum, this.pageNum);
resetForm
Parameters: [aFields]
Returns: nothing
Use this method to reset the field values within a document. If the aFields parameter is
present, then only the fields indicated are reset. If not present or null then all fields in the form
are reset. You can include non-terminal f ields in the array. Us e this as a simple shortcut for
having a whole subtree reset. For example, if you pass “name” as part of the fields array then
“name.first”, “name.last”, etc. will be reset.
var fields = new Array(2);
fields[0] = "P1.OrderForm.Description";
fields[1] = "P1.OrderForm.Qty";
this.resetForm(fields);
scroll
Parameters: xO rigin, yOrigin
Returns: nothing
Acrobat Forms - JavaScript Object Specification
28
Use this function to scroll the cur rent page to the location specified by xOrigin and yOrigin.
These coordinates must be defi ned in user space. Please refer t o the PDF Ref erence Manual
Version 1. 3 for more details on the user space coordinate system.
Use this method wit h a template name, such as the ones returned by getNthTemplate.The
optional parameter nP age, represents the page number (zero-based) into which the template
will be spawned. If that page already exists, then the template contents ar e appended to that
page. If nPage is omitted, a new page is created at the e nd of the document. T he optional
parameter bRename, is a boolean that indicates whether fields should be renamed. The default
for bRename is true.
Example:
var n = this.numTemplates;
var cTempl;
for(i=0;i<n;i++) {
If bInsert is specified then the template is inserted before the page specified by nPage as
opposed to being overlaid on top of that pa ge. The default for bInsert is false.
Use t his method to submit the f orm to a specific URL. The first parameter, cURL, is the URL
to submit to. This string must end in “#FDF” if the result from the submission is FDF and the
document is being viewed inside a browser window.
The optional bF DF parameter is a boolean that indicates to submit as FDF or HTML. If s et to
true, the default, it submits the form data as FDF. If false,itsubmitsitasHTML(URL
encoded).
The optional bEmpty parameter i s a boolean that indicates, when tru e, that all fields are
submitted, including those that have no value and if false to exclude those that currently have
no value. T he default for bEmpty is false.
Acrobat Forms - JavaScript Object Specification
29
The optional aFields parameter is the array of field names to submit or a string containing a
single field name. If this parameter is present then only the fields indicated are s ubmitted,
except those excluded by parameter bEmpty. If this parameter is omitted or is null then all
fields in the Form are submitted (again subject to the restrictions of bEmpty).
You can include non-terminal fields in the array or the str ing passed as a parameter: this is a
simple shortcut for having a whole subtree submitted.
Example:
/* Submit the form to the server */
this.submitForm("http://myserver/cgi-bin/myscript.cgi#FDF");
/* Or */
this.submitForm("http://myserver/cgi-bin/myscript.cgi#FDF",
true, "name");
The example above illustrates a shortcut to s ubmitting a w hole subtree. Passing “name” as part
of the field parameter, submits “name.title”, “name.first”, “name .middle” and “name.last”.
Addition
4.0
The optional bGet parameter indicates, if true, that the submission uses the GET HTTP method
and if false (the default) a POST. GET is only allowed if using Acrobat Web Capture to submit
(the browser interface only supports POST) and only if the data is s ent as HTML (i.e. bFDF
should be false ).
Note:You need to be running inside a web browser or have the Acrobat Web
Capture plug-in installed, in order to call the submitForm method ( unless
the U RL uses the “mailto” scheme, in which case it will be honored even if
not r unning inside a w eb browser, as long as the SendMail plug-in is
present).
Note:Usage of the https protocol is s upported for secure connections.
Acrobat Forms - JavaScript Object Specification
30
Event Object
All Jav aScripts are executed as the result of a particular event (also referred to as a trigger).
Acrobat Forms accepts the following events and executes any scr ipts that are specified for
these events: mouse enter, mouse down, mouse up, mous e ex it, keys troke, format, validate, and
calculate. It is important to JavaScript writers to know what these events are and when and
what or der they are processed.
Event Processing
Mouse Enter
The mouse enter eve nt is triggered when a user moves t he mouse pointer inside the rectangle
of a field. T his is the typical plac e to open a text field to display help text, etc.
Mouse Down
The mous e down event is triggered when a user starts to click on a form f ield and the m ouse
button is still down. It is advised that you perform very little processing (i.e. play a short
sound) during this event. A mouse down event will not occ ur unless a mouse enter event has
already occurred.
Mouse Up
The mouse up event is triggered when the user clicks on a form f ield and releases the mouse
button. T his is the typical place to attach routines such as the submit action if a form. A mouseup eve nt will not occur unless a mouse down event has already occur red.
Mouse Exit
The mous e exit event is the opposite of the mouse enter event and occur s when a us er moves
the mouse pointer outside of the rectangle of a field. A mouse exit event will not occur unless a
mouse enter event has already occurred.
Keystroke
The keystr oke event oc curs whenever a us er types a keys troke into a te xt box or combo box
(this includes cut and pas te operations), or selects an item in a combo box drop down or listbox
field. A keystroke script may want to limit the type of keys allowed. For example, a numeric
field might only a llow numeric characters.
Acrobat Forms - JavaScript Object Specification
31
The us er interface for Acrobat Forms allows the author to s pecify a Selection Change scrip t fo r
list boxes . The script is trigge red every time an item is selected. This is implemented as the
keystroke e vent where the keystroke value is equivalent to the us er selection. This behavior is
also implemented for the combo box—the “keystroke” could be thought to be a paste into the
text f ield of the value selected from the drop dow n list.
There is a final call to the keystroke script before the validate e vent is triggered. T his call sets
the w illCommit property to true for the event. With keystroke processing, it is sometimes
useful to make a final check on the field value before it is committed (pre-commit). This
allows the s cript writer to gracefully handle particularly complex formats that can only be
partially checked on a keys troke by keystroke basis.
Validate
Regardless of the field type, user interaction with the field may p roduce a new value for that
field. After the user has either c licked outside a field, tabbed to another field, o r pressed the
enter key, the user is said to have committed the new data value.
The validate e vent is the first event generated for a field after the value has been committed so
that a JavaScript can verify that t he value entered wa s correct. I f the vali date event is
successful, the next event triggered is the calculate event.
Calculate
The calculate event causes all fi elds that have a calcul ation script attached to them to be
executed. All fields that depend on the value o f the validated field will now be re- calculated.
These fields may in turn generate additional validate, calculate, and format events .
Calculated fields may have dependencies on other calculated fie lds whose values must be
determined beforehand. The calculation or der array c ontains an ordered list of all the f ields in
a document that have a cal culation s cript atta ched. When a full calculation is needed, each of
the fields in the array is calculated in turn starting with the z eroth index of the array and
continuing in sequence to the end of the array.
To change t he calcul ation order of fields, use the Tools->Forms->JavaScript->Set CalculationOrder... menu item in Adobe Acrobat.
Format
Once all dependent calculations have been performed t he format eve nt is tr iggered. This event
allows the attached JavaScript to change the way tha t the da ta value appears to a user (also
known as its presentation or appearance). For exa mple, if a data value is a number and the
context in which it should be displayed is currency, the formatting s cript can add a dollar sign
($) to the front of the value and limit it to two decimal places past the decimal point.
This property spec ifies the change in value that the us er has just typed. The change is
replaceable such that if the JavaScript wishes to substitute certain characters, it may.
commitKey
4.0
Type: NumberEvent: Keystroke, FormatAccess: R
Use this property to determine how a form field lost focus. Valid values are:
0 - value was not committed (e.g. escape key was pressed).
1 - value was committed because of a click outs ide the field using the mouse.
2 - value was committed because of hitting the enter key.
3 - value was committed by tabbing to a new field.
For example, to automatically display a n alert dialog after a field has been committed add the
following to the field’s format script:
if (event.commitKey != 0)
app.alert(“Thank you for your new field value.”);
modifier
Type: BooleanEvent: Keystroke, Mouse e vents Access: R
This pr operty is a boolean that specifies whether the modifier key is down during a pa rticular
event. The modifier key on the Microsoft Windows platform is Control and on the Macintosh
platform is Option or Command. The modifier property is not supported on UNIX.
This property is used for validation. It indicates whe ther a particular e vent in the event chain
should succeed. Set rc to fal s e to prevent a change from occurring or a value from committing.
By default rc is true.
Acrobat Forms - JavaScript Object Specification
33
For each event, e xcept t he mouse related events, the static event object is populated with the
following data. In most events, it is important for JavaScript to se t the rc (return code)
property to indicate that the event can proceed.
selEnd
Type: IntegerEvent: KeystrokeAc cess: R/W
This property specifies the ending position of the current text selection during a keystroke
event.
selStart
Type: IntegerEvent: KeystrokeAc cess: R/W
This property specifies the starting position of the current text selection during a keystroke
event.
shift
Type: BooleanEvent: Keystroke, Mouse e vents Access: R
This property is a boolean that specifies whether the shift key is down during a particular
event.
target
Type: ObjectEvent: All eventsAccess: R
This property contains the target object tha t triggered the event. In all m ouse events it is the
field object that triggered the event. In other events like page open and close it is the document
or this Object.
value
Type: VariousEvent: Validate, Calculate, Format, SelChange Acces s: R/W
For the validate event, value is the value that the field contains when it is committed. The
current field value is the value property for the field. For example, the following JavaScript
verifies that the field value is between zero and 100.
Example:
if (event.value<0||event.value > 100) {
app.beep(0);
Acrobat Forms - JavaScript Object Specification
34
app.alert("Invalid value for field " + event.target.name);
event.rc = false;
}
For a calculate event, JavaScript should set this property. This is the value that the field should
take upon completion of the event. For exa mple, the following JavaScript sets the calculated
value of the f ield to the value of the SubTotal field plus tax.
var f = this.getField("SubTotal");
event.value = f.value * 1.0725;
For a fo rmat event, JavaScript should set this property. This is the value use d when generating
the appearance for the field. By default, it contains the value that the user has committed. For
example, the following JavaScri pt formats the field as a currency type of field.
event.value = util.printf("$%.2f", event.value);
willCommit
Type: BooleanEvent: KeystrokeAccess: R
Use this property to verify the c urrent keystroke event before the data is committed. This is
useful to check t he target form field values and for example verify if charac ter data instead of
numeric data was entered. JavaScript sets this property to true after the last keystroke event
and be fore the field is validat ed.
Example:
var value = event.value
if (event.willCommit)
// Final value checking.
else
// Keystroke level checking.
For more examples of using willCommit, refer to the Acrobat Forms JavaScript application
(Aform.js) in your Acrobat plug-ins dire ctory.
Acrobat Forms - JavaScript Object Specification
35
Field Object
The Field objec t represents an Acrobat form field (that is, a field created using the Acrobat
form tool). In the s ame manner that an author might want to modify an existing field’s
properties like the border color or font, the Field object gives the JavaScript user the ability to
perform the same modifications.
Field Access from JavaScript
Before a fie ld can be a ccessed, it must be “bound” to a J avaScript var iable through a method
provided by the this Object methods interface. More than one variable may be bound to a field
by modifying the field’s objec t properties or accessing its methods. This a ffects all va riables
bound to that field.
var f = doc.getField("Total");
This example allows the script to now manipulate the form field Total via the variable “f”.
Field Properties
The following is a chart of fi eld property names used by Acrobat with Javascript and the field
properties that are available:
This property determines how the text is laid out within the text field. Valid alignments include
left, center, and right.
var f = this.getField("MyText");
f.alignment = "center";
Acrobat Forms - JavaScript Object Specification
37
borderStyle
Type: StringFields: AllAccess: R/W
This property specifies the border style for a field. V alid border styles include solid, dashed,
beveled, inset, and underline. The border style determines how the bor der for the rectangle is
drawn.
•Thesolid style strokes the entire perimeter of the rectangle with a solid line.
•Thedashed style strokes the perimeter with a dashed line.
•Thebeveled style is equivalent to the solid style with an additional beveled
(pushed-out appearance) border applied inside the solid border.
•Theinset style is equivalent to the solid style with an additional inset (pushed-in
appearance) border applied inside the solid border.
•Theunderline style strokes the bottom portion of the r ectangle’s perimeter.
The border object is a static convenience cons tant that defines all the border s tyles of a field.
The f ollowing example illustrates how to set the border style of a field to solid:
var f = this.getField("MyField");
f.borderStyle = border.s; /* border.s evaluates to "solid" */
The following chart defines the borderStyle property and its associated keywords:
Use t his property to change the calculation order of fields in the document. When a computable
Text or Combo Box field is added to a document, it is added to the end of the document and the
field’s name is pl aced in the calculation order array.Thecalculation order array determines
the orde r fields are calculated in the document (see Event Processing for more information
about calculation order arrays). The calcOrderIndex property works similarly to the Calculate
tab used by the Acrobat Exchange Form tool. Note the following example:
Acrobat Forms - JavaScript Object Specification
38
var a = this.getField("newItem");
var b = this.getField("oldItem");
a.calcOrderIndex = b.calcOrderIndex + 1;
In this example, the this Object method getField,getsthenewItem field that was added after
‘oldItem’ field. It then changes the calcOrderIndex of the oldItem fieldsothatitiscalculated
before ‘newItem’ field.
charLimit
Type: IntegerFields: TextAccess: R/W
This property limits the number of characters that a user can type into a text field.
defaultValue
Type: StringFields: All but ButtonAccess: R/W
This property exposes the default value of a field. This is the value that the field is set to when
the form is reset.
delay
Type: BooleanFields: AllAccess: R/W
This property delays the redrawing of a field’ s appearance. It is gener ally used to buffer a
series of changes to the pr operties of the field before requesting that the field r egenerate its
appearance. Setting the property to true forces the field to wait until delay is set to false.The
update of its a ppearance then takes place, redrawing the field with its latest settings.
// Get the MyCheckBox field
var f = this.getField("MyCheckBox");
// set the delay and change the fields properties
// to beveled edge and medium thickness line.
f.delay = true;
f.borderStyle = border.b;
f.strokeWidth = 2;
// force the changes now
f.delay = false;
There is a corresponding doc ument level delay flag if changes are being made to many fields at
once.
Acrobat Forms - JavaScript Object Specification
39
display
Type: IntegerFields: AllAccess: R/W
This proper ty controls whether the f ield is hidden or visible on screen and in print:
EffectKeyword
Field is visible on screen and in printdisplay.visible
Field is hidden on screen and in printdispl ay.hidden
Field is visible on screen but doesn’t printdisplay.noPrint
Field is hidden on screen but p rintsdisplay.noView
This proper ty supersedes the older hidden and print properties.
doc
Type: ObjectFields: AllAccess: R
4.0
This property defines the document the field be longs to. Its va lue is the this Object or the this
Object . Pleas e ref er t o the this Object section for more details.
editable
Type: BooleanFields: ComboboxAccess: R/W
Combo boxes can be editable, that is, the user can type in a selection. This property determines
whether t he user can type in a selection or must choose one of the provided selections.
var f = this.getField("MyComboBox");
f.editable = true;
fillColor
Type: ArrayFields: AllAccess: R/W
This property specifies the background color for a field. The background color is used to fill
the field’s rectangle. Values are defined by using transparent, gray, RGB or CMYK color.
Refer to the Gl obal Objec t section for information on defining color arrays and how values are
used with this property.
var f = this.getField("MyField");
if (color.equal(f.fillColor, color.red))
Acrobat Forms - JavaScript Object Specification
40
f.fillColor = color.blue;
else
f.fillColor = color.yellow;
In older vers ions of this specification, this property was na med
bgColor
. The use of
bgColor
is
now discouraged but for backwards compatibility is still valid.
hidden
Type: BooleanFields: AllAccess: R/W
This property controls whether the field is hidden or visible to the user. If the value is false the
field is visible, true the field is invisible. The default value for hidden is false.
// Set the field to hidden
var f = this.getField("MyField");
f.hidden = true;
See also the display property which supersedes this property in later versions.
highlight
Type: StringFields: ButtonAccess: R/W
This property defines how a button reacts when a user clicks i t. T he four highlight modes
supported a re none, invert, push and outline.
•Thenone highlight does not indicate visually that the button has been clicked.
•Theinvert highlight causes the r egion encompassing the button’s rectangle to inver t
momentarily.
•Thepush highlight displays the down face for the button (if any) momentarily.
•Theoutline highlight causes the border of the rectangle to invert momentarily.
The ‘ highlight’ object defines all the characteristics that a button can have. Use it in your
scripts to access t he highlight of choice. The following chart shows the highlight object and its
associated keywords:
The f ollowing example sets the highlight property of a button to “inver t”.
// set the highlight mode on button to invert
var f = this.getField("MyButton");
f.highlight = highlight.i;
lineWidth
Type: IntegerFields: AllAccess: R/W
This property specifies the thickness of the bor der when stroking the perimeter of a field’s
rectangle. If the stroke color is transpare nt, thi s paramet er has no effect exce pt in the ca se of a
beveled bor der. You can set the lineWidth property in JavaScript by using the integer values
below:
Line WidthKey Value
none0
thin1
medium2
thick3
For example:
// Change the border width of the Text Box to medium thickness
f.lineWidth = 2
The default value for lineWidth is 1 (thin ) . Any integer value can be used. However, v alues
beyond 5 may dis tort the field’s appearance.
In older versions of this specif ication, this property was
borderWidth
.Theuseof
borderWidth
is now discouraged but for backwards compatibility is still valid.
multiline
Type: BooleanFields: TextAccess: R
This read-only property determines how the text is wrapped within the field. Text fields can be
single line (clip to field boundaries) or multi-line (wrap to field boundaries).
name
Type: StringFields: AllAccess: R
Acrobat Forms - JavaScript Object Specification
42
This property allows you to access the fully qualified field name of the field as a string object.
var f = this.getField("MyField");
console.println(f.name);
numItems
Type: IntegerFields: Combo & L istboxAccess: R
The number of items in the combo or list box.
password
Type: BooleanFields: TextAccess: R
This property causes the field to display asterisks for the data entered into the field. Upon
submission, the actual data entered is sent. Fields that ha ve the password attribute set will not
have the data in t he field saved when the document is saved to disk.
print
L
Type: BooleanFields: AllAccess: R/W
This property determines whether a given field prints or not. Set the print property to true to
allow the field to appear when the user prints the document, set it to false to prevent printing.
This pr operty can be used to hide control buttons and other fields that are not useful on the
printed page.
var f = this.getField("MyField");
f.print = false;
This pr operty has been superseded by the displaypropert y and its use is dis couraged.
readonly
Type: BooleanFields: AllAccess: R/W
This property sets or gets the read-only characteristic of a field. If a f ield is r ead-only, the user
can see the f ield but cannot change it.
required
Type: BooleanFields: All but ButtonAccess : R/W
Acrobat Forms - JavaScript Object Specification
43
This property sets or gets the required characteri stic of a field. If a fi eld is required its value
must be non-null when the user clicks a submit button that causes the value of the field to be
posted. If the field value is null, the user receives a war ning message and the submit does not
occur.
var f = this.getField("MyField");
f.required = true;
strokeColor
Type: ArrayFields: AllAccess: R/W
This property specifies the s troke color for a field which is used to stroke the field’s rectangle
with a line as large as the line width. Values are defined by using transparent, gray, RGB or
CMYK color. Refer to the C ol or Arrays section for information on defining color arrays a nd how
values are us ed with this property.
In older versions of this specification, this property was
borderColor
. The use of
borderColor
is
now discouraged but for backwards compatibility is still valid.
style
Type: StringFields: Checkbox, Radio ButtonAccess: R/W
This property allows the user to set the style of a check box or a radio button, that is, sets the
glyph used to indicate that the check box or radio button has been s elected. Valid styles
include check, cross, diamond, circle, star, and square. The following defines the style
properties and the a ssociated keywor ds:
StyleKey word
checksty le.ch
crossstyle.cr
diamonds ty le.di
circlestyle.ci
starstyle.st
squarestyle.sq
The f ollowing example illustrates the use if this property and the style object:
var f = this.getField("MyCheckbox");
f.style = style.ci;
Acrobat Forms - JavaScript Object Specification
44
textColor
Type: ArrayFields: AllAccess: R/W
This property determines the foreground color of a field. I t r epresents the text color for text,
button,orlist box f ields and the check c olor for check box or radio button fields. Values are
defined the same as the fillColor property. Re fer to the Color Arrays section for information on
defining color ar rays and how values are set and used with this pr operty.
var f = this.getField("MyField");
f.textColor = color.red;
In older versions of this specification, this property was
fgColor
. The use of
fgColor
is now
discouraged but for backwards compatibility is still valid.
textFo nt
Type: StringFields: Text, Combo, List & ButtonAccess: R/W
The textFont pr operty determines the font that is used when laying out text in a text field,
combo box, list box or button. Valid fonts ar e defined as properties of the “font” object as
follows:
Text FontKeyword
Times-Romanfont.Times
Times-Boldfont.TimesB
Times- Itali cfont. Times I
Times-BoldI talicfon t.TimesBI
Helveticafont.Helv
Helvetica-Boldfont.HelvB
Helvetica-Obliquefont.HelvI
Helvetica-BoldObliquefont.HelvBI
Courierfont.Cour
Courier-Boldfont.CourB
Courier-Obliquefont.CourI
Courier-BoldObliquefont.CourBI
Symbolfont.Symbol
ZapfDingbatsfont.ZapfD
Acrobat Forms - JavaScript Object Specification
45
The f ollowing example illustrates the use of this property and the font object.
// set the font of MyField to Helvetica
var f = this.getField("MyField");
f.textFont = font.Helv;
textSize
Type: IntegerFields: AllAccess: R/W
This property determines the text size in points tha t is used in all controls. In combo box and
radio button fields, the text size determines the size of the check. Valid te xt sizes include zero
and the range from 4 to 144 inclusive. A text siz e of zero means that the largest point size that
can still f it in the field’s rectangle should be used (in multi-line text fields and buttons this is
always 12 point).
// set the text size of MyField to 28 point
var f = this.getField("MyField");
f.textSize = 28;
type
Type: StringFields: AllAccess: R
This read-only pr operty returns the type of the field as a string. Valid types that are returned
include button, chec kbox, combobox, listbox, radiobutton, and signature.
userName
Type: StringFields: AllAccess: R/W
This property returns/sets the user name of the field (short description) as a string. The user
name is intended to be used as tool tip text whenever the mouse cursor enters a field. It can
also be used as a user friendly name when generating error me ssages instead of the field name
(which can sometimes not be suitable for human consumption).
value
Type: VariousFields: All But ButtonAccess: R/W
This pr operty gets the value of the field data that the user has enter ed. Depending on the type
of the field, the value may be a string, date, or number. Typically, the value is used to create
calculated fields.
In this example, the value of the field be ing calculated is set to the sum of the oil and filter
fields and multiplied by the state sales tax. Valu e is perhaps the most important of all t he field
properties.
Field Methods
buttonImportIcon
Parameter: none
Returns: nothing
This method imports the appearance of a button from another PDF file. It prompts the user to
select a PDF file available on the system.
clearItems
Parameters: none
Returns: nothing
This method clears all the values in a list box or combo box.
// Clear the field MyListbox
var f = this.getField("MyListBox");
f.clearItems();
deleteItemAt
4.0
Parameters: [nIndex]
Returns: nothing
This function deletes an item in a combo box or a list box. The paramete r nIndex is the index of
the item in the list to delete (zero-based). If nIndex is not specified then the currently select ed
item is deleted.
var a = this.getField("MyListBox");
a.deleteItemAt();
getArray
Parameters: None
Returns: an array of fields.
Acrobat Forms - JavaScript Object Specification
47
This function returns an array of terminal children fields (i.e. fields that c an have a value) for a
parent field. This method can be particularly useful for doing field calculations in tables where
a parent field value is the s um of all of its children. To unders tand more about field name and
hierarchies, please see the section on Field Properties.
// f has 3 children: f.v1, f.v2, f.v3
var f = this.getField("f");
var a = f.getArray();
var v = 0.0;
for (j =0; j < a.length; j++)
v += a[j].value;
// v contains the sum of all the children of field "f"
getItemAt
Parameters: nIndex
Retu rns: internal value in an item in a list or combo box
This function gets the internal value of an item in a combo box or a list box. The parameter
nIndex is the index of the item in the list to obtain. If nIndex is set to -1, it returns the value of
the la st item in the list. The getItemAt function returns the exported or internal value of the
item at nIndex in the combo box or list box.
// returns value of first item in list l
var a = this.getField("MyListBox");
var v = a.getItemAt(0);
This function inserts a new item into a combo box or a list box. cNam e is the index at which to
insert the item in a list box or combo box. cExportValue is the string export value of the item
i.e. internal value of the item being inserted. nIndex is the index in the list to insert the item at.
If nIndex is 0, cName is inserted at the top of the list. If nIndex is –1, cName is inserted at the
end of the list. The default value f or nIndex is 0.
var l = this.getField("l"); /* l is a list box */
var v =l.insertItemAt("sam", "s", 0); /* inserts sam to top of list l */
setItems
4.0
Parameters: array
Acrobat Forms - JavaScript Object Specification
48
Returns: nothing
This method sets the list of items for a combo box or a list box. The single parameter necessary
to call this method m ust be an array. Each eleme nt in the ar ray must either be an object
convertible to a s tring or another array. If the e lement can be converted to a string, the user and
export values for the list item are equal to the s tring. If the element is an array it must cons ist
of two sub-elements. The first sub-element s hould be convertible to a s tring which will be used
as the us er value, the second element will be used as the export value.
var l = this.getField("ListBox");
l.setItems(["One", "Two", "Three"]);
var c = this.getField("StateBox");
c.setItems([["California", "CA"],["Massachusetts", "MA"],["Arizona", "AZ"]]);
var c = this.getField("NumberBox");
c.setItems(["1", 2, 3, ["PI", Math.PI]]);
See also the clearItems, getItemAt,andinsertItemAt field methods.
Acrobat Forms - JavaScript Object Specification
49
Global Object
The Global object is a static JavaScript object that allows you to share data between documents
and ha ve data be p ersistent acr oss sess ions. This is referred to as persistent global data.
Global data-sharing and notification a cross docume nts is done through a publish and subscribe
mechanism. This mechanism gives you the ability to monitor global data variables and report
their value changes across documents.
Global data c an be specified by adding properties to the globa l object. The property type c an
be a string, a boolean, or a number. For example, to add a variable called “volume” and to
allow all document scripts to have acces s to this variable, a scri pt would simply define it as:
global.volume = 80;
To delete a variable or a property from the global object, us e the delete operator to remove the
defined property. For more information on the reserved JavaScript ke yword delete, pleas e see
Netscape’s Ja vaScript Reference Manual. For example, to r emove the property “volume” from
the global object, call the f ollowing script:
delete global.volume
Global Object Methods
setPersisten t
parameters: cVariable, bPersist
Return s: n one
This method sets cVariable to be persistent. It requires that bPersist is s et true.Thismeansthe
cVariable will exist across invocations of Acrobat Exchange or Reader. If bPersis t is false (the
default for any global propert y) then the propert y will be acces sible across docum ents but not
across the Acrobat Viewer sessions. For example, to make the “volume” pr operty persistent
and a ccessible for other doc uments you could use:
global.setPersistent("volume", true);
Note:Persistent global data only applies to variables of type boolean, number or
string. For all persistent data the re is a 32k limit for the maximum size of
the global pers istent variables. Any data added to the string after the 32k
limit will be dropped.
It is recommended that JavaScript developers building scripts for Acrobat Forms, u tilize some
type of naming convention when specifying persistent global var iables. One suggestion is to
start all var iables with your c ompany name. For e xample, if your company name is Xyz , start
Acrobat Forms - JavaScript Object Specification
50
all variables with “xyz_”. This w ill prevent collisions with other persistent global variable
names throughout the docume nts.
Note that global variables that are persistent are recorded in the plug-in level glob.js file upon
application exit a nd re-loaded at application start. See the section on Pl ug-i n f old er level scripts
for more details.
Acrobat Forms - JavaScript Object Specification
51
this
Object
In JavaScript the special keyword “this” refers to the current objec t. In Acrobat Forms the
current object is defined as follows:
• In an object method, it is the object to which the method belongs.
• In a constructor function, it is the object being constructed.
• In a function defined at the Plug-in folder level it is undefined. It is recommended
that calling functions pass the document object to any function at this level that
needs it.
•InaDocum ent level script or Field level script it is the document object and
therefore can be used to set or get document properties and functions.
For example, assume that the following function was defined at the Plug-in folder level:
function PrintPageNum(doc)
{ /* Print the current page number to the console. */
console.println(“Page=” + doc.page);
}
The following script outputs the current page number to t he console (twice) and then prints the
page:
PrintPageNum(this);/* Must pass the document object. */
console.println(“Page=” + this.pageNum);/* Same as the previous call. */
this.print(false, this.pageNum, this.pageNum); /* Prints the current page. */
Variable and Function Name Conflicts
Variables and functions that are def ined in scripts a re parented off of the this object. For
example:
var f = this.getField(“Hello”);
is equivalent to
this.f = this.getField(“Hello”);
with the exception that the variable “f” can be garbage collected at any time after the script is
run.
If a script uses a name that conf licts with a document level pr operty or method and the this
object is the current document then a run-time error will result: Invalid or unknown property,set not possible.
The f ollowing script fragment will ge nerate such an error:
var pageNum = this.pageNum;
To avoid s uch an error, rename your variables and functions to avoid conflict:
var pNum = this.pageNum;
Acrobat Forms - JavaScript Object Specification
52
Util Object
The Util Object is a static JavaScript object that defines a number of utility methods and
convenience functions for s tring and date formatting.
Util Object Methods
printf
Parameters: cFormat
Retu rns: cRes ul t
This method will format one or more values as a string a ccording to a format string. This is
similar to the C function of the same name.
printx
Parameters: cMask, …
Returns: cResult
This method formats a source string according to a masking string. Valid mas king values are as
follows:
ValueEffect
?Copy next character.
XCopy next alphanumeric character, skipping any others.
ACopy next alpha character, sk ipping any others.
9Copy next numeric character, s k ippi ng any others.
*Copy the rest of the s ourc e string from this point on.
\Escape character.
>U pperc as e translation until further notice.
<Lowerc as e translation until further notice.
=Preserve cas e until further notice (default).
To format a s tring as a U. S. telephone number, for example, use the following script:
var v = "aaa14159697489zzz";
v = util.printx("9 (999) 999-9999", v);
console.println(v);
Acrobat Forms - JavaScript Object Specification
53
printd
Parameters: cFormat, date
Returns: cResult
Use this method to format a date accordi ng to a format str ing. Valid string format val ues are as
follows:
StringEffectExample
mmmmLong monthSeptember
mmmAbbreviated monthSept
mmNumeric month with leading zero09
mNumeric month without leading zero9
ddddLong dayWednesday
dddAbbreviated dayWed
ddNumeric dat e with lea ding z ero03
dNumeric date without leading zero3
yyyyLong year1997
yyAbbreviate Year97
HH24 hour time with leading zero09
H24 hour t im e without leadi ng zero9
hh12 hour time wi th lead ing zero09
h12 hour time wi thout leading zero9
MMminutes with leading zero08
Mminutes without leading zero8
ssseconds with leading zero05
sseconds without leadin g zero5
ttam/pm indicationam
tsingle digit am/pm indicationa
\use as an escape character
To format the curr ent date in long format, for example, you would use the following script:
var d = new Date();
console.println(util.printd("mmmm dd, yyyy", d));
Acrobat Forms - JavaScript Object Specification
54
scand
4.0
Parameters: cFormat, cDate
Returns: date object
This method converts the supplied date, cDate, into a JavaScript date objec t according to rules
of the supplied format string, cFormat. cFormat uses the same syntax as found in printd.This
routine is much more flexible than using the date constructor directly.
/* Turn the current date into a string. */
var cDate = util.printd("mm/dd/yyyy", new Date());
console.println("Today’s date: " + cDate);
/* Parse it back into a date. */
var d = util.scand("mm/dd/yyyy", cDate);
/* Output it in reverse order. */
console.println("Yet again: " + util.printd("yyyy mmm dd", d));
Note:Given a two digit year for input, scand resolves the ambiguity as follows: if
the y ear is less than 50 then it is assumed to be in the 21s t century (i.e. add
2000), if i t is greater than or equal to 50 then it is in the 20th century (add
1900). This heur istic is often known as t he Date Horizon.
Acrobat Forms - JavaScript Object Specification
55
Implementation Considerations
JavaScript Locations and Loading
JavaScripts work with Acrobat Forms on a variety of levels: the plug-in level, document level,
and field level. These levels restrict the type of processing that can occur and are loaded at
different times.
Plug-in folder
JavaScripts can work as individual files with the “.js” extension. The Acrobat Forms plug-in
looks for these f iles on the UNIX platform in the Acrobat plug-ins folder . On the Apple
Macintosh and Windows platforms, the files are in a subfolder of the plug-ins/Acroform fold er
called JavaScripts. Variables and functions that might be gener ally useful to the application
should be kept at the plug-in level.
There are some restrictions w hen writing plug-in level scripts particularly with respect to the
this Object.
The standard Acrobat Forms implementation comes with two plug-in level files: Aform .js ,
which c ontains built-in pre-canned functions and AFString.js, which contains the language
dependent strings needed by Afor m.j s.
The fileglob.js isprogrammatically generatedand containscross-session application
preferences set using the global object’s setPersistent method.
If the file Config.js is present this file can be used to customize the look of the viewer
4.0
by removing toolbar buttons and menu items (see the application m ethods hideMenuItem and
hideToolbarButton).
The plug-in level scripts are loaded in the following order: Config.js (if it ex ist s), AFString.js,
AForm.js, glob.js ( if it exists), and then all other .js files in no particular order.
level
Document
By using the Adobe Acrobat menu item Tools->Forms->Document Scripts…, the user ca n add,
modify, or delete document level scripts. T hese scripts should be function definitions that are
generally useful to the document but are not applicable outside the document. Doc ument level
scripts are executed af ter the document has opened and after the plug-in level scripts ar e
loaded. Document level scripts ar e stored within the PDF document. Th erefore, the forms
programmer s hould make every effort to package scripts as effectively as possible.
Acrobat Forms - JavaScript Object Specification
level
56
Field
level
The user can add scripts to a form f ield definition using a dialog box in the form editing tool.
(seeEvent Processing section below). These scripts are executed as the events occur (e.g.
mouse up or calculate). Scripts that are field specific should be created at this level. Usually
these scripts validate, format, or calculate field values.
Unlike plug-in folder scripts, document level and field level scripts are stored within the PDF
document and therefore the forms programmer should make every effort to package his scripts
as effectively as possible (e.g. code reuse) at the various levels for performance and file size
reasons.
Form Field Hierarchies
Form fields typically have names like FirstName, LastName, etc. This naming convention is
referred to as flat names. For many form applications, this flat hierarchy of names is sufficient
and works well. The problem with using flat names is that there is no association between the
fields.
Form field names can be more useful by creating a hierarchal structure. For example, if we
change FirstName to Name.First and LastName to Name.Last we form a tree of fields. The
period (‘.’) separator used in Acrobat Forms and denotes a hierarchy shift. The Name portion
of these fields is the parent, and First and Last become the children. While there is no limit to
the depth a hierarchical name can be constructed it is important that the hierarchy remain
manageable.
This hierarchy can be useful in a number of ways. It can speed up authoring and ease
manipulation of groups of fields in JavaScript. In addition, a form field hierarchy can improve
the performance of forms applications when there are many fields in the document.
Form Field Hierarchies with JavaScript
Using our original flat names FirstName, MiddleName and LastName, imagine that we want to
change the background color of these fields to yellow (to indicate missing data, or emphasize
an important point). We would need two lines of JavaScript code for each field:
var name = this.getField("FirstName");
name.fillColor = color.yellow;
name = this.getField("MiddleName");
name.fillColor = color.yellow;
name = this.getField("LastName");
name.fillColor = color.yellow;
With our hierarchy of Name.First,Name.Middle and Name.Last above (and perhaps,
Name.Title if used), we can change the background color of these fields with just two lines of
code instead of six:
Acrobat Forms - JavaScript Object Specification
57
var name = this.getfield("Name");
name.fillColor = color.yellow
When using this hierarchy within a JavaScript, remember you can only change appearance
related properties of the parent field and that appear ance changes propagate to all children.
You ca nnot change the field’s value. For example if you try the following script:
var name = this.getField("Name");
name.value = "Lincoln";
the script will fail. Name is considered a parent field. You c an only change the value of
terminal fields (i.e. a field that does not have children like Last or Fir st ). T he following script
executes correctly:
var first = this.getField("Name.First");
var last = this.getField("Name.Last");
first.value = "Abraham";
last.value = "Lincoln";
Working With The Date Object
This section discusses the use of D ate objects within Acrobat. The reader should be familiar
with the Java Script Date object and the Util Object functions that process dates . JavaScript Date
objects are actually an object c ontaining both a date and time. All references to date in this
section refer to the date-time combination.
Note:All date manipulations in JavaScript, including those methods that have
been documented in this specification are Year 2000 (Y2K) compliant.
Converting a Date to a String
Acrobat Forms provides se veral date related methods in addition to the ones provided by the
JavaScript D ate object. These methods are the preferred method of converting between Date
objects and st rings. Because of Acrobat Forms' ability to handle dates in ma ny formats, the
Date object does not always handle these conversions correctly.
To convert a Date object into a s tring, the printd method of the Util Object is used. Unlike the
built-in conversion of the Date object to a string, printd allows an exact s pecification of how
the date should be formatted.
/* Example of util.printd */
var d = new Date(); /* Create a Date object containing the current date. */
/* Create some strings from the Date object with various formats with
** util.printd */
var s1 = util.printd("mm/dd/yy", d);
Acrobat Forms - JavaScript Object Specification
58
var s2 = util.printd("yy/m/d", d);
var s3 = util.printd("mmmm dd, yyyy", d);
var s4 = util.printd("dd-mmm-yyyy", d);
/* print these strings to the console */
console.println("Format mm/dd/yy looks like: " + s1);
console.println("Format yy/m/d looks like:"+s2);
console.println("Format mmmm dd, yyyy looks like: " + s3);
console.println("Format dd-mmm-yyyy looks like: " + s4);
The output of this script would look like:
Format mm/dd/yy looks like: 01/15/99
Format yy/mm/dd looks like: 99/1/15
Format mmmm dd, yyyy looks like: January 15, 1999
Format dd-mmm-yyyy looks like: 15-Jan-1999
Note:Given the relative closeness of the new millenium and the ever increasing
length of the human lifespan, it is advised to output dates with a four digit
year to avoid ambiguity.
Converting a String to a Date
To convert a string into a Date object the scand method of the Util Ob je ct, i s used. It accepts a
format s tring that it uses as a hint as to the or der of the year, month, and day in the input
string.
/* Example of util.scand */
/* Create some strings containing the same date in differing formats. */
var s1 = "03/12/97";
var s2 = "80/06/01";
var s3 = "December 6, 1948";
var s4 = "Saturday 04/11/76";
var s5 = "Tue. 02/01/30";
var s6 = "Friday, Jan. the 15th, 1999";
/* Convert the strings into Date objects using util.scand */
var d1 = util.scand("mm/dd/yy", s1);
var d2 = util.scand("yy/mm/dd", s2);
var d3 = util.scand("mmmm dd, yyyy", s3);
var d4 = util.scand("mm/dd/yy", s4);
var d5 = util.scand("yy/mm/dd", s5);
var d6 = util.scand("mmmm dd, yyyy", s6);
/* Print the dates to the console using util.printd */
console.println(util.printd("mm/dd/yyyy", d1));
console.println(util.printd("mm/dd/yyyy", d2));
console.println(util.printd("mm/dd/yyyy", d3));
Unlike the date constructor (new Date(...)), scand is rather forgiving in terms of the string
passed to it.
Note:Given a two digit year for input, scand resolves the ambiguity as follows: if
the y ear is less than 50 then it is assumed to be in the 21s t century (i.e. add
2000), if i t is greater than or equal to 50 then it is in the 20th century (add
1900). This heur istic is often known as t he Date Horizon.
Date Arithmetic
It is often useful to do arithmetic on dates to determine things like the time interval between
two dat es or what the date will be sever al days or weeks in the future. The JavaScr ipt Date
object pr ovides several ways to do this. The simplest and possibly mos t easily understood
method is by manipulating dates in terms of their numeric representation. Internally, J avaScript
dates are s tored as the number of milliseconds ( one thousand milliseconds is one whole
second) since a fixed date a nd time. This number c an be retrieved through the valueOf method
of the D ate object. The Date c onstructor allows the construction of a new da te from this
number.
/* Example of date arithmetic. */
/* Create a Date object with a definite date. */
var d1 = util.scand("mm/dd/yy", "4/11/76");
/* Create a date object containing the current date. */
var d2 = new Date();
/* Number of seconds difference. */
var diff = (d2.valueOf() - d1.valueOf()) / 1000;
/* Print some interesting stuff to the console. */
console.println("It has been " + diff + " seconds since 4/11/1976");
console.println("It has been"+diff/60+"minutes since 4/11/1976");
console.println("It has been " + (diff / 60) / 60 + " hours since 4/11/1976");
console.println("It has been " +
Acrobat Forms - JavaScript Object Specification
60
((diff / 60) / 60) / 24 + " days since 4/11/1976");
console.println("It has been " +
(((diff / 60) / 60) / 24) / 365 + " years since 4/11/1976");
The output of this script would look something like:
It has been 718329600 seconds since 4/11/1976
It has been 11972160 minutes since 4/11/1976
It has been 199536 hours since 4/11/1976
It has been 8314 days since 4/11/1976
It has been 22.7780821917808 years since 4/11/1976
The f ollowing example shows the addition of dates.
/* Example of date arithmetic. */
/* Create a date object containing the current date. */
var d1 = new Date();
/* num contains the numeric representation of the current date. */
var num = d1.valueOf();
/* Add thirteen days to today’s date. */
/* 1000 ms / sec; 60 sec / min; 60 min / hour; 24 hours / day; 13 days */
num+=1000*60*60*24*13;
/* Create our new date that is 13 days ahead of the current date. */
var d2 = new Date(num);
/* Print out the current date and our new date using util.printd */
console.println("It is currently: " + util.printd("mm/dd/yyyy", d1));
console.println("In 13 days, it will be: " + util.printd("mm/dd/yyyy", d2));
The output of this script would look something like:
It is currently: 01/15/1999
In 13 days, it will be: 01/28/1999
Acrobat Forms and Security
Security in Acrobat takes on the f orm of restricting acce ss to a document, r estrictin g
permissions f or a form once it has been opened, and digital signatures.
Restricting Access
If the author desires to restrict access to the form in its entirety then the standard security
model in Acrobat can be selecte d and an open password de fined that requires a user t o type in a
password before opening the form. Other security handlers exist and a re provided by thir d
party developers as plug-ins and may also be useful. E.g. using a public/private key
Acrobat Forms - JavaScript Object Specification
61
infrastructure to lock a form for a particular set of people or allowing a form to e xpire after a
certain time period.
The ability to set a use r password is accessed us ing the Save As function by choosing the
appropriate security handler and configuring its settings.
Restricting Permissions
The standard security model in Acrobat is accessible at document save time and allows you to
set the following restrictions on the document: printing, changing the document, selecting text
and graphics , and adding and changing annotations and form fields.
Once a f orm has been authored it is often useful to lock the form so that it may be filled in but
cannot be tamper ed with using the forms tool. For example, after authoring a form may be
posted on a Web site. I n order to preserve the form integrity it needs to be shielded from any
changes to its f ormulae or internal data routines.
If the changing the document r estrictio n is selected, the user c an fill-in form fields and add
annotations but cannot author or modify form f ields or change the bac kground text using the
TouchUp plug-in.
In addition, once a form has been filled in, it i s often desirable to lock the entire document s o
that it cannot be cha nged wha tsoever. In filling out a tax or other sensitive form, the user may
wish to save the doc ument so that no further changes to the document are allowed. In order to
disallow both fill-in a nd authoring, the changing the document and the adding and changingannotations and form fields restrictions m ust be selected.
Digital S ignatures
Although thes e form f ields do not restrict access or per missions, they do allow an author or
user to verify that a document has not been changed after a signature has been applied.
An author may digitally sign a form thus signifying that it has been released for fill-in. A user
can verify the signature to make sure that the form has not been tampered with and is thus
Acrobat Forms - JavaScript Object Specification
62
“official”. A blind s ignature ( signed without any appearance) is often use ful in this situation
and c an be created via the pull right menu in the signatures pane.
After fill-in a user can also sign the document either by us ing the signing tool or filling in a
pre-authored signature field, thus ens uring that the form undergoes no further changes without
detection.
Working with Signature Fields
4.0
Signature fields allow the user to digitally sign a document. Once a signature is applied to the
document a ny subsequent changes to the document will cause the signature to indicate that the
“Document has been changed after signing”.
A signature field’s value is read-only. An unsigned signature has a null value. O nce the field
has been signed its value is non-null.
When crafting a custom script for when the signature field i s signed remember to allow for
resetting the form (i.e. the field’s value is set to null). For e xample, imagine a form where
upon signing a signature field that all fields whose names starts with “A” are locked and all
fields whose names start with “B” are locked. We might start with a script fragment, to be
executed at s ignature time, looking something like this :
/* This example is incorrect. */
var f = this.getField("A");
/* Lock all A fields. */
f.readOnly = true;
f = this.getField("B");
/* Unlock all B fields. */
f.readOnly = false;
This is a typical opera tion for many forms. T his script is incor rect a nd when the form is reset
it will lock a nd unlock the wrong fields. Instead, it should check the value of the signing event
and r eact accordingly:
var bLock = (event.value != "");
var f = this.getField("A");
/* Lock A on sign, unlock on reset. */
f.readOnly = bLock;
f = this.getField("B");
/* Unlock B on sign, lock on reset. */
f.readOnly = !bLock;
There is a convenience routine available for your use called AFSignatureLock() in AForm.js
(see JavaScript Locations and Loading) that performs the programmatic equivalent of the simple
locking user interface in the signature properties dialog. This allows you to e asily lock and
unlock all fields, a par ticular list of fields, or all fields but those specified. The example is recoded using this convenienc e routine below:
var bLock = (event.value != "");
AFSignatureLock(this, "THESE", "A", bLock);
Acrobat Forms - JavaScript Object Specification
63
AFSignatureLock(this, "THESE", "B", !bLock);
See the comments in AForm.js for more details.
Acrobat Forms - JavaScript Object Specification
64
Loading...
+ hidden pages
You need points to download manuals.
1 point = 1 manual.
You can buy points or you can get point for every manual you upload.