Developing Acrobat Applications Using JavaScript Js Developer Guide

js_developer_guide

User Manual: Pdf

Open the PDF directly: View PDF PDF.
Page Count: 220

DownloadDeveloping Acrobat Applications Using JavaScript Js Developer Guide
Open PDF In BrowserView PDF
bc

Developing Acrobat® Applications
Using JavaScript™

Adobe® Acrobat® SDK
November 2006

Version 8.0

© 2006 Adobe Systems Incorporated. All rights reserved.
Adobe® Acrobat® SDK 8.0 Developing Acrobat Applications Using JavaScript for Microsoft® Windows® and Mac OS®.
Edition 1.0, November 2006
If this guide is distributed with software that includes an end user agreement, this guide, as well as the software described in it, is furnished
under license and may be used or copied only in accordance with the terms of such license. Except as permitted by any such license, no part
of this guide may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, electronic, mechanical, recording,
or otherwise, without the prior written permission of Adobe Systems Incorporated. Please note that the content in this guide is protected
under copyright law even if it is not distributed with software that includes an end user license agreement.
The content of this guide is furnished for informational use only, is subject to change without notice, and should not be construed as a
commitment by Adobe Systems Incorporated. Adobe Systems Incorporated assumes no responsibility or liability for any errors or
inaccuracies that may appear in the informational content contained in this guide.
Please remember that existing artwork or images that you may want to include in your project may be protected under copyright law. The
unauthorized incorporation of such material into your new work could be a violation of the rights of the copyright owner. Please be sure to
obtain any permission required from the copyright owner.
Any references to company names and company logos in sample material are for demonstration purposes only and are not intended to refer
to any actual organization.
Adobe, the Adobe logo, Acrobat, After Effects, FrameMaker, Illustrator, LiveCycle, Photoshop, PostScript and Reader are either registered
trademarks or trademarks of Adobe Systems Incorporated in the United States and/or other countries.
Apple and Mac OS are trademarks of Apple Computer, Inc., registered in the United States and other countries.
JavaScript is a trademark or registered trademark of Sun Microsystems, Inc. in the United States and other countries.
Microsoft and Windows are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries.
All other trademarks are the property of their respective owners.
Adobe Systems Incorporated, 345 Park Avenue, San Jose, California 95110, USA.
Notice to U.S. Government End Users. The Software and Documentation are “Commercial Items,” as that term is defined at 48 C.F.R. §2.101,
consisting of “Commercial Computer Software” and “Commercial Computer Software Documentation,” as such terms are used in 48 C.F.R.
§12.212 or 48 C.F.R. §227.7202, as applicable. Consistent with 48 C.F.R. §12.212 or 48 C.F.R. §§227.7202-1 through 227.7202-4, as applicable,
the Commercial Computer Software and Commercial Computer Software Documentation are being licensed to U.S. Government end users
(a) only as Commercial Items and (b) with only those rights as are granted to all other end users pursuant to the terms and conditions herein.
Unpublished-rights reserved under the copyright laws of the United States. Adobe Systems Incorporated, 345 Park Avenue, San Jose, CA
95110-2704, USA. For U.S. Government End Users, Adobe agrees to comply with all applicable equal opportunity laws including, if
appropriate, the provisions of Executive Order 11246, as amended, Section 402 of the Vietnam Era Veterans Readjustment Assistance Act of
1974 (38 USC 4212), and Section 503 of the Rehabilitation Act of 1973, as amended, and the regulations at 41 CFR Parts 60-1 through 60-60,
60-250, and 60-741. The affirmative action clause and regulations contained in the preceding sentence shall be incorporated by reference.

Contents
Contents ....................................................................................................................................... 3
List of Examples ......................................................................................................................... 10
Preface ........................................................................................................................................ 12
What’s in this guide? ...................................................................................................................................................................12
Who should read this guide? ...................................................................................................................................................12
About the sample scripts...........................................................................................................................................................12
Related documentation .............................................................................................................................................................13

1

Introduction ............................................................................................................................... 14
Overview..........................................................................................................................................................................................14
Reading the JavaScript for Acrobat API Reference ..........................................................................................................15
Object summary ...........................................................................................................................................................................16
app...............................................................................................................................................................................................16
Doc ..............................................................................................................................................................................................16
dbg ..............................................................................................................................................................................................17
console.......................................................................................................................................................................................17
global..........................................................................................................................................................................................17
util................................................................................................................................................................................................18
dialog..........................................................................................................................................................................................18
security.......................................................................................................................................................................................18
SOAP ...........................................................................................................................................................................................18
search .........................................................................................................................................................................................18
ADBC...........................................................................................................................................................................................19
event...........................................................................................................................................................................................19
JavaScript applications...............................................................................................................................................................19

2

Tools ........................................................................................................................................... 21
Using the JavaScript Debugger console..............................................................................................................................21
Opening the console ............................................................................................................................................................22
Executing JavaScript .............................................................................................................................................................22
Formatting code.....................................................................................................................................................................22
Enabling JavaScript ...............................................................................................................................................................22
Debugging with the JavaScript Console.......................................................................................................................24
Using a JavaScript editor ...........................................................................................................................................................24
Specifying the default JavaScript editor ..............................................................................................................................25
Using an external editor.............................................................................................................................................................26
Additional editor capabilities ............................................................................................................................................26
Specifying additional capabilities to your editor .......................................................................................................26
Saving and closing a file with a syntax error................................................................................................................28
Using the Debugger with Adobe Reader ............................................................................................................................28
Enabling the JavaScript Debugger ........................................................................................................................................29

3

Adobe Acrobat SDK
Developing Acrobat Applications Using JavaScript

2

Contents
4

Tools (Continued)
JavaScript Debugger...................................................................................................................................................................30
Main groups of controls.......................................................................................................................................................30
Debugger View windows....................................................................................................................................................31
Debugger buttons .................................................................................................................................................................32
Debugger Scripts window ..................................................................................................................................................33
Call Stack list ............................................................................................................................................................................35
Inspect details window ........................................................................................................................................................35
Coding styles and breakpoints ...................................................................................................................................37
Listing breakpoints .........................................................................................................................................................38
Using conditional breakpoints ...................................................................................................................................38
Starting the Debugger .........................................................................................................................................................38
Final notes ................................................................................................................................................................................39

3

JavaScript Contexts in Acrobat ................................................................................................ 40
The concept of a JavaScript event .........................................................................................................................................40
About contexts..............................................................................................................................................................................41
Folder level ...............................................................................................................................................................................42
Document level ......................................................................................................................................................................43
Page level..................................................................................................................................................................................43
Field level ..................................................................................................................................................................................44
Batch level ................................................................................................................................................................................44
Privileged versus non-privileged context ...........................................................................................................................45
Executing privileged methods in a non-privileged context...................................................................................45
Executing privileged methods through the menu....................................................................................................47
Executing privileged methods in a certified document ..........................................................................................48

4

Creating and Modifying PDF Documents ................................................................................ 49
Creating and modifying PDF files...........................................................................................................................................49
Combining PDF documents...............................................................................................................................................51
Combining and extracting files.........................................................................................................................................51
Creating file attachments....................................................................................................................................................52
Cropping and rotating pages ............................................................................................................................................55
Cropping pages................................................................................................................................................................55
Rotating pages..................................................................................................................................................................56
Extracting, moving, deleting, replacing, and copying pages ................................................................................56
Adding watermarks and backgrounds...........................................................................................................................58
Converting PDF documents to XML format .......................................................................................................................59

5

Print Production ........................................................................................................................ 60
Setting print options ...................................................................................................................................................................60
Printing PDF documents............................................................................................................................................................62
Silent printing..........................................................................................................................................................................63
Printing comments and forms ..........................................................................................................................................64
Booklet printing......................................................................................................................................................................64
Setting advanced print options........................................................................................................................................65
Specifying output settings ...........................................................................................................................................65
Specifying marks and bleeds.......................................................................................................................................65
Setting PostScript options............................................................................................................................................65
Setting font options........................................................................................................................................................65

Adobe Acrobat SDK
Developing Acrobat Applications Using JavaScript

6

Contents
5

Using JavaScript in Forms......................................................................................................... 67
Forms essentials............................................................................................................................................................................67
About PDF forms....................................................................................................................................................................67
Elements of Acrobat forms...........................................................................................................................................68
Guidelines for creating a new form...........................................................................................................................68
Creating Acrobat form fields..............................................................................................................................................69
Setting Acrobat form field properties ............................................................................................................................70
Field properties ................................................................................................................................................................71
Button fields ......................................................................................................................................................................72
Check box fields ...............................................................................................................................................................74
Combo box fields.............................................................................................................................................................75
List box fields.....................................................................................................................................................................79
Radio button fields..........................................................................................................................................................81
Signature fields.................................................................................................................................................................82
Text fields............................................................................................................................................................................83
Validation scripts..............................................................................................................................................................84
Calculation script .............................................................................................................................................................85
Task-based topics.........................................................................................................................................................................86
Highlighting required form fields ....................................................................................................................................86
Making a form fillable...........................................................................................................................................................87
Setting the hierarchy of form fields.................................................................................................................................87
Creating forms ........................................................................................................................................................................88
Positioning form fields...................................................................................................................................................88
Duplicating form fields ..................................................................................................................................................89
Creating multiple form fields ......................................................................................................................................90
Defining the tabbing order ................................................................................................................................................91
Defining form field calculation order .............................................................................................................................91
Making PDF forms web-ready ...........................................................................................................................................91
Creating a submit button .............................................................................................................................................92
Creating a reset form button.......................................................................................................................................92
Defining CGI export values ..........................................................................................................................................92
Importing and exporting form data................................................................................................................................92
Emailing completed forms .................................................................................................................................................93
Use date objects .....................................................................................................................................................................93
Date arithmetic .......................................................................................................................................................................95
Defining global variables in JavaScript ..........................................................................................................................96
Enable the global object security policy .................................................................................................................96
Setting and getting a global variable.......................................................................................................................96
Deleting global variables ..............................................................................................................................................97
Making global variables persistent ...........................................................................................................................97
Querying an Acrobat form field value in another open form..........................................................................97
Global object security policy .......................................................................................................................................98
Intercepting keystrokes in an Acrobat form.................................................................................................................98
Constructing custom colors ...............................................................................................................................................99
Prompting the user for a response..................................................................................................................................99
Fetching an URL from JavaScript .....................................................................................................................................99
Creating special rollover effects .......................................................................................................................................99

Adobe Acrobat SDK
Developing Acrobat Applications Using JavaScript

6

Contents
6

Using JavaScript in Forms (Continued)
Introduction to XML forms architecture (XFA) ..................................................................................................................99
Enabling dynamic layout and rendering.................................................................................................................... 100
Growable form fields ......................................................................................................................................................... 100
Variable-size rows and tables ......................................................................................................................................... 100
Multiple customized forms within a form based on user input......................................................................... 100
Handling image data ......................................................................................................................................................... 100
Dynamic tooltips ................................................................................................................................................................. 100
XFA-specific JavaScript methods .................................................................................................................................. 101
JavaScript methods not enabled in XML Forms ...................................................................................................... 105
ADO support for Windows .............................................................................................................................................. 105
Detecting XML forms and earlier form types............................................................................................................ 105
Saving form data as XML or XML Data Package (XDP) .......................................................................................... 106
Global submit ....................................................................................................................................................................... 106
Making forms accessible......................................................................................................................................................... 107
Text-to-speech ..................................................................................................................................................................... 107
Tagging annotations ......................................................................................................................................................... 108
Document metadata.......................................................................................................................................................... 109
Short description................................................................................................................................................................. 109
Setting tab order ................................................................................................................................................................. 109
Reading order....................................................................................................................................................................... 109
Using JavaScript to secure forms......................................................................................................................................... 110

7

Review, Markup, and Approval ..............................................................................................112
Working with comments using JavaScript....................................................................................................................... 112
Annotation types ................................................................................................................................................................ 112
Getting annotation data................................................................................................................................................... 113
Adding comments with JavaScript............................................................................................................................... 114
Setting comment properties .......................................................................................................................................... 114
Online collaboration essentials ............................................................................................................................................ 115
Reviewing documents with additional usage rights ............................................................................................. 115
Emailing PDF documents................................................................................................................................................. 116
JavaScript-based collaboration driver......................................................................................................................... 116
Spell-checking in comments and forms ..................................................................................................................... 118
Setting spelling preferences..................................................................................................................................... 118
Adding words to a dictionary................................................................................................................................... 119
Approval................................................................................................................................................................................. 119
Managing comments............................................................................................................................................................... 119
Selecting, moving, and deleting comments ............................................................................................................. 119
Using the comments list................................................................................................................................................... 120
Changing the status of comments......................................................................................................................... 120
Changing the appearance of comments ............................................................................................................. 120
Sorting comments .............................................................................................................................................................. 120
Showing and hiding comments.............................................................................................................................. 121
Exporting and importing comments ........................................................................................................................... 121
Aggregating comments for use in Excel .................................................................................................................... 121
Comparing comments in two PDF documents ....................................................................................................... 121
Extracting comments in a batch process ................................................................................................................... 122

Adobe Acrobat SDK
Developing Acrobat Applications Using JavaScript

7

Contents
7

Review, Markup, and Approval (Continued)
Approving documents using stamps (Japanese workflows) .................................................................................... 122
Setting up a Hanko approval workflow ...................................................................................................................... 122
Participating in a Hanko approval workflow............................................................................................................. 122
Installing and customizing Hanko stamps .......................................................................................................... 123
Creating custom Inkan stamps ................................................................................................................................ 123
Deleting custom stamps ............................................................................................................................................ 123

8

Working with Digital Media in PDF Documents....................................................................124
Media players: control, settings, renditions, and events............................................................................................. 124
Accessing a list of active players.................................................................................................................................... 125
Specifying playback settings .......................................................................................................................................... 125
Monitors........................................................................................................................................................................................ 127
Integrating media into documents .................................................................................................................................... 128
Controlling multimedia through a rendition action .............................................................................................. 130
Controlling multimedia with a Run a JavaScript action........................................................................................ 131
Adding and editing renditions....................................................................................................................................... 133
Setting multimedia preferences .......................................................................................................................................... 134

9

Modifying the User Interface ..................................................................................................135
Adding toolbar buttons and menu items ........................................................................................................................ 135
Adding navigation to PDF documents.............................................................................................................................. 137
Thumbnails............................................................................................................................................................................ 138
Creating page thumbnails......................................................................................................................................... 138
Adding page actions with page thumbnails ...................................................................................................... 138
Bookmarks ............................................................................................................................................................................. 139
Creating bookmarks .................................................................................................................................................... 139
Managing bookmarks ................................................................................................................................................. 140
Creating a bookmark hierarchy ............................................................................................................................... 140
Links ......................................................................................................................................................................................... 141
Adding and removing web links from text ......................................................................................................... 142
Adding and removing links....................................................................................................................................... 142
Defining the appearance of a link .......................................................................................................................... 143
Opening links ................................................................................................................................................................. 144
Opening file attachments.......................................................................................................................................... 144
Using destinations........................................................................................................................................................ 144
Using actions for special effects .................................................................................................................................... 145
Highlighting form fields and navigational components ...................................................................................... 145
Setting up a presentation ................................................................................................................................................ 146
Defining the initial view in full screen view ........................................................................................................ 146
Defining an initial view............................................................................................................................................... 147
Numbering pages ............................................................................................................................................................... 149
Creating buttons ................................................................................................................................................................. 150
Working with PDF layers......................................................................................................................................................... 150
Navigating with layers....................................................................................................................................................... 151
Editing the properties of PDF layers............................................................................................................................. 151
Reordering layers ................................................................................................................................................................ 152

Adobe Acrobat SDK
Developing Acrobat Applications Using JavaScript

Contents
8

10 Acrobat Templates ..................................................................................................................153
The role of templates in PDF form architecture ............................................................................................................. 153
Spawning templates ................................................................................................................................................................ 153
Dynamic form field generation...................................................................................................................................... 154
Dynamic page generation ............................................................................................................................................... 154
Template syntax and usage ............................................................................................................................................ 154

11 Search and Index Essentials....................................................................................................157
Searching for text in PDF documents ................................................................................................................................ 157
Finding words in an PDF document............................................................................................................................. 158
Using advanced search options .............................................................................................................................. 159
Searching across multiple PDF documents............................................................................................................... 159
Searching all PDF files in a specific location ....................................................................................................... 160
Using advanced search options for multiple document searches ............................................................. 160
Searching PDF index files........................................................................................................................................... 160
Using Boolean queries ................................................................................................................................................ 160
Indexing multiple PDF documents ..................................................................................................................................... 161
Creating, updating, or rebuilding indexes................................................................................................................. 161
Searching metadata ................................................................................................................................................................. 162

12 Security.....................................................................................................................................163
Security essentials ..................................................................................................................................................................... 163
Methods for adding security to PDF documents .................................................................................................... 163
Passwords and restrictions........................................................................................................................................ 163
Certifying documents ................................................................................................................................................. 163
Encrypting files using certificates ........................................................................................................................... 165
Security policies ............................................................................................................................................................ 166
Secure forms................................................................................................................................................................... 166
Digitally signing PDF documents ........................................................................................................................................ 166
Signing a PDF document ................................................................................................................................................. 166
The security handler object............................................................................................................................................. 166
The SignatureInfo object ........................................................................................................................................... 167
Applying the signature............................................................................................................................................... 167
Clearing a digital signature from a signature field ........................................................................................... 168
Getting signature information from another user.................................................................................................. 168
Removing signatures......................................................................................................................................................... 168
Certifying a document ...................................................................................................................................................... 168
Validating signatures......................................................................................................................................................... 169
Setting digital signature properties with seed values........................................................................................... 169
Adding security to PDF documents.................................................................................................................................... 170
Adding passwords and setting security options ..................................................................................................... 170
Adding usage rights to a document ............................................................................................................................ 170
Encrypting PDF files for a list of recipients ................................................................................................................ 171
Encrypting PDF files using security policies .............................................................................................................. 173
Adding security to document attachments .............................................................................................................. 175

Adobe Acrobat SDK
Developing Acrobat Applications Using JavaScript

Contents
9

12 Security (Continued)
Digital IDs and certification methods ................................................................................................................................ 175
Digital IDs............................................................................................................................................................................... 176
About digital ID providers ......................................................................................................................................... 176
Creating a digital ID (default certificate security) ............................................................................................. 177
Using digital IDs (default certificate security)..................................................................................................... 179
Managing digital IDs (Windows certificate security) ....................................................................................... 179
Managing digital ID certificates..................................................................................................................................... 180
Sharing digital ID certificates ................................................................................................................................... 180
Building a list of trusted identities.......................................................................................................................... 181
Checking information on certificates .................................................................................................................... 181
Task based topics ...................................................................................................................................................................... 182
Disallowing changes in scripts....................................................................................................................................... 182
Hiding scripts........................................................................................................................................................................ 182

13 Rights-Enabled PDF Files ........................................................................................................183
Additional usage rights........................................................................................................................................................... 183
LiveCycle Reader Extensions ................................................................................................................................................. 184
Writing JavaScript for Adobe Reader ................................................................................................................................. 184
Enabling collaboration ............................................................................................................................................................ 186

14 Interacting with Databases.....................................................................................................188
About ADBC ................................................................................................................................................................................ 188
Establishing an ADBC connection....................................................................................................................................... 189
Executing SQL statements ..................................................................................................................................................... 191

15 SOAP and Web Services ..........................................................................................................193
Using SOAP and web services .............................................................................................................................................. 193
Using a WSDL proxy to invoke a web service ........................................................................................................... 194
Synchronous and asynchronous information exchange ..................................................................................... 195
Establishing a synchronous connection............................................................................................................... 196
Asynchronous web service calls.............................................................................................................................. 198
Using document/literal encoding................................................................................................................................. 199
Exchanging file attachments and binary data.......................................................................................................... 200
Converting between string and readstream information.................................................................................... 201
Accessing SOAP version information .......................................................................................................................... 201
Accessing SOAP header information........................................................................................................................... 201
Authentication ..................................................................................................................................................................... 202
Error handling ...................................................................................................................................................................... 202
DNS service discovery.............................................................................................................................................................. 203
Managing XML-based information..................................................................................................................................... 205
Workflow applications............................................................................................................................................................. 206

16 Interfacing with 3D JavaScript ...............................................................................................207
Basic concepts ............................................................................................................................................................................ 207
Getting the Annot3D object of the 3D annotation....................................................................................................... 208
Annot3D properties ........................................................................................................................................................... 208
Acquiring the JavaScript 3D engine............................................................................................................................. 209
Using the default script of a 3D annotation .................................................................................................................... 210
Initializing upon activation .................................................................................................................................................... 211

Index .........................................................................................................................................213

List of Examples
Example 2.1
Example 3.1
Example 4.1
Example 4.2
Example 4.3
Example 4.4
Example 4.5
Example 4.6
Example 4.7
Example 5.1
Example 5.2
Example 6.1
Example 6.2
Example 6.3
Example 6.4
Example 6.5
Example 6.6
Example 6.7
Example 6.8
Example 6.9
Example 8.1
Example 8.2
Example 8.3
Example 8.4
Example 8.5
Example 8.6
Example 8.7
Example 9.1
Example 9.2
Example 9.3
Example 9.4
Example 9.5
Example 9.6
Example 9.7
Example 10.1
Example 12.1

Test a regular expression in the JavaScript Debugger Console .....................................................................24
Executing privileged methods....................................................................................................................................46
Creating a document with content...........................................................................................................................50
Creating a new document from two other documents ....................................................................................51
Combining several PDF files ........................................................................................................................................51
Combining several files of different formats .........................................................................................................52
Extracting and saving pages........................................................................................................................................52
Saving form data to and reading form data from an attachment .................................................................53
Accessing an XML attachment using E4X...............................................................................................................54
Set up booklet printing for right-side binding of text and print ....................................................................64
Print booklet in duplex mode, printing only the front pages .........................................................................64
Custom script for a combo box ..................................................................................................................................78
Accessing a list from another field ............................................................................................................................80
Accessing individual radio button widgets ...........................................................................................................81
Counting the number of widgets in a radio button field..................................................................................81
Inputting numbers and checking the range in a text field...............................................................................84
Calculating the average of several text fields........................................................................................................85
Highlighting required fields.........................................................................................................................................86
Inserting navigation buttons on each page ..........................................................................................................89
Detecting and classifying XML forms in batch................................................................................................... 105
Customizing the number of repetitions for playback ..................................................................................... 127
Running openPlayer with settings and events as a rendition action ........................................................ 130
Play a clip in full screen............................................................................................................................................... 131
Playing a rendition in a screen annotation from a form button.................................................................. 132
Playing a media clip from a URL.............................................................................................................................. 132
Playing a media clip from a file................................................................................................................................ 133
Playing a sound clip from a URL.............................................................................................................................. 133
Adding a menu item.................................................................................................................................................... 135
Installing and uninstalling a toolbar...................................................................................................................... 136
Add navigation links to the document................................................................................................................. 142
Setting full screen preferences and resetting them......................................................................................... 146
Adding page transitions............................................................................................................................................. 147
Creating a rollover effect ........................................................................................................................................... 150
Toggling a PDF layer.................................................................................................................................................... 151
Gathering personal data using templates........................................................................................................... 155
Certification signature ................................................................................................................................................ 170

10

Adobe Acrobat SDK
Developing Acrobat Applications Using JavaScript

Example 16.1
Example 16.2
Example 16.3
Example 16.4

List of Examples
11

Assigning a name to a 3D annotation................................................................................................................... 208
Rotating a named object in a 3D model .............................................................................................................. 209
Setting the render mode of a 3D model .............................................................................................................. 210
Setting the background color of the canvas on activation ........................................................................... 211

Preface
This guide shows how you can use JavaScript™ to develop and enhance standard Adobe® Acrobat®
workflows, such as:
●

Printing and viewing

●

Spell-checking

●

Stamping and watermarking

●

Managing document security and rights

●

Accessing metadata

●

Facilitating online collaboration

●

Creating interactive forms

●

Customizing interaction with web Services

●

Interacting with databases

●

Accessing the 3D JavaScript engine

What’s in this guide?
This guide contains detailed information about JavaScript for Acrobat, extensive examples which
demonstrate its capabilities, as well as descriptions of the use of the SDK tools.

Who should read this guide?
It is assumed that you are an Acrobat solution provider or power user, and that you possess basic
competency with JavaScript. If you would also like to take full advantage of Acrobat’s web-based features,
you will find it useful to understand XML, XSLT, SOAP, and web services. Finally, if you would like to use
Acrobat’s database capabilities, you will need a basic understanding of SQL.
This guide assumes that you are familiar with the non-scripting elements of the Acrobat 8 user interface
that are described in Acrobat’s accompanying online help documentation. To run the examples in this
guide, you will need to use Acrobat 8 Professional.

About the sample scripts
This guide includes examples that give you an opportunity to work directly with JavaScript for Acrobat. If
you plan to work with any of the examples, configure your computer as follows:
1. Install Acrobat Professional on your Microsoft® Windows® or Mac OS workstation.
2. Use the same directory for all the scripts, PDF documents and other files.
3. Extract the Zip files in the Acrobat SDK to a local directory.

12

Adobe Acrobat SDK

Preface

Developing Acrobat Applications Using JavaScript

Related documentation

13

Related documentation
This document refers to the following sources for additional information about JavaScript and related
technologies. The Acrobat documentation is available through the Acrobat Family Developer Center,
http://www.adobe.com/go/acrobat_developer.
For information about

See

A guide to the documentation in the Acrobat SDK.

Acrobat SDK Documentation Roadmap

Known issues and implementation details.

Readme

Answers to frequently asked questions about the
Acrobat SDK.

Developer FAQ

New features in this Acrobat SDK release.

What’s New

A general overview of the Acrobat SDK.

Overview

A guide to the sections of the Acrobat SDK that pertain
to Adobe Reader.

Developing for Adobe Reader

A guide to the sample code included with the Acrobat SDK.

Guide to SDK Samples

Configuring and administering a system for online
collaboration using comment repositories, Acrobat and
Adobe Reader.

Acrobat Online Collaboration:
Setup and Administration

Detailed descriptions of JavaScript APIs for adding
interactivity to 3D annotations within PDF documents.

JavaScript for Acrobat 3D Annotations
API Reference

Detailed descriptions of JavaScript APIs for developing and
enhancing workflows in Acrobat and Adobe Reader.

JavaScript for Acrobat API Reference

A description of how to convert JavaScript for Acrobat for
use in an Adobe® LiveCycle® Designer form.

Converting Acrobat JavaScript for Use
in LiveCycle Designer Forms

A detailed description of the PDF file format.

PDF Reference

Using JavaScript to perform repetitive operations on a
collection of files.

Batch Sequences

A description of Acrobat's digital signature capabilities, which
document authors can use to create certified documents,
signable forms, and custom workflows and appearances.

Acrobat 8.0 Security User Guide

1

Introduction
This chapter introduces the JavaScript for Acrobat scripting model and containment hierarchies (its
objects), as well as the primary Acrobat and PDF capabilities related to JavaScript usage.
Topic

Description

See

Overview

A brief history of JavaScript, its origins in HTML, and its page 14
relevance to Acrobat

Reading the JavaScript for Acrobat
API Reference

Discusses important features of the JavaScript for
Acrobat such as security restrictions on some of the
methods, safe paths and privileged methods.

page 15

Object summary

A listing and short description of some objects that
play an important role in JavaScript for Acrobat.

page 16

JavaScript applications

A far-from-complete listing of suggested applications page 19
to JavaScript.

Overview
JavaScript for Acrobat is an extension of core JavaScript, version 1.5 of ISO-16262, formerly known as
ECMAScript, an object-oriented scripting language developed by Netscape Communications. JavaScript
was created to offload web page processing from a server onto a client in web-based applications. Acrobat
extends the core language by adding new objects and their accompanying methods and properties, to
the JavaScript language. These Acrobat-specific objects enable a developer to manage document security,
communicate with a database, handle file attachments, manipulate a PDF file so that it behaves as an
interactive, web-enabled form, and so on. Because the Acrobat-specific objects are added on top of core
JavaScript, you still have access to its standard classes, including Math, String, Date, and RegExp.
PDF documents have great versatility since they can be displayed both within the Acrobat software as well
as a web browser. Therefore, it is important to be aware of the differences between JavaScript used in a
PDF file and JavaScript used in a web page:
●

JavaScript in a PDF file does not have access to objects within an HTML page. Similarly, JavaScript in
a web page cannot access objects within a PDF file.

●

In HTML, JavaScript is able to manipulate such objects as Window. JavaScript for Acrobat cannot
access this particular object but it can manipulate PDF-specific objects.

Most people know Acrobat as a medium for exchanging and viewing electronic documents easily and
reliably, independent of the environment in which they were created; however, Acrobat provides far more
capabilities than a simple document viewer.
You can enhance a PDF document so that it contains form fields to capture user-entered data as well as
buttons to initiate user actions. This type of PDF document can replace existing paper forms, allowing
employees within a company to fill out forms and submit them via PDF files, and connect their solutions to
enterprise workflows by virtue of their XML-based structure and the accompanying support for
SOAP-based web services.

14

Adobe Acrobat SDK
Developing Acrobat Applications Using JavaScript

Introduction
Reading the JavaScript for Acrobat API Reference

15

Acrobat also contains functionality to support online team review. Documents that are ready for review are
converted to PDF. When a reviewer views a PDF document in Acrobat and adds comments to it, those
comments (or annotations) constitute an additional layer of information on top of the base document.
Acrobat supports a wide variety of standard comment types, such as a note, graphic, sound, or movie. To
share comments on a document with others, such as the author and other reviewers, a reviewer can
export just the comment "layer" to a separate comment repository.
In either of these scenarios, as well as others that are not mentioned here, you can customize the behavior
of a particular PDF document, implement security policies, interact with databases and web services, and
dynamically alter the appearance of a PDF document by using JavaScript. You can tie JavaScript code to a
specific PDF document, a particular page within a PDF document, or a form field or button in a PDF file.
When an end user interacts with Acrobat or a PDF file displayed in Acrobat that contains JavaScript,
Acrobat monitors the interaction and executes the appropriate JavaScript code.
Not only can you customize the behavior of PDF documents in Acrobat, you can customize Acrobat itself.
In earlier versions of Acrobat (prior to Acrobat 5), this type of customization could only be done by writing
Acrobat plug-ins in a high-level language like C or C++. Now, much of that same functionality is available
through Acrobat extensions to JavaScript. You will find that using JavaScript to perform a task such as
adding a menu to Acrobat’s user interface is much easier than writing a plug-in.
Using Acrobat Professional, you can create batch sequences for processing multiple documents,
processing within a single document, processing for a given page, and processing for a single form field.
For batch processing, it is possible to execute JavaScript on a set of PDF files, which enables tasks such as
extracting comments from a comment repository, identifying spelling errors, and automatically printing
PDF files.

Reading the JavaScript for Acrobat API Reference
The companion document to Developing Acrobat Applications Using JavaScript is the JavaScript for Acrobat
API Reference. If you are seriously interested in developing JavaScript solutions for your PDF documents,
this document is of the highest importance to you. This being the case, it is vital to learn how to read the
reference, to be aware of the many security restrictions placed on some of the methods and to know the
standard ways of working with security-restricted methods.
These features are of particular importance:
●

The quick bar: In the JavaScript for Acrobat API Reference, each object, property and method has a quick
bar, a one-row table of icons that provides a summary of the item’s availability and usage
recommendations. Many lost hours of time can be avoided by paying attention to this quick bar. Refer
to the JavaScript for Acrobat API Reference for details.

●

Privileged context: This guide contains detailed information on executing JavaScript in a privileged
context, beyond that provided in JavaScript for Acrobat API Reference, see “Privileged versus
non-privileged context” on page 45.

●

Safe path: Acrobat 6.0 introduced the concept of a safe path for JavaScript methods that write data to
the local hard drive based on a path passed to it by one of its parameters. Generally, when a path is
judged to be not safe, a NotAllowedError exception is thrown. See the JavaScript for Acrobat API
Reference for more information about safe paths.

Note: Many sample scripts presented in this guide reference the local file system. These scripts generally
use the path "/c/temp/", which is a safe path.

Adobe Acrobat SDK

Introduction

Developing Acrobat Applications Using JavaScript

Object summary

16

Object summary
The Acrobat extension to core JavaScript defines many objects that allow your code to interact with the
Acrobat application, a PDF document, or form fields within a PDF document. This section introduces you
to the primary objects used to access and control the application and document, the development
environment itself, and general-purpose JavaScript functionality.
Below is a short listing of some of the main objects used in the document and in the sample files. A brief
description of each of the objects follow the table.
Object

Purpose

ADBC

Database connections and queries

app

Acrobat

console

JavaScript Debugger

dbg

Debugger

dialog

Modal dialog boxes

Doc

PDF document

event

JavaScript events

global

Persistent and cross-document information

search

Searching and indexing

security

Encryption and digital signatures

SOAP

Web services

util

JavaScript utility methods

app
The app object is a static object that represents the Acrobat application itself. It offers a number of
Acrobat-specific functions in addition to a variety of utility routines and convenience functions. By
interacting with the app object, you can open or create PDF and FDF documents, and customize the
Acrobat interface by setting its viewing modes, displaying popup menus, alerts, and thermometers,
displaying a modal dialog box, controlling time intervals, controlling whether calculations will be
performed, performing email operations, and modifying its collection of toolbar buttons, menus, and
menu items. You can also query app to determine which Adobe product and version the end user is using
(such as Adobe Reader 8 or Acrobat Professional 7.0), as well as which printer names and color spaces are
available.

Doc
The Doc object is the primary interface to the PDF document, and it can be used to access and manipulate
its content. The Doc object provides the interfaces between a PDF document open in the viewer and the
JavaScript interpreter. By interacting with the Doc object, you can get general information about the

Adobe Acrobat SDK

Introduction

Developing Acrobat Applications Using JavaScript

dbg

17

document, navigate within the document, control its structure, behavior and format, create new content
within the document, and access objects contained within the document, including bookmarks, form
fields, templates, annotations, and sounds.
The following graphic represents the containment hierarchy of objects related to the Doc object.

Doc object containment hierarchy
doc

field

annot

bookmark

sound

template

data

Accessing the Doc object from JavaScript can be done in a variety of ways. The most common method is
using the this object, which is normally equivalent to the Doc object of the current underlying
document.

dbg
You can use the dbg object, available only in Acrobat Professional, to control the JavaScript Debugger
from a command line while the application is not executing a modal dialog box. The dbg object methods
offer the same functionality as the buttons in the JavaScript debugger dialog box toolbar, which permit
stepwise execution, setting, removing, and inspecting breakpoints, and quitting the debugger.

console
The console object is a static object that is used to access the JavaScript console for displaying debug
messages and executing JavaScript. It is useful as a debugging aid and as a means of interactively testing
code and is only available within Acrobat Professional.

global
The global object is used to store data that is persistent across invocations of Acrobat or shared by
multiple documents. Global data sharing and notification across multiple documents is done through a
subscription mechanism, which enables monitoring of global variables and reporting of their values to all
subscribing documents. In addition, global can be used to store information that pertains to a group of
documents, a situation that occurs when a batch sequence runs. For example, batch sequence code often
stores the total number of documents to be processed as a property of global. If information about the
documents needs to be stored in a Report object, it is assigned to a set of properties within global so it
is accessible to the Report object.

Adobe Acrobat SDK
Developing Acrobat Applications Using JavaScript

Introduction
util

18

util
The util object is a static JavaScript object that defines a number of utility methods and convenience
functions for number and date formatting and parsing. It can also be used to convert information between
rich content and XML representations.

dialog
The dialog object is an object literal used by the app object’s execDialog method to present a modal
dialog box identical in appearance and behavior to those used across all Adobe applications. The dialog
object literal consists of a set of event handlers and properties which determine the behavior and contents
of the dialog box, and may be comprised of the following elements: push buttons, check boxes, radio
buttons, list boxes, text boxes, popup controls, and containers and frames for sets of controls.

security
The security object is a static JavaScript object, available without restriction across all Acrobat
applications including Adobe Reader, that employs a token-based security model to facilitate the creation
and management of digital signatures and encryption in PDF documents, thus providing a means of user
authentication and directory management. Its methods and properties are accessible during batch,
console, menu, or application initialization events. The security object can be used to add passwords
and set security options, add usage rights to a document, encrypt PDF files for a list of recipients, apply
and assign security policies, create custom security policies, add security to document attachments, create
and manage digital IDs using certificates, build a list of trusted identities, and check information on
certificates.

SOAP
The SOAP object can be used to make remote procedure calls to a server and invoke web services
described by WSDL, and supports both SOAP 1.1 and 1.2 encoding. Its methods are available from
Acrobat Professional, Acrobat Standard, and for documents with form export rights open in Adobe Reader
6.0 or later. The SOAP object makes it possible to share comments remotely and to invoke web services in
form field events. It provides support for rich text responses and queries, HTTP authentication and
WS-Security, SOAP headers, error handling, sending or converting file attachments, exchanging
compressed binary data, document literal encoding, object serialization, XML streams, and applying DNS
service discovery to find collaborative repositories on an intranet. In addition the XMLData object can be
used to evaluate XPath expressions and perform XSLT conversions on XML documents.

search
The search object is a static object that can be used to perform simple and advanced searches for text in
one or more PDF documents or index files, create, update, rebuild, or purge indexes for one or more PDF
documents, and search through document-level and object-level metadata. The search object has
properties that can be used to fine-tune the query, such as a thesaurus, words with similar sounds,
case-sensitivity, and settings to search the text both in annotations and in EXIF metadata contained in
JPEG images.

Adobe Acrobat SDK

Introduction

Developing Acrobat Applications Using JavaScript

ADBC

19

ADBC
The ADBC object is used in conjunction with the connection and statement objects to interface with a
database. These objects constitute Acrobat Database Connectivity (ADBC), and provide a simplified means
of using ODBC calls to connect to a database and access its data. SQL statements are passed to the
statement object’s execute method in order to insert, update, retrieve, and delete data.

event
All JavaScript actions are executed when a particular event occurs. For each event, an event object is
created. When an event occurs, the event object can be used to obtain and manage any information
associated with the state of that particular event. An event object is created for each of the following type
of events: Acrobat initialization, batch sequences, mouse events on bookmarks, JavaScript console actions,
document print, save, open, or close actions, page open and close events, form field mouse, keystroke,
calculation, format, and validation events, and menu item selection events.

JavaScript applications
JavaScript for Acrobat enables you to do a wide variety of things within Acrobat and Adobe Reader, and
within PDF documents. The Acrobat extensions to JavaScript can help with the following workflows:
●

●

●

●

Creating PDF documents
●

Create new PDF files

●

Control the appearance and behavior of PDF files

●

Convert PDF files to XML format

●

Create and spawn templates

●

Attach files to PDF documents

Creating Acrobat forms
●

Create, modify, and fill in dynamically changing, interactive forms

●

Import and export form, attachment, and image data

●

Save form data in XML, XDP, or Microsoft Excel format

●

Email completed forms

●

Make forms accessible to visually impaired users

●

Make forms web-ready

●

Migrate legacy forms to dynamic XFA

●

Secure forms

Facilitating review, markup, and approval
●

Set comment repository preferences

●

Create and manage comments

●

Approve documents using stamps

Integrating digital media into documents
●

Control and manage media players and monitors

●

Add movie and sound clips

●

Add and manage renditions

●

Set multimedia preferences

Adobe Acrobat SDK

Introduction

Developing Acrobat Applications Using JavaScript

●

●

●

●

●

●

●

JavaScript applications

Modifying the user interface
●

Create dialog boxes

●

Add navigation to PDF documents

●

Manage PDF layers

●

Manage print production

Searching and indexing of documents and document metadata
●

Perform searches for text in one or more documents

●

Create, update, rebuild, and purge indexes

●

Search document metadata

Securing documents
●

Create and manage digital signatures

●

Add and manage passwords

●

Add usage rights

●

Encrypt files

●

Manage digital certificates

Managing usage rights
●

Write JavaScript for Adobe Reader

●

Enable collaboration

Interacting with databases
●

Establish an ADBC connection

●

Execute SQL statements

●

Support for ADO (Windows only)

Interacting with web services
●

Connection and method invocation

●

HTTP authentication and WS-Security

●

SOAP header support

●

Error handling

●

Handle file attachments

●

Exchange compressed binary data

●

Document literal encoding

●

Serialize objects

●

XML streams

●

Apply DNS service discovery to find collaborative repositories on an intranet

XML
●

Perform XSLT conversions on XML documents

●

Evaluate XPath expressions

20

2

Tools
Acrobat provides an integrated development environment that offers several tools with which to develop
and test JavaScript functionality. These tools are the JavaScript Editor, Console, and Debugger. In addition,
Acrobat supports the use of third-party editors for code development.
Topic

Description

See

Using the JavaScript Debugger console

Covers the following topics:

page 21

●

Opening the Console

●

Executing JavaScript

●

Formatting code

●

Enabling JavaScript

Using a JavaScript editor

How to access and to use the JavaScript editor
built into Acrobat.

page 24

Specifying the default JavaScript editor

How to set the default JavaScript editor to an
external text application.

page 25

Using an external editor

The use of an external editor to write JavaScript
code.

page 26

Using the Debugger with Adobe Reader

How to use the Debugger with Adobe Reader.

page 28

Enabling the JavaScript Debugger

Debugger preferences.

page 29

JavaScript Debugger

The Debugger controls and their use.

page 30

Using the JavaScript Debugger console
The JavaScript console provides an interactive and convenient interface for testing portions of JavaScript
code and experimenting with object properties and methods. Because of its interactive nature, the
console behaves as an editor that permits the execution of single lines or blocks of code.
There are two ways to activate the JavaScript console: either through an Acrobat menu command or
through the use of the static console object within JavaScript code. In either case, it appears as a
component of the JavaScript Debugger, and the primary means of displaying values and results is through
the console.println method.

21

Adobe Acrobat SDK

Tools

Developing Acrobat Applications Using JavaScript

Opening the console

22

Opening the console
➤ To open the JavaScript Debugger console:

1. Open the Debugger window using one of these methods:
●

Select Advanced > Document Processing > JavaScript Debugger, or

●

Type Ctrl+J (Windows) or Command+J (Mac OS)

2. Select either Console or Script and Console from the debugger View list.
To open and close the console with JavaScript code, use console.show() and console.hide()
methods, respectively.

Executing JavaScript
The JavaScript console allows you to evaluate single or multiple lines of code. There are three ways to
evaluate JavaScript code while using the interactive console:
●

To evaluate a portion of a line of code, highlight the portion and press either the Enter key on the
numeric keypad or press Ctrl + Enter.

●

To evaluate a single line of code, make sure the cursor is positioned on that line and press either the
Enter key on the numeric keypad or press Ctrl + Enter.

●

To evaluate multiple lines of code, highlight those lines and press either the Enter key on the numeric
keypad or press Ctrl + Enter.

In all cases, the result of the most recent single JavaScript statement executed is displayed in the console.

Formatting code
To indent code in the JavaScript console, use the Tab key.
●

To indent four spaces to the right, position the cursor at the beginning of a single line or highlight the
block of code, and press the Tab key.

●

To indent four spaces to the left, position the cursor at the beginning of a single line or highlight a
block of code and press Shift + Tab.

Enabling JavaScript
In order to use JavaScript, you must first verify that JavaScript has been enabled. In order to execute code
from the console, you will also need to ensure that the JavaScript Debugger is enabled, since the Console
window is a component within the JavaScript Debugger interface.
➤ To enable JavaScript, the Debugger and the Console:

1. Launch Acrobat.
2. Select Edit > Preferences to open the Preferences dialog box.
3. Select JavaScript from the list of options on the left side of the dialog box.
4. Select Enable Acrobat JavaScript if it is not already selected.

Adobe Acrobat SDK

Tools

Developing Acrobat Applications Using JavaScript

Enabling JavaScript

23

5. In the Preferences dialog box, select Enable JavaScript Debugger After Acrobat is Restarted from
the JavaScript Debugger options.
6. Select Enable Interactive Console. This option enables you to evaluate code that you write in the
console window.
7. Select Show Console on Errors and Messages. This ensures that whenever you make mistakes, the
console displays helpful information.
8. Click OK to close the Preferences dialog box.
9. Close and restart Acrobat.
➤ To test the interactive Console:

1. Select Advanced > Document Processing > JavaScript Debugger to open the JavaScript Debugger.
2. In the debugger, select Console from the View window.
The Console window appears.
3. Click Clear (the trash can icon), located at the bottom right of the Console, to delete any contents that
appear in the window.
4. In the text window, type the following code:
var jsNum = 10;

5. With the mouse cursor positioned somewhere in this line of code, press Enter on the numeric keypad
or press Ctrl + Enter. The JavaScript variable is created and is assigned a value of 10. The results are
shown in the following graphic.

Evaluating the variable declaration

After each JavaScript statement executes, the console window prints out undefined, which is the
return value of the statement. Note that the result of a statement is not the same as the value of an
expression within the statement. In this case, the return value undefined does not mean that the
value of jsNum is undefined; it just means that the entire JavaScript statement’s value is undefined.
Note the use of the console.println() method to display the result in a more human-readable
format.

Adobe Acrobat SDK

Tools

Developing Acrobat Applications Using JavaScript

Debugging with the JavaScript Console

24

Debugging with the JavaScript Console
Though Acrobat Professional has a full-featured debugger, see “JavaScript Debugger” on page 30, for
simple scripts it is often easier to debug scripts by the following methods:
●

testing and/or developing script snippets in the Console itself

●

inserting console.println() commands to write information to the Console.

Example 2.1

Test a regular expression in the JavaScript Debugger Console

The following script, which can be created in the JavaScript Console, illustrates the use of
console.println().
The regular expression
var re = /(Professional|Pro)(\s+)(\d)/g

and the replacement function, myReplace(), are used to search the string, str, for the phrase
"Professional 7" or "Pro 7", and to replace the string "7" with the string "8". The script is executed
using the procedures described in “Executing JavaScript” on page 22.
After testing and debugging, the script can be copied and pasted to the target location.
Note the debugging loop inside the function myReplace() writes the arguments of the function to the
Console. This helps in the development phase: the arguments are seen in the Console where you can verify
that they are the ones expected. The loop can be deleted or commented out after testing.
function myReplace() {
var l = arguments.length;
for ( var i = 0; i < l; i++)
console.println("arg" + i + " = " + arguments[i])
return arguments[1] + arguments[2] + "8";
}
var str = "Acrobat Professional\n7 is a great application, "
+ "so I say on the 7th of May.\nOn a laptop Acrobat Pro 7.0 is on the go!"
var re = /(Professional|Pro)(\s+)(\d)/g;
var newStr = str.replace( re, myReplace);
console.println("\nnewStr = " + newStr);

Using a JavaScript editor
There are several ways to invoke the JavaScript Editor, depending on the context. To begin with, it is
possible to select JavaScripts from the Advanced > Document Processing menu and choose one of the
following options:
●

Edit All JavaScripts

●

Document JavaScripts

●

Set Document Actions

A more basic approach, however, is to think of a script as an action associated with a part of the document,
such as a page, bookmark, or form field. As in the following example, you can select the object of interest
and edit its particular script.

Adobe Acrobat SDK
Developing Acrobat Applications Using JavaScript

Tools
Specifying the default JavaScript editor

25

➤ To write a script for a document component:

1. Right-click a document component such as a bookmark. This triggers a context menu.
2. Select Properties and choose the Actions tab.
3. Select Run a JavaScript from the Select Action drop-down list.
4. Click Add to open the JavaScript editor.
5. In the editor window, write the JavaScript code to run when the event that activates the code is
created.
6. Click Close.
If there are errors in your code, the JavaScript editor highlights the code line in question and displays
an error message.
Note: JavaScript actions have a scope associated with various levels of objects in a PDF document, such as
a form field, a page, or the entire document. For example, a script at the document level would be
available from all other scriptable locations within the document.

Specifying the default JavaScript editor
You can choose whether to use the built-in JavaScript editor that comes with Acrobat, or an external
JavaScript editor of your choice.
➤ To set the default editor:

1. Choose Edit > Preferences (Ctrl+K) to open the Preferences dialog box.
2. Select JavaScript from the list of options on the left side of the dialog box.
This brings up the Preferences dialog box.
3. In the JavaScript Editor section, select the editor you would like to use.
The Acrobat JavaScript Editor option sets the built-in JavaScript editor as the default.
The External JavaScript Editor option sets an external editor as the default.
Note: For some external editors, Acrobat provides extra command line options for invoking the editor. For
details, see “Additional editor capabilities” on page 26.
Like the JavaScript Console, the built-in JavaScript Editor can be used to evaluate portions of JavaScript
code. Select a line or block of code to be evaluated, and press the Enter key on the numeric keypad or
Ctrl + Enter on the regular keyboard.
When you execute script from within an JavaScript Editor window, results appear in the Console window.
The Console window should be open prior to opening any JavaScript Editor window.
The JavaScript Editor provides the same formatting options as those in the console window. For details,
see “Formatting code” on page 22.

Adobe Acrobat SDK
Developing Acrobat Applications Using JavaScript

Tools
Using an external editor

26

Using an external editor
If an external editor program has been specified as the default application for editing scripts in Acrobat,
Acrobat generates a temporary file and opens it in the external editor program. When editing a file in an
external editor, note the following restrictions:
●

You must save the file in order for Acrobat to detect the changes.

●

Acrobat is inaccessible while the external editor is in use.

●

JavaScript code cannot be evaluated within the external editor.

Additional editor capabilities
Acrobat supports some additional command line editor capabilities for Windows-based applications, and
provides support for two parameters in particular: the file name (%f ) and the target line number (%n).
Parameters for Mac OS-based editors are not supported.
Note that Acrobat launches a new instance of the editor for each new editing session. Some editors, if
already running, load new files into the same session and may close the other open files without saving
them. Thus, it is important to remember to take one of the following measures: save your changes before
beginning a new editing session, close the editor application before starting a new editing session, or
adjust its default preferences so that it always launches a new editor instance (this is the best course of
action, if available).
If you are able to set the editor preferences to launch a new instance for each editing session, and if the
editor requires a command line parameter in order to invoke a new editor instance, you can add that
parameter to the editor command line specified, as described in “Specifying additional capabilities to your
editor” on page 26.
If your editor accepts a starting line number on the command line, Acrobat can start the editor on a line
containing a syntax error by inserting the line number as a command line parameter (%n).
For your convenience, Acrobat provides predefined, command line templates for many current external
editors. The external editor settings are defined in Edit > Preferences > JavaScript. If you use the Browse
button to specify an external editor and it has a pre-defined command line template, the command line
parameters and options appear to the right of the pathname for the editor application, and you can edit
them. If no predefined template is available for your editor, you can still specify the appropriate command
line parameters.

Specifying additional capabilities to your editor
Acrobat provides internal support for both of the commands described above on a few editors such as
CodeWrite, Emacs, and SlickEdit (see the table “Supported external JavaScript editors with command line
templates” on page 27).
If your editor is not one that Acrobat currently supports, it will be necessary to check the editor’s
documentation. You will need to search for the following information:
●

What are the command switches to tell the editor to always open a new instance?
Switches vary depending on the editor and include such parameters as /NI and +new followed by the
file name ("%f"). Note that the quotes are required, because the file name that Acrobat sends to the
editor may contain spaces.

Adobe Acrobat SDK

Tools

Developing Acrobat Applications Using JavaScript

●

Specifying additional capabilities to your editor

27

Is there a way to instruct the editor to open a file and jump to a line number?
Some line number command switches are -#, -L, +, and -l, each followed by the line number (%n). For
most editors, the line number switch and %n should be enclosed in square brackets [...]. The text
inside the square brackets will be used only when Acrobat requires that the editor jump to a specific
line in order to correct a JavaScript syntax error. You can use an editor that does not support a line
number switch; in this case, you will need to scroll to the appropriate line in the event of a syntax error.

For example, Acrobat recognizes the Visual SlickEdit editor as vs.exe and automatically supplies this
command line template:
"C:\Program Files\vslick\win\vs.exe" "%f" +new [-#%n]

When Acrobat opens the default JavaScript editor, it makes the appropriate substitutions in the command
line and executes it with the operating system shell. In the above case, if the syntax error were on line 43,
the command line generated would appear as follows:
"C:\Program Files\vslick\win\vs.exe" "C:\Temp\jsedit.js" +new -#43

Note: To insert %, [, or ] as characters in the command line, precede each of them with the % escape
character, thus using %%, %[, or %] respectively.

Supported external JavaScript editors with command line templates

Editor

Web site

Template command line
arguments

Boxer

http://www.boxersoftware.com

-G -2 "%f" [-L%n]

ConTEXT

http://fixedsys.com/context

"%f" [/g1:%n]

CodeWright

http://www.codewright.com

-M -N -NOSPLASH "%f" [-G%n]

Emacs

http://www.gnu.org/software/emacs/emacs.html [+%n] "%f"

Epsilon

http://www.lugaru.com

[+%n] "%f"

Multi-Edit

http://www.multiedit.com

/NI /NS /NV [/L%n] "%f"

TextPad

http://www.textpad.com

-m -q "%f"

UltraEdit

http://www.ultraedit.com

"%f" [-l%n]

VEDIT

http://www.vedit.com

-s2 "%f" [-l %n]

Visual SlickEdit http://www.slickedit.com

+new "%f" [-#%n]

➤ To determine whether Acrobat can open your editor on a line number:

1. Open a script in your editor.
2. Add a syntax error.
3. Move the cursor to a line other than the one containing the syntax error.
4. Close and save the file.
If a dialog box automatically appears prompting you to fix the syntax error, check whether it correctly
specifies the line containing the error.

Adobe Acrobat SDK

Tools

Developing Acrobat Applications Using JavaScript

Saving and closing a file with a syntax error

28

Saving and closing a file with a syntax error
If you save and close a file containing a syntax error, Acrobat displays a dialog box with a message asking if
you would like to fix the error. For example, if there is an error on line 123, the following message appears:
There is a JavaScript error at line 123.
Do you want to fix the error?

Note: If you click No, Acrobat discards your file.
Always click Yes. Acrobat expands the path to the editor to include the line number in the specified syntax.
The editor opens and the cursor is placed on the appropriate line.

Using the Debugger with Adobe Reader
The JavaScript Debugger is a fully capable debugger that allows you to set breakpoints and inspect
variable values while stepping through code. While it is normally accessed from the Acrobat Professional
user interface, it can also be triggered to appear in Adobe Reader when an exception occurs.
Though fully supported JavaScript debugging is only available in Acrobat Professional, the following
instructions to make the complete Debugger functionality available in Adobe Reader on Windows and
Mac OS platforms are provided as a courtesy. For Windows, note that this procedure involves editing the
registry. Adobe Systems Incorporated does not provide support for editing the registry, which contains
critical system and application information. It is recommended that you back up the registry before
modifying it.
1. The file debugger.js, available at http://www.adobe.com/go/acrobat_developer or in the SDK
installation (Acrobat 8.0 SDK/JavaScriptSupport/Debugger/debugger.js), must be copied to the
Acrobat 8.0/Reader/JavaScripts folder.
2. Create key/value pairs in the registry settings, starting at the location
HKEY_CURRENT_USER\Software\Adobe\Acrobat Reader\8.0\JSPrefs\ on Windows as shown in the
table below, or in the property list file :Library:Preferences:com.adobe.Reader8.0.plist on Mac
OS. For Mac OS, use an appropriate editor for the property list file, and add the following children under
JSPrefs, using Type : Array in each case: ConsoleOpen, ConsoleInput, EnableDebugger, and Exceptions.
Under each of these children, add the following children: 0 (number) and 1 (boolean).
3. Close and restart Adobe Reader. At this point the Debugger will be available.

Registry key/value pairs for Windows
bConsoleInput

REG_DWORD

0x00000001

bEnableDebugger

REG_DWORD

0x00000001

iExceptions

REG_DWORD

0x00000002

(This will break into the Debugger when exceptions
occur.)
Note: Since Adobe Reader does not provide access to the Debugger through its menu items or the Ctrl + J
key sequence, the only ways to access the Debugger are to execute a JavaScript, cause an error, or
customize the user interface (for example, you could add a button that runs a JavaScript causing the
Debugger to appear).

Adobe Acrobat SDK

Tools

Developing Acrobat Applications Using JavaScript

Enabling the JavaScript Debugger

29

As you learned earlier when opening the JavaScript Console, which is integrated with the Debugger dialog
box, the Debugger may be opening in Acrobat Professional by selecting Advanced > Document
Processing > JavaScript Debugger. In addition, the Debugger automatically opens if a running script
throws an exception or encounters a previously set break point.
Note: The JavaScript Debugger cannot be used to analyze JavaScript stored in HTML pages viewed by
web browsers or any other kind of scripting languages.

Enabling the JavaScript Debugger
The JavaScript Debugger can be a powerful tool for debugging complex scripts; however, it is a tool for an
advanced user. For this reason, this section can be skipped at first reading. (Simple scripts can be
debugged by inserting console.println() statements to read out debugging information to the
console. For more information on this subject, see “Debugging with the JavaScript Console” on page 24.)
In order to make the Debugger available for use, you must enable both JavaScript and the Debugger. As
you did earlier, use the Preferences dialog box (Ctrl+K) to control the behavior of the JavaScript
development environment. Enabling JavaScript and the JavaScript editor are described in “Enabling
JavaScript” on page 22. To enable the Debugger, select JavaScript from the list on the left in the
Preferences dialog box and make sure the item Enable JavaScript Debugger after Acrobat is Restarted is
enabled. Note that you must restart Acrobat for this option to take effect.
The Debugger options are located in the JavaScript Debugger section of the Preferences dialog box, and
are explained in the following table.

JavaScript Debugger options
Option

Meaning

Enable Javascript Debugger
after Acrobat is restarted

To enable the Debugger, check this option, which makes all Debugger
features available the next time Acrobat is launched.

Store breakpoints in PDF file

This option enables you to store breakpoints so they are available the
next time you start Acrobat or open the PDF file. To remove the
breakpoints, do the following:

When an exception is thrown

●

Turn this option off.

●

Select Advanced > Document Processing > Document JavaScripts
and delete the ACRO_Breakpoints script.

●

Save the file.

This option provides three choices for actions when an exception is
thrown:
Ignore — ignores the exception
Trace — displays a stack trace
Break — stops execution and displays a message window that gives
you the option to start the debugger at the line where the exception
occurred.

Adobe Acrobat SDK

Tools

Developing Acrobat Applications Using JavaScript

JavaScript Debugger

Option

Meaning

Enable interactive console

This option allows you to enter JavaScript commands in the console
window. If this option is not checked and you click in the console
window, the following message appears:

30

The interactive console is not enabled. Would you like to enable it
now?
Click Yes to enable this option from within the Debugger. In
Preferences you will now see this option checked.
Show console on errors and
messages

This option opens the console window in the Debugger dialog box.
Regardless of whether the Debugger is enabled, this option causes the
Debugger dialog box to open when an error occurs and displays the
error message to the console window.

JavaScript Debugger
You can open the JavaScript Debugger at any time by selecting the Acrobat menu item Advanced >
Document Processing > JavaScript Debugger. Familiarize yourself with the parts of the window and the
controls as described here before you attempt interactive debugging of a script.
For information on the types and locations of scripts that may be debugged, see “Accessing scripts in the
Scripts window” on page 33. The section “Starting the Debugger” on page 38 describes how to
automatically start the Debugger for a script.
Caution: In Windows, while the Debugger is open and a debugging session is in progress, Acrobat will be
unavailable.

Main groups of controls
The Debugger dialog box, see “Debugger dialog box” on page 31, consists of three main groups of
controls. The toolbar on the top left contains six button controls that provide basic debugging session
functionality.
Immediately below the toolbar, a Scripts window displays the names of scripts available for debugging.
These are organized in a tree hierarchy, such as the one shown below in the graphic Debugger dialog box,
and may be accompanied by the Scripts window below, which shows the code for a single script
corresponding to the one highlighted in the Scripts window.
The Call Stack and Inspect drop-down lists are located at the top right of the Debugger dialog box.
Selecting entries in these lists enables you to view the nesting order of function calls, and enables you to
inspect the details of variables, watches, and breakpoints in the Inspect Details window.

Adobe Acrobat SDK

Tools

Developing Acrobat Applications Using JavaScript

Debugger View windows

31

Debugger View windows
Below the main group of controls, the debugger provides a View drop-down list with the following
choices:
Script — view a single JavaScript script selected from the Scripts hierarchy window
Console — view the output of a selected script as it executes in the JavaScript Console window. The
Console may also be used to run scripts or individual commands. See “Using the JavaScript Debugger
console” on page 21.
Script and Console — view both the Console and Script windows at the same time. The Script window
displays above the console window, as shown in the following graphic.

Debugger dialog box

Adobe Acrobat SDK

Tools

Developing Acrobat Applications Using JavaScript

Debugger buttons

32

Debugger buttons
The following graphic shows the debugger buttons on the toolbar, and the table summarizes the
functionality of each button, followed by detailed descriptions below.

Debugger buttons

Resume

Interrupt

Quit

Step over

Step into

Step out

Debugger buttons summary
Button

Description

Resume Execution

Runs a script stopped in the debugger.

Interrupt

Halts execution.

Quit

Closes the debugger and terminates script execution.

Step over

Executes the next instruction, but does not enter a function call if encountered.

Step into

Executes the next instruction, and enters a function call if encountered.

Step out

Executes the remaining code in a function call, and stops at the next instruction
in the calling script.

Resume execution
When the script is stopped, the Resume Execution button cause the script to continue execution until it
reaches one of the following:
●

The next script to be executed

●

The next breakpoint encountered

●

The next error encountered

●

The end of the script

Interrupt
The Interrupt button halts execution of the current script. When clicked, it appears in red, which indicates
that it has been activated and causes execution to stop at the beginning of the next script that is run. If this
occurs, the Interrupt button is automatically deactivated and returns to its green color. It must be activated
again in order to interrupt another script.

Quit
The Quit button terminates the debugging session and closes the Debugger.

Adobe Acrobat SDK

Tools

Developing Acrobat Applications Using JavaScript

Debugger Scripts window

33

Step over
The Step Over button executes a single instruction, and if it is a function call, it executes the entire function
in a single step, rather than stepping into the function. For example, the position indicator (yellow arrow)
in the Debugger is to the left of a function call, as shown below.

Position indicator at a function call

Execution is currently halted before the call to callMe. Assuming that there are no errors or breakpoints in
callMe, clicking Step Over executes the entire callMe function, and advances the position indicator to
the next script instruction following the function call.
If the statement at the position indicator does not contain a function call, Step Over simply executes that
statement.

Step into
The Step Into button executes the next statement, and if it is a function call, it proceeds to the first
statement within the function.
Note: It is not possible to step into native functions, since they have no JavaScript implementation. This
applies to Acrobat native functions as well as core JavaScript functions.

Step out
The Step Out button executes the remaining code within the current function call and stops at the instruction
immediately following the call. This button provides a convenient means of eliminating cumbersome, stepwise
execution of functions that do not contain bugs. If you are not inside a function call and there are no errors, the
Step Out button continues executing code to the end of the current script or until a breakpoint is encountered.

Debugger Scripts window
All scripts associated with a PDF file are available in the Debugger dialog box. The Debugger displays these
in the Scripts window.

Scripts window

Accessing scripts in the Scripts window
To display the content of a script, click the triangle to its left in the Scripts window. Each triangle opens the
next level in the containment hierarchy. A script icon indicates the lowest level, which means that the code

Adobe Acrobat SDK

Tools

Developing Acrobat Applications Using JavaScript

Debugger Scripts window

34

for the given function is available. As shown above in the graphic Scripts window, a function has been
defined for a mouse-up action on a button named Button1. Click on the script icon to display its code.
JavaScript can be stored in several places, which may be either inside or outside PDF files. The following
sections describe their possible locations.

Scripts inside PDF files
The table below lists the types of scripts that can be placed in PDF files. These can be accessed from the
Scripts window within the Debugger dialog box. You can edit them from inside the Debugger, and set
breakpoints as described in “Breakpoints” on page 37.
Note: Changes to scripts do not take effect until the scripts are re-run; changes cannot be applied to a
running script.
Scripts inside PDF files
Location

Access

Document level

Advanced > Document Processing > Document JavaScripts

Document actions

Advanced > Document Processing > Set Document Actions

Page actions

Click the page on the Pages tab; right-click the thumbnail for the page and click
Page Properties.

Forms

Double-click the form object in form editing mode (see below) to bring up the
properties dialog box for that form object.

Bookmarks

Click the bookmark on the Bookmarks tab; right-click the bookmark and click on
Properties.

Links

Double-click the link object in object editing mode (see below) to bring up the
Link Properties dialog box.

Form editing mode — To switch to form editing mode, select Forms > Edit Form in Acrobat.

Scripts outside PDF files
Scripts outside of Acrobat are also listed in the Scripts window and are available for debugging in Acrobat.
The following table lists these script types and how to access them.

Scripts outside PDF files
Location

Access

Folder level

Stored as JavaScript (.js) files in the App or User folder areas

Console

Entered and evaluated in the console window

Batch

Choose Advanced > Document Processing > Batch Processing

Folder-level scripts normally can be viewed and debugged but not edited in Acrobat. Console and batch
processing scripts are not visible to the Debugger until they are executed. For this reason, you cannot set
breakpoints prior to executing these scripts. You can access the scripts either using the Debug From Start
option or by using the debugger keyword. See “Starting the Debugger” on page 38 for details.

Adobe Acrobat SDK

Tools

Developing Acrobat Applications Using JavaScript

Call Stack list

35

Call Stack list
To the right of the Debugger control buttons is the Call Stack drop-down list which displays the currently
executing function and its associated state within the current set of nested calls. An example is shown in
the following graphic. When the Debugger has been used to suspend execution at a given statement, the
call stack displays text indicating the current function call (stack frame). Each entry shows the current line
number and function name. The most recent stack frame is displayed at the top of the Call Stack
drop-down list. To inspect the local variables of a particular frame in the stack, click that entry. They appear
in the Inspect details window immediately below the Call Stack list.

Call stack

You can select any function in the call stack. Doing so selects that stack frame, and its location is shown in
the Inspect details window. When Local Variables is selected in the Inspect drop-down list, the variables
specific to that active frame are displayed in the Inspect details window.

Inspect details window
The Inspect details window is located to the right of the Scripts window and below the Call Stack. Its
purpose is to help you inspect the values of variables, customize the way in which variables are inspected
(setting watches), and obtain detailed information about breakpoints.

Inspect details window controls
The three buttons at the bottom right of the Inspect details window, shown in the following graphic, can
be used to edit, create, or delete items. The Edit, New, and Delete buttons become active when items in
the Inspect drop-down list are selected.

Inspect details window button controls

Edit New Delete

Adobe Acrobat SDK

Tools

Developing Acrobat Applications Using JavaScript

Inspect details window

36

Inspecting variables
The Inspect details window is a powerful tool that you can use to examine the current state of JavaScript
objects and variables. It enables you to inspect any objects and properties in a recursive manner within the
current stack frame in the debugging session.
To inspect a variable, select Local Variables from the Inspect drop-down list, which displays a list of variable
and value pairs in the Inspect details window. To place a value in a variable, highlight the variable in the
details window (this activates the Edit button). Click the Edit button. An Edit Variable dialog box appears,
allowing you to enter a new value for the variable as shown in the following graphic.
A triangle next to a name indicates that an object is available for inspection. If you would like to view its
properties, click the triangle to expand the object.

Local variable details

Watches
The Watches list enables you to customize how variables are inspected. Watches are JavaScript
expressions evaluated when the debugger encounters a breakpoint or a step in execution. The Watches
list provides you with the ability to edit, add, or delete watches using the three buttons just below the
Inspect details window. All results are displayed in the Inspect details window in the order in which they
were created.
➤ To set a watch:

1. Select Watches from the Inspect drop-down list.
2. Click the New button. A dialog box prompts you for the JavaScript variable or expression to be
evaluated.
➤ To change the value of a watch:

1. Select the watch from the list.
2. Click the Edit button, which displays a dialog box prompting you to specify a new expression for
evaluation.
➤ To delete a watch:

1. Select the watch from the Inspect drop-down list.
2. Click the Delete button.

Adobe Acrobat SDK

Tools

Developing Acrobat Applications Using JavaScript

Inspect details window

37

Breakpoints
The Breakpoints option in the Inspect drop-down list enables you to manage program breakpoints, which
in turn make it possible to inspect the values of local variables once execution is halted. A breakpoint may
be defined so that execution halts at a given line of code, and conditions may be associated with them (see
“Using conditional breakpoints” on page 38).
When a breakpoint is reached, JavaScript execution halts and the debugger displays the current line of
code.
To add a breakpoint, click on the gray strip to the left of the code in the script view, which causes a red dot
to appear. The lines at which breakpoints are permitted have small horizontal lines immediately to their
left in the gray strip.
To remove the breakpoint, click on the red dot, which subsequently disappears.

Coding styles and breakpoints
Placement of the left curly brace ({) in a function definition is a matter of style.
Style 1: Place the left curly brace on the same line as the function name, for example,
function callMe() { // curly brace on same line as function name
var a = 0;
}

Style 2: Place the left curly brace on a separate line, for example
function callMe()
{ // curly brace is on a separate line
var a = 0;
}

If you would like to set a breakpoint at the function heading, use Style 1. Note that the JavaScript
Debugger does not set a breakpoint at the function heading for Style 2. It is only possible to set a
breakpoint from the line of code containing the left curly brace. This is illustrated in the graphic below. It is
possible to set the breakpoint on the line below the function heading for callMe and on the line
containing the function heading for testLoop. Setting a breakpoint at a function heading causes
execution to stop at the first statement within the function.

Setting a breakpoint at a function heading

Adobe Acrobat SDK
Developing Acrobat Applications Using JavaScript

Tools
Starting the Debugger

38

Listing breakpoints
To view the list of all breakpoints set for the debugging session, select the Breakpoints option from the
Inspect drop-down list. You can edit and delete breakpoints using the button controls just beneath the
Inspect details window, as shown in the graphic “Inspect details window button controls” on page 35.

Using conditional breakpoints
A conditional breakpoint causes the interpreter to stop the program and activate the Debugger only when
a specified condition is true. Conditional breakpoints are useful for stopping execution when conditions
warrant doing so, and streamline the debugging process by eliminating needless stepwise execution. For
example, if you are only interested in debugging after 100 iterations in a loop, you can set a breakpoint
that only becomes active when the looping index reaches the value of 100.
The condition is a JavaScript expression. If the expression evaluates to true, the interpreter stops the
program at the breakpoint. Otherwise, the interpreter does not stop the program. An unconditional
breakpoint, the default, always causes the interpreter to stop the program and to activate the Debugger
when it reaches the breakpoint, because its condition is always set to true.
➤ To change a breakpoint condition:

1. Select Breakpoint from the Inspect drop-down list
2. Click Edit. A dialog box appears, prompting you to change the breakpoint condition

Starting the Debugger
There are four ways to invoke the JavaScript Debugger. Two of these ways begin the debugging session
from the start of execution, and the other two begin the session from a specified line of code.

Debugging from the start of execution
There are two ways to start the Debugger from the start of execution. In either case, use the Step Into
button, described on page 33, to proceed with the debugging session.
The first method is to choose Advanced > Document Processing and, if the option is not already checked,
click on Debug From Start.
This option causes the debugging session to begin at the start of execution of any new script.
Note: Debug From Start does not turn off automatically. Be sure to turn off this option when you have
finished debugging, otherwise it continues to stop on every new script you execute in Acrobat.
The second method uses the Interrupt button. Open the Debugger window and click the Interrupt button
(page 32), which displays in red. At this point, performing any action that runs a script causes execution to
stop at the beginning of the script.
Unlike Debug From Start, the Interrupt button is automatically deactivated after being used. To stop at the
beginning of a new script, you must reactivate it by clicking it again.

Adobe Acrobat SDK
Developing Acrobat Applications Using JavaScript

Tools
Final notes

39

Debugging from an arbitrary point in the script
To start debugging from a specific point in your script, you can set a breakpoint. For more information, see
“Breakpoints” on page 37.
An alternate approach is to insert the debugger keyword in any line of your code to stop execution and
enter the Debugger when that particular line is reached.
Note: Breakpoints created using the debugger keyword are not listed in the Inspect details window
when you select Breakpoints from the Inspect drop-down list.

Final notes
There are limitations to debugging scripts in Acrobat from inside a browser, because not all scripts
contained in a PDF file may be available if the PDF file has not been completely downloaded.
Debugging is not possible if a modal dialog box is running. This may occur when debugging a batch
sequence. If a modal dialog box is running during a debugging session and the program stops responding,
press the Esc key.
Debugging scripts with an event initiated by either the app.setInterval or app.setTimeOut
method may trigger the appearance of a series of recurring alert messages. If this occurs, press the Esc key
after the modal dialog box has exited.

3

JavaScript Contexts in Acrobat
JavaScript for Acrobat can be placed in a variety of locations, both external to the document, and within
the document. This chapter discusses how to determine the appropriate location for a script, and how to
create and access the scripts.
Topic

Description

See

The concept of a JavaScript event

A brief description of an event and how they are
triggered.

page 40

About contexts

Discusses the placement of scripts at the folder,
document, page, field and batch levels.

page 41

Privileged versus non-privileged
context

A discussion of the execution of methods in a
privileged context, and how to work around these
security restrictions.

page 45

The concept of a JavaScript event
All scripts are executed in response to a particular event. There are several types of events:
●

App
When the Viewer is started, the Application Initialization Event occurs. Script files, called Folder Level
JavaScripts, are read in from the application and user JavaScript folders. See “Folder level” on page 42
for additional details.

●

Batch
A batch event occurs during the processing of each document of a batch sequence.

●

Bookmark
This event occurs whenever a user clicks on a bookmark that executes a script.

●

Console
A console event occurs whenever a user evaluates a script in the console. See “Executing JavaScript” on
page 22.

●

Doc
This event is triggered whenever a document level event occurs. For more information, see “Document
level” on page 43.

●

External
This event is the result of an external access, for example, through OLE, AppleScript, or loading an FDF

●

field
This event is triggered when the user interacts with an Acrobat form, see “Field level” on page 44 for
more information.

●

Link
This event is triggered when a link containing a JavaScript action is activated by the user.

●

Menu
A menu event occurs whenever JavaScript that has been attached to a menu item is executed. In
Acrobat 5.0 and later, the user can add a menu item and associate JavaScript actions with it.
40

Adobe Acrobat SDK

JavaScript Contexts in Acrobat

Developing Acrobat Applications Using JavaScript

About contexts

41

●

Page
This event is triggered when the user changes pages in the document. See “Page level” on page 43 for
more information.

●

Screen
This event is triggered when the user interacts with a multimedia screen annotation.

These types of events may be initiated, or triggered, in a number of different ways, for example, in
response to a mouse up, a mouse down, a keystroke, on focus, or on blur. These are referred to by the
JavaScript for Acrobat API Reference as the event names. Event types and names appear in pairs. For
example, if an action is initiated by clicking a button, this would generate a Field type event, triggered by a
mouse up event; consequently, we refer to such an event as a field/mouse up event.
The table that follows lists all event type/name combinations.

Event type/name combinations
Event type

Event names

App

Init

Batch

Exec

Bookmark

Mouse Up

Console

Exec

Doc

DidPrint, DidSave, Open, WillClose, WillPrint, WillSave

External

Exec

Field

Blur, Calculate, Focus, Format, Keystroke, Mouse Down,
Mouse Enter, Mouse Exit, Mouse Up, Validate

Link

Mouse Up

Menu

Exec

Page

Open, Close

Screen

InView, OutView, Open, Close, Focus, Blur, Mouse Up,
Mouse Down, Mouse Enter, Mouse Exit

An event manifests itself in JavaScript as an Event object. Complete documentation for the different event
types of events and the ways in which they can be triggered can be found in the description of the Event
object in the JavaScript for Acrobat API Reference.

About contexts
JavaScript for Acrobat can be placed at a variety of levels:
●

Folder level
Scripts placed here respond to App type events.

●

Document level
Scripts placed here respond to Doc type events.

●

Page level
Scripts placed here respond to Page type events.

Adobe Acrobat SDK

JavaScript Contexts in Acrobat

Developing Acrobat Applications Using JavaScript

●

Field level
Scripts placed here respond to Field type events.

●

Batch level
Scripts are placed here respond to Batch type events.

Folder level

42

Each of these levels represents a context, or location, in which processing occurs. The list above is by no
means a complete list of locations at which scripts can be placed.
The placement of a script at a given level determines its reusability. Folder level scripts are available within
all documents, document level scripts are available to all form fields within a given document, field level
scripts are visible to the form fields with which they are associated.
Note: For instructions on how to disallow changes to scripts or hide scripts, see “Disallowing changes in
scripts” on page 182 and “Hiding scripts” on page 182.

Folder level
Folder level scripts contain variable declarations and function definitions that may be generally useful to
Acrobat, and are visible from all documents. Top level scripts, ones that are not contained in a function
definition, are executed when the application is initialized.
There are two kinds of folder level scripts: App and User. For example, if you would like to add specialized
menus and menu items to be available to all documents opened in Acrobat, you can store the code at the
folder level.
Folder level scripts are placed in separate files that have the .js extension. App folder level scripts are
stored in the Acrobat application’s JavaScripts folder, and user folder level scripts are stored in the
user’s JavaScripts folder. These scripts are loaded when Acrobat starts execution, and are associated
with the event object’s Application Initialization (App/Init) event.
Note: The locations of these folders can be found by executing the following lines in the JavaScript
Debugger Console:
// for App folder scripts
app.getPath("app", "javascript");
// for User folder scripts
app.getPath("user", "javascript");

When Acrobat is installed on your machine, it provides you with several standard folder level JavaScript
files, including JSByteCodeWin.bin (this file is a pre-compiled script that supports the forms and
annotation plug-ins) and debugger.js; these are in the App folder. Other JavaScript files in the App
folder may be installed by third-party Acrobat plug-in developers.
The user folder may contain the files glob.js and config.js. The glob.js file is programmatically
generated and contains cross-session global variables set using the global object’s setPersistent
method. The config.js file is used to set user preferences or to customize the viewer UI by adding
toolbar buttons or menu items. (See “Adding toolbar buttons and menu items” on page 135 for more
information on this topic.) Any file with an extension of .js found in the user folder is also loaded by
Acrobat during initialization, after it has loaded the files found in the App folder, and after it has loaded the
config.js and global.js files.
To create folder level scripts, use an external editor running in parallel to Acrobat. Note that the external
editor cannot be invoked from Acrobat for folder level scripts.

Adobe Acrobat SDK

JavaScript Contexts in Acrobat

Developing Acrobat Applications Using JavaScript

Document level

43

Document level
Document level scripts are variable and function definitions that are generally useful to a given document,
but are not applicable outside the document.
●

Variable definitions: Define variables at the document level to make them visible to any executing
script. For example,
var defaultUserColor = "red";

The variable defined above, which has an initial value of "red", may be changed as the user
interacts with the document.
●

Function definitions: Define functions at the document level that support the user interaction with
the document. These functions may be utility functions for handling common tasks for string or
number manipulation, or functions that execute lengthy scripts called by actions initiated by a user
interacting with Acrobat form fields, bookmarks, page changes, and so on.

To create or access document level scripts in Acrobat, select Advanced > Document Processing >
Document JavaScript, which enables you to add, modify, or delete document level scripts. Document level
scripts are executed after the document has opened, but before the first Page Open event (See “Page
level” on page 43). They are stored within the PDF document.
You can also create Doc level scripts programmatically using the addScript method of the Doc object.
In addition to document level scripts, there are document action scripts that execute when certain
document events occur. Such document events are
●

Document Will Close
This event is triggered before the document is closed.

●

Document Will Save
This event is triggered before the document is saved.

●

Document Did Save
This event is triggered after the document is saved.

●

Document Will Print
This event is triggered, before the document is printed.

●

Document Did Print
This event is triggered after the document is closed.

To access the JavaScript Editor for each of these document actions, select Advanced > Document
Processing > Set Document Action.
You can also create the document actions just described programmatically using the setAction method
of the Doc object.

Page level
Page level scripts are scripts that are executed when a particular page is either closed or opened.
●

Page Open
This event is triggered whenever a new page is viewed and after the drawing of the page has occurred.

●

Page Close
This event is triggered whenever the page being viewed is no longer the current page; that is, the user
switched to a new page or closed the document. Page Close will occur before the Document Will Close
event.

Adobe Acrobat SDK
Developing Acrobat Applications Using JavaScript

JavaScript Contexts in Acrobat
Field level

44

➤ To create a page level script:

1. Click the Pages tab.
2. Right-click a thumbnail and select Page Properties.
3. Select the Actions tab from the Page Properties dialog box.
4. In the Select Trigger list, choose either Page Open or Page Close.
5. In the Select Action list, choose Run a JavaScript.
6. Click Add to open the JavaScript editor.
➤ To access or delete a page level script:

1. Click the Pages tab.
2. Select the page by clicking the page thumbnail.
3. Right-click a thumbnail and select Page Properties.
4. Select the Actions tab from the Page Properties dialog box.
5. Select any of the actions listed in the Actions list.
6. Click Edit or Delete.
Other actions, as listed in the Select Action Menu of the Page Properties dialog box, can be created,
accessed and deleted in the same way.
Page level scripts can also be created programmatically using the setPageAction method of the Doc
object.

Field level
Field level scripts are associated or attached to an Acrobat form field. Field events occur as the user
interacts with the field, either directly or indirectly. Field scripts are typically executed to validate, format,
or calculate form field values. Like document level scripts, field level scripts are stored within the PDF
document.
There are several ways to create or edit field level scripts. The most straightforward manner is to right-click
the form field, select the Properties context menu item and choose the Actions tab. Choose Run a
JavaScript for Select Action and choose how to trigger the script from the Select Trigger Menu.
Field level scripts can also be created programmatically using the setAction method of the Field object.

Batch level
A batch level script is a script that can be applied to a collection of documents, and operates at the
application level. For example, you can define a batch script to print a series of documents or apply
security restrictions to them.
To create or edit a batch level script in Acrobat, select Advanced > Document Processing > Batch
Processing. The document Batch Sequences, available from the Acrobat Family Developer Center, is a
complete tutorial on how to write batch sequences using JavaScript.

Adobe Acrobat SDK
Developing Acrobat Applications Using JavaScript

JavaScript Contexts in Acrobat
Privileged versus non-privileged context

45

Privileged versus non-privileged context
Some JavaScript methods have security restrictions. These methods can be executed only in a privileged
context, which includes console, batch, and application initialization events. All other events (for example,
page open and mouse-up events) are considered non-privileged. In the JavaScript for Acrobat API Reference,
methods with security restrictions are marked by an S in the third column of the quick bar.
The description of each security-restricted method indicates the events during which the method can be
executed.
Beginning with Acrobat 6.0, security-restricted methods can execute in a non-privileged context if the
document is certified by the document author for embedded JavaScript.
Security-restricted methods can also execute in a non-privileged context through the use of a trusted
function (introduced in Acrobat 7.0).
In Acrobat versions earlier than 7.0, menu events were considered privileged contexts. Beginning with
Acrobat 7.0, execution of JavaScript through a menu event is no longer privileged. You can execute
security-restricted methods through menu events in one of the following ways:
●

By enabling the preferences item named Enable Menu Items JavaScript Execution Privileges.

●

By executing a specific method through a trusted function (introduced in Acrobat 7.0). Trusted
functions allow privileged code—code that normally requires a privileged context to execute—to
execute in a non-privileged context. For details and examples, see documentation of the
app.trustedFunction method in the JavaScript for Acrobat API Reference.

Executing privileged methods in a non-privileged context
To illustrate the techniques required, let’s work with a specific method, app.browseForFile. According
to the JavaScript for Acrobat API Reference, this method can only be executed during batch or console
events. This means that we are free to executed this method in the console, or to use it as a part of a batch
sequence. (See the Batch Sequences document, available from the Acrobat Family Developer Center, for a
detailed discussion of the Execute JavaScript command option.)
What happens when we execute this method in a non-privileged context? Create an Acrobat form button,
and attach the following script as a mouse up JavaScript action.
var oRetn = app.browseForDoc({bSave: true});

After clicking the button, an exception is thrown; the console displays the following message:
NotAllowedError: Security settings prevent access to this property or method.
app.browseForDoc:1:Field Button1:Mouse Up

This shows that we have violated the documented security restriction.
If we really want this method in our workflow what do we need to do? We need to move this method to
folder JavaScript and declare it as a trusted function. Why move it to the folder context? Because you can
only declare a function trusted from a folder (console or batch) context.

Adobe Acrobat SDK

JavaScript Contexts in Acrobat

Developing Acrobat Applications Using JavaScript

Executing privileged methods in a non-privileged context

46

Navigate to the user JavaScript folder and open the file config.js in your text editor. Paste the following
script into config.js:
myTrustedBrowseForDoc = app.trustedFunction( function ( oArgs )
{
app.beginPriv();
var myTrustedRetn = app.browseForDoc( oArgs );
app.endPriv();
return myTrustedRetn;
});

For the syntax details of app.trustedFunction, see the JavaScript for Acrobat API Reference. Note that
the privileged script must be enclosed by the app.beginPriv and app.endPriv pair.
Save the file and restart Acrobat (folder JavaScript is read only at startup).
Now create a PDF with a single button on it. The script for that button is
try {
var oRetn = myTrustedBrowseForDoc({bSave: true});
console.println(oRetn.toSource());
} catch(e) {
console.println("User cancelled Save As dialog box");
}

Clicking the button now executes the app.browseForDoc method without throwing the security
exception.
Here is another, more complex, example.

Example 3.1

Executing privileged methods

In this example, we use the app.browseForDoc and the Doc.saveAs methods, both of which have
security restrictions.
In config.js, paste both the myTrustedBrowseForDoc script listed above, and paste this script:
myTrustedSaveAs = app.trustedFunction( function ( doc, oArgs )
{
app.beginPriv();
var myTrustedRetn = doc.saveAs( oArgs );
app.endPriv();
return myTrustedRetn;
});

Note that the Doc object is passed to this trusted function. Now, revise the button described above to read
as follows:
try {
var oRetn = myTrustedBrowseForDoc({bSave: true});
try {
myTrustedSaveAs(this, { cPath: oRetn.cPath, cFS:oRetn.cFS });
} catch(e) { console.println("Save not allowed, perhaps readonly."); }
} catch(e) { console.println("User cancelled Save As dialog box");}

Now, the PDF document, through a mouse up button action, can open a Save As dialog box and save the
current document.

Adobe Acrobat SDK
Developing Acrobat Applications Using JavaScript

JavaScript Contexts in Acrobat
Executing privileged methods through the menu

47

Executing privileged methods through the menu
In versions of Acrobat previous to 7.0, executing JavaScript through a menu was non-privileged. This is no
longer the case. To execute privileged JavaScript through a menu event there are now two choices:
1. Ask the user to enable the Enable Menu Items JavaScript Execution Privileges option, in the JavaScript
section of the Preferences.
2. Use the trusted function approach discussed above.
In this section we discuss the first alternative.
Open config.js, found in the user’s JavaScript folder, and paste the following script:
app.addSubMenu({ cName: "New", cParent: "File", nPos: 0 })
app.addMenuItem({ cName: "Letter", cParent: "New", cExec: "app.newDoc();"});
app.addMenuItem({ cName: "A4", cParent: "New", cExec: "app.newDoc(420,595)"});

As usual, restart Acrobat so that the config.js file is read. Under the File menu, there is now a menu item
named New, with a sub menu with two items, Letter and A4.
With the Enable Menu Items JavaScript Execution Privileges option not enabled, upon the execution of
one of these menu items, either File > New > Letter or File > New > A4 are executed, an alert box appears
declaring that “An internal error occurred”, and the console shows the following error message:
1:Menu Letter:Exec
NotAllowedError: Security settings prevent access to this property or method.
app.newDoc:1:Menu Letter:Exec

The problem is app.newDoc, a method that has a security restriction.
Now enable the Enable Menu Items JavaScript Execution Privileges option and execute the same menu
item again, a new document is created, the menu operates as designed.
The above discussion shows what happens when you try to executed a privileged method through the
menu system and how to work around the restrictions on privileged methods by enabling the Enable
Menu Items JavaScript Execution Privileges option of the JavaScript section of the Preferences.
A note of caution. An Acrobat developer, cannot assume the user has enabled the JavaScript execution
privileges options; indeed, in a corporate setting, enabling this option may not be allowed for security
reasons. An Acrobat developer using JavaScript should perhaps use the trusted function approach, as
discussed in “Executing privileged methods in a non-privileged context” on page 45, which necessarily
implies the installation of folder JavaScript on the user’s system.

Adobe Acrobat SDK
Developing Acrobat Applications Using JavaScript

JavaScript Contexts in Acrobat
Executing privileged methods in a certified document

48

Executing privileged methods in a certified document
Many of the JavaScript methods in Acrobat are restricted for security reasons, and their execution is only
allowed during batch, console or menu events. This restriction is a limitation when enterprise customers
try to develop solutions that require these methods and know that their environment is secure.
Three requirements must be met to make restricted JavaScript methods available to users.
●

You must obtain a digital ID.

●

You must sign the PDF document containing the restricted JavaScript methods using the digital ID.
For details on where you can obtain digital IDs and the procedures for using them to sign documents,
see Acrobat Help.

●

The recipient should trust the signer for certified documents and JavaScript.
For details, see Acrobat Help.

All trusted certificates can be accessed by selecting Certificates from Advanced > Manage Trusted
Identities in the Acrobat main menu.

4

Creating and Modifying PDF Documents
This chapter provides a detailed overview of how to apply JavaScript in order to dynamically create PDF
files, modify them, and convert PDF files to XML format.
Topic

Description

See

Creating and modifying PDF files

Discusses methods for reading a document using page 49
JavaScript and surveys methods for modifying the
document, by adding fields, links and even
content.

Combining PDF documents

Combine multiple PDF documents.

page 51

Combining and extracting files

Combine multiple documents that are not
necessarily PDF files.

page 51

Creating file attachments

Programmatically attach a file to a PDF document. page 52
This includes examples of communicating with
the attachments, and extracting data from and
writing to the attachments.

Cropping and rotating pages

Covers methods for cropping and rotating pages. page 55

Extracting, moving, deleting, replacing,
and copying pages

Techniques and methods for manipulating pages. page 56

Adding watermarks and backgrounds

Applying watermarks and backgounds using
JavaScript methods.

page 58

Converting PDF documents to XML
format

Use the saveAs method of the Doc object to
convert a document to XML format.

page 59

Creating and modifying PDF files
The Acrobat extensions to JavaScript provide support for dynamic PDF file creation and content
generation. This means that it is possible to dynamically create a new PDF file and modify its contents in an
automated fashion. This can help make a document responsive to user input and can enhance the
workflow.
To create a new PDF file, invoke the newDoc method of the app object, as shown in the example below:
var myDoc = app.newDoc();

This statement creates a blank PDF document and is used primarily for testing purposes.

49

Adobe Acrobat SDK

Creating and Modifying PDF Documents

Developing Acrobat Applications Using JavaScript

Creating and modifying PDF files

50

Once this statement has been executed from the console, you can manipulate the page by invoking
methods contained within the Doc object, as indicated in the following table. Details of these methods are
found in the JavaScript for Acrobat API Reference.

JavaScript for manipulating a PDF document
Content

Object

Methods

page

Doc

newPage, insertPages, replacePages

page

template

spawn

annot

Doc

addAnnot

field

Doc

addField

icon

Doc

addIcon

link

Doc

addLink

document-level
JavaScript

Doc

addScript

thumbnails

Doc

addThumbnails

bookmark

Doc.bookmarkRoot

createChild, insertChild

web link

Doc

addWebLinks

template

Doc

createTemplate

The Doc.newDoc() method cannot write text content to the newly created document. To do that, you
need to use the Report object.

Example 4.1

Creating a document with content

The following example creates a PDF document, sets the font size, sets the color to blue, and writes a
standard string to the document using the writeText method of the Report object. Finally, it opens the
document in the viewer. See the JavaScript for Acrobat API Reference for details of this object, its properties
and methods and for additional examples.
var rep = new Report();
rep.size = 1.2;
rep.color = color.blue;
rep.writeText("Hello World!");
rep.open("My Report");

The Report object has many useful applications. With it, for example, you can create a document that
reports back a list of all form fields in the document, along with their types and values; another application
is to summarize all comments in a document. The JavaScript for Acrobat API Reference has an example of
the latter application in the Report object section.

Adobe Acrobat SDK

Creating and Modifying PDF Documents

Developing Acrobat Applications Using JavaScript

Combining PDF documents

51

Combining PDF documents
You can customize and automate the process of combining PDF documents.
If you would like to combine multiple PDF files into a single PDF document, you can do so through a series
of calls to the Doc object’s insertPages method.

Example 4.2

Creating a new document from two other documents

// Create a new PDF document:
var newDoc = app.newDoc();
// Insert doc1.pdf:
newDoc.insertPages({
nPage: -1,
cPath: "/c/temp/doc1.pdf",
});
// Insert doc2.pdf:
newDoc.insertPages({
nPage: newDoc.numPages-1,
cPath: "/c/temp/doc2.pdf",
});
// Save the new document:
newDoc.saveAs({
cPath: "/c/temp/myNewDoc.pdf";
});
// Close the new document without notifying the user:
newDoc.closeDoc(true);

Combining and extracting files
It is possible to combine several PDF files using the Doc.insertPages() method.

Example 4.3

Combining several PDF files

In this example, a document is opened with an absolute path reference, then other PDF files in the same
folder are appended to the end of the document. For convenience, the files that are appended are placed
in an array for easy execution and generalization.
var doc = app.openDoc({
cPath: "/C/temp/doc1.pdf"
})
aFiles = new Array("doc2.pdf","doc3.pdf");
for ( var i=0; i < aFiles.length; i++) {
doc.insertPages ({
nPage: doc.numPages-1,
cPath: aFiles[i],
nStart: 0
});
}

Adobe Acrobat SDK

Creating and Modifying PDF Documents

Developing Acrobat Applications Using JavaScript

Creating file attachments

52

Another problem is to combine several files of possibly different file types. In recent versions of Acrobat,
the notion of a binder was introduced. There is a nice UI for combining files of different formats. How do
you do it programmatically?

Example 4.4

Combining several files of different formats

In this example, an initial PDF file is opened, and all other files are appended to it.
doc = app.openDoc({ cPath: "/C/temp/doc1.pdf" })
// List of files of different extensions
aFiles = new Array( "doc2.eps", "doc3.jpg", "doc4.pdf");
for ( var i=0; i < aFiles.length; i++) {
// Open and convert the document
newDoc = app.openDoc({
oDoc: doc,
cPath: aFiles[i],
bUseConv: true
})
// Save the new PDF file to a temp folder
newDoc.saveAs({ cPath: "/c/temp/tmpDoc.pdf" });
// Close it without notice
newDoc.closeDoc(true);
// Now insert that PDF file just saved to the end of the first document
doc.insertPages ({
nPage: doc.numPages-1,
cPath: "/c/temp/tmpDoc.pdf",
nStart: 0
});
}

You can also programmatically extract pages and save them to a folder.

Example 4.5

Extracting and saving pages

Suppose the current document consists of a sequence of invoices, each of which occupies one page. The
following code creates separate PDF files, one for each invoice:
var filename = "invoice";
for (var i = 0; i < this.numPages; i++)
this.extractPages({
nStart: i,
cPath : filename + i + ".pdf"
});

Creating file attachments
Another way you can “combine files” is by attaching one or more files to your PDF document. This is useful
for packaging a collection of documents and send them together by emailing the PDF file. This section
describes the basic object, properties and methods of attaching and manipulating attachments.

Adobe Acrobat SDK

Creating and Modifying PDF Documents

Developing Acrobat Applications Using JavaScript

Creating file attachments

These are the objects, properties and methods relevant to file attachments.
Name

Description

Doc.createDataObject()

Creates a file attachment.

Doc.dataObjects

Returns an array of Data objects
representing all files attached to the
document.

Doc.exportDataObject()

Saves the file attachment to the local file
system

Doc.getDataObject()

Acquires the Data object of a particular
attachment.

Doc.importDataObject()

Attaches a file to the document.

Doc.removeDataObject()

Removes a file attachment from the
document.

Doc.openDataObject()

Returns the Doc object for an attached
PDF file.

Doc.getDataObjectContents()

Allows access to the contents of the file
attachment associated with a Data
object.

Doc.setDataObjectContents()

Rights to the file attachment.

util.streamFromString()

Converts a stream from a string

util.stringFromStream()

Converts a string from a stream.

Example 4.6

Saving form data to and reading form data from an attachment

This example takes the response given in a text field of this document and appends it to an attached
document. (Perhaps this document is circulating by email, and the user can add in their comments
through a multiline text field.) This example uses four of the methods listed above.
var v = this.getField("myTextField").value;
// Get the contents of the file attachment with the name "MyNotes.txt"
var oFile = this.getDataObjectContents("MyNotes.txt");
// Convert the returned stream to a string
var cFile = util.stringFromStream(oFile, "utf-8");
// Append new data at the end of the string
cFile += "\r\n" + v;
// Convert back to a stream
oFile = util.streamFromString( cFile, "utf-8");
// Overwrite the old attachment
this.setDataObjectContents("MyNotes.txt", oFile);
// Read the contents of the file attachment to a multiline text field
var oFile = this.getDataObjectContents("MyNotes.txt");
var cFile = util.stringFromStream(oFile, "utf-8");
this.getField("myTextField").value = cFile;

53

Adobe Acrobat SDK

Creating and Modifying PDF Documents

Developing Acrobat Applications Using JavaScript

Creating file attachments

54

Beginning with Acrobat 8, the JavaScript interpreter includes E4X, the ECMA-357 Standard that provides
native support of XML in JavaScript. See the document ECMAScript for XML (E4X) Specification for the
complete specification of E4X. The next example illustrates the use of E4X and file attachments.

Example 4.7

Accessing an XML attachment using E4X

The following script describes a simple database system. The database is an XML document attached to
the PDF file. The user enters the employee ID into a text field, the JavaScript accesses the attachment, finds
the employee’s record and displays the contents of the retrieved record in form fields.
We have a PDF file, employee.pdf, with three form fields, whose names are employee.id,
employee.name.first and employee.name.last. Attached to the PDF file is an XML document
created by the following script:
// Some E4X code to create a database of info
x = ;
function popXML(x,id,fname,lname)
{
y = ;
y.employee.@id = id;
y.employee.name.first = fname;
y.employee.name.last = lname;
x.employee += y.employee;
}
popXML(x,"334234", "John", "Public");
popXML(x,"324234", "Jane", "Doe");
popXML(x,"452342", "Davey", "Jones");
popXML(x,"634583", "Tom", "Jefferson");

Copy and paste this code into the console and execute it. You’ll see the XML document as the output of
this script. The output was copied and pasted into a document named employee.xml, and saved to the
same folder as employee.pdf.
You can attach employee.xml using the UI, but the script for doing so is as follows:
var thisPath = this.path.replace(/\.pdf$/, ".xml");
try { this.importDataObject("employees", thisPath); }
catch(e) { console.println(e) };

Of the three form fields in the document employee.pdf, only employee.id has any script. The
following is a custom keystroke script:
if (event.willCommit) {
try {
// Get the data contents of the "employees" attachment
var oDB = this.getDataObjectContents("employees");
// Convert to a string
var cDB = util.stringFromStream(oDB);
// Use the eval method to evaluate the string, you get an XML variable
var employees = eval(cDB);
// Retrieve record with the id input in the employee.id field
var record = employees.employee.(@id == event.value);
// If the record is an empty string, or there was nothing entered...
if ( event.value != "" && record.toString() == "" ) {
app.alert("Record not found");
event.rc = false;
}

Adobe Acrobat SDK

Creating and Modifying PDF Documents

Developing Acrobat Applications Using JavaScript

Cropping and rotating pages

// Populate the two other fields
this.getField("employee.name.first").value = record.name.first;
this.getField("employee.name.last").value = record.name.last;
} catch(e) {
app.alert("The DB is not attached to this document!");
event.rc = false;
}
}

Cropping and rotating pages
In this section we discuss the JavaScript API for cropping and rotating a page.

Cropping pages
The Doc object provides methods for setting and retrieving the page layout dimensions. These are the
setPageBoxes and getPageBox methods. There are five types of boxes available:
●

Art

●

Bleed

●

Crop

●

Media

●

Trim

See Section 10.10.1 of the PDF Reference version 1.7 for a discussion of these types of boxes.
The setPageBoxes method accepts the following parameters:
cBox — the type of box
nStart — the zero-based index of the beginning page
nEnd — the zero-based index of the last page
rBox — the rectangle in rotated user space

For example, the following code crops pages 2-5 of the document to a 400 by 500 pixel area:
this.setPageBoxes({
cBox: "Crop",
nStart: 2,
nEnd: 5,
rBox: [100,100,500,600]
});

The getPageBox method accepts the following parameters:
cBox — the type of box
nPage — the zero-based index of the page

For example, the following code retrieves the crop box for page 3:
var rect = this.getPageBox("Crop", 3);

55

Adobe Acrobat SDK
Developing Acrobat Applications Using JavaScript

Creating and Modifying PDF Documents
Extracting, moving, deleting, replacing, and copying pages

56

Rotating pages
You can use JavaScript to rotate pages in 90-degree increments in the clockwise direction relative to the
normal position. This means that if you specify a 90-degree rotation, no matter what the current
orientation is, the upper portion of the page is placed on the right side of your screen.
The Doc object’s setPageRotations and getPageRotation methods are used to set and retrieve
page rotations.
The setPageRotations method accepts three parameters:
nStart — the zero-based index of the beginning page
nEnd — the zero-based index of the last page
nRotate — 0, 90, 180, or 270 are the possible values for the clockwise rotation

In the following example, pages 2 and 5 are rotated 90 degrees in the clockwise direction:
this.setPageRotations(2,5,90);

To retrieve the rotation for a given page, invoke the Doc object getPageRotation method, which
requires only the page number as a parameter. The following code retrieves and displays the rotation in
degrees for page 3 of the document:
var rotation = this.getPageRotation(3);
console.println("Page 3 is rotated " + rotation + " degrees.");

Extracting, moving, deleting, replacing, and copying pages
The Doc object, in combination with the app object, can be used to extract pages from one document and
place them in another, and moving or copying pages within or between documents.
The app object an be used to create or open any document. To create a new document, invoke its newDoc
method, and to open an existing document, invoke its openDoc method.
The Doc object offers three useful methods for handling pages:
insertPages — Inserts pages from the source document into the current document
deletePages — Deletes pages from the document
replacePages — Replaces pages in the current document with pages from the source document.

These methods enable you to customize the page content within and between documents.
Suppose you would like to remove pages within a document. Invoke the Doc object’s deletePages
method, which accepts two parameters:
nStart — the zero-based index of the beginning page
nEnd — the zero-based index of the last page

For example, the following code deletes pages 2 through 5 of the current document:
this.deletePages({nStart: 2, nEnd: 5});

Adobe Acrobat SDK
Developing Acrobat Applications Using JavaScript

Creating and Modifying PDF Documents
Extracting, moving, deleting, replacing, and copying pages

57

Suppose you would like to copy pages from one document to another. Invoke the Doc object
insertPages method, which accepts four parameters:
nPage — the zero-based index of the page after which to insert the new pages
cPath — the device-independent path of the source file
nStart — the zero-based index of the beginning page
nEnd — the zero-based index of the last page

For example, the following code inserts pages 2 through 5 from mySource.pdf at the beginning of the
current document:
this.insertPages({
nPage: -1,
cPath: "/C/temp/mySource.pdf",
nStart: 2,
nEnd: 5
});

You can combine these operations to extract pages from one document and move them to another (they
will be deleted from the first document). The following code will extract pages 2 through 5 in
mySource.pdf and move them into myTarget.pdf :
// The operator, this, represents myTarget.pdf
// First copy the pages from the source to the target document
this.insertPages({
nPage: -1,
cPath: "/C/temp/mySource.pdf",
nStart: 2,
nEnd: 5
});
// Now delete the pages from the source document
var source = app.openDoc({cPath:"/C/temp/mySource.pdf"});
source.deletePages({nStart: 2, nEnd: 5});

To replace pages in one document with pages from another document, invoke the target document’s
replacePages method, which accepts four parameters:
nPage — The zero-based index of the page at which to start replacing pages
cPath — The device-independent pathname of the source file
nStart — The zero-based index of the beginning page
nEnd — The zero-based index of the last page

In the following example, pages 2 through 5 from mySource.pdf replace pages 30 through 33 of
myTarget.pdf :
// This represents myTarget.pdf
this.replacePages({
nPage: 30,
cPath: "/C/temp/mySource.pdf",
nStart: 2,
nEnd: 5
});

Adobe Acrobat SDK

Creating and Modifying PDF Documents

Developing Acrobat Applications Using JavaScript

Adding watermarks and backgrounds

58

To safely move pages within the same document, it is advisable to perform the following sequence:
1. Copy the source pages to a temporary file.
2. Insert the pages in the temporary file at the new location in the original document.
3. Delete the source pages from the original document.
The following example moves pages 2 through 5 to follow page 30 in the document:
// First create the temporary document:
var tempDoc = app.newDoc("/C/temp/temp.pdf");
// Copy pages 2 to 5 into the temporary file
tempDoc.insertPages({
cPath: "/C/temp/mySource.pdf",
nStart: 2,
nEnd: 5
});
// Copy all of the temporary file pages back into the original:
this.insertPages({
nPage: 30,
cPath: "/C/temp/temp.pdf"
});
// Now delete pages 2 to 5 from the source document
this.deletePages({nStart: 2, nEnd: 5});

Adding watermarks and backgrounds
The Doc object addWatermarkFromText and addWatermarkFromFile methods create watermarks
within a document, and place them in optional content groups (OCGs).
The addWatermarkFromFile method adds a page as a watermark to the specified pages in the
document. The example below adds the first page of watermark.pdf as a watermark to the center of all
pages within the current document:
this.addWatermarkFromFile("/C/temp/watermark.pdf");

In the next example, the addWatermarkFromFile method is used to add the second page of
watermark.pdf as a watermark to the first 10 pages of the current document. It is rotated
counterclockwise by 45 degrees, and positioned one inch down and two inches over from the top left
corner of each page:
this.addWatermarkFromFile({
cDIPath: "/C/temp/watermark.pdf",
nSourcePage: 1,
nEnd: 9,
nHorizAlign: 0,
nVertAlign: 0,
nHorizValue: 144,
nVertValue: -72,
nRotation: 45
});

Adobe Acrobat SDK
Developing Acrobat Applications Using JavaScript

Creating and Modifying PDF Documents
Converting PDF documents to XML format

59

It is also possible to use the addWatermarkFromText method to create watermarks. In this next
example, the word Confidential is placed in the center of all the pages of the document, and its font
helps it stand out:
this.addWatermarkFromText(
"Confidential",
0,
font.Helv,
24,
color.red
);

Converting PDF documents to XML format
Since XML is often the basis for information exchange within web services and enterprise infrastructures, it
may often be useful to convert your PDF documents into XML format.
It is a straightforward process to do this using the Doc object saveAs method, which not only performs
the conversion to XML, but also to a number of other formats.
In order to convert your PDF document to a given format, you will need to determine the
device-independent path to which you will save your file, and the conversion ID used to save in the desired
format. A list of conversion IDs for all formats is provided in the JavaScript for Acrobat API Reference found at
the Acrobat Family Developer Center. For XML, the conversion ID is com.adobe.acrobat.xml-1-00.
The following code converts the current PDF file to XML and saves it at C:\temp\test.xml:
this.saveAs("/c/temp/test.xml", "com.adobe.acrobat.xml-1-00");

5

Print Production
This chapter will provide you with an in-depth understanding of the ways in which you can manage print
production workflows for PDF documents.
Topic

Description

See

Setting print options

Gives brief descriptions of the printParams object, used to page 60
set print options.

Printing PDF documents

Discusses printing a document using the print method
of the Doc object.

page 62

Silent printing

Print document with little user interaction.

page 63

Printing comments and forms

Setting the print job to print just forms.

page 64

Booklet printing

Use the print method to create a booklet. Various
options for doing this are discussed.

page 64

Setting advanced print options

Discusses how to set the print job to some of the advanced page 65
print options: marks and bleeds, PostScript® printing,
setting output and font options.

Setting print options
Since printing involves sending pages to an output device, there are many options that can affect print
quality. JavaScript can be used to enhance and automate the use of these options in print production
workflows, primarily through the use of the printParams object, whose properties and methods are
described in the following table.

PrintParams properties
Property

Description

binaryOK

Binary printer channel is supported.

bitmapDPI

DPI used for bitmaps or rasterizing transparency.

booklet

An object used to set properties of booklet printing.

colorOverride

Uses color override settings.

colorProfile

Color profile based on available color spaces.

constants

Wrapper object for printParams constants.

downloadFarEastFonts

Sends Far East fonts to the printer.

fileName

fileName is used when printing to a file instead of a printer.

60

Adobe Acrobat SDK

Print Production

Developing Acrobat Applications Using JavaScript

Setting print options

Property

Description

firstPage

The first zero-based page to be printed.

flags

A bit field of flags to control printing options.

fontPolicy

Used to determine when fonts are emitted.

gradientDPI

The DPI used for rasterizing gradients.

interactive

Sets the level of interaction for the user.

lastPage

The last zero-based page to be printed.

nUpAutoRotate

Auto rotate pages during multiple pages per sheet printing.

nUpNumPagesH

Number of pages to lay out horizontally during multiple pages per
sheet printing.

nUpNumPagesV

Number of pages to lay out vertically during multiple pages per sheet
printing.

nUpPageBorder

Determines whether a page boundary is drawn and printed during
multiple pages per sheet printing.

nUpPageOrder

Determines how the multiple pages are laid out on the sheet for
multiple pages per sheet printing.

pageHandling

How pages will be handled (fit, shrink, or tiled).

pageSubset

Even, odd, or all pages are printed.

printAsImage

Sends pages as large bitmaps.

printContent

Determines whether form fields and comments will be printed.

printerName

The name of the destination printer.

psLevel

The level of PostScript emitted to the printer.

rasterFlags

A bit field of flags for outlines, clips, and overprint.

reversePages

Prints pages in reverse order.

tileLabel

Labels each page of tiled output.

tileMark

Output marks to cut the page and where overlap occurs.

tileOverlap

The number of points that tiled pages have in common.

tileScale

The amount that tiled pages are scaled.

transparencyLevel

The degree to which high level drawing operators are preserved.

userPrinterCRD

Determines whether the printer Color Rendering Dictionary is used.

useT1Conversion

Determines whether Type 1 fonts will be converted.

61

Adobe Acrobat SDK

Print Production

Developing Acrobat Applications Using JavaScript

Printing PDF documents

62

In addition to the properties of the printParams object, the app object’s printColorProfiles and
printerNames properties provide a list of available color spaces and printer names, respectively.
When printing a document, any comments and form fields of the document may or may not print,
depending on the settings of the individual annotations. The print property of the Annotation and Field
objects is used to set whether an individual annotation is printed.

Printing PDF documents
It is possible to use JavaScript to specify whether a PDF document is sent to a printer or to a PostScript file.
In either case, to print a PDF document, invoke the Doc object print method. Its parameters are
described in the following table.

Print method parameters
Parameter

Description

bAnnotations

Determines whether to print annotations.

bPrintAsImage

Determines whether to print each page as an image.

bReverse

Determines whether to print in reverse page order.

bShrinkToFit

Determines whether the page is shrunk to fit the imageable area of the
printed page.

bSilent

Suppresses the Cancel dialog box while the document is printed.

bUI

Determines whether to present a user interface to the user.

nEnd

The zero-based index of the last page.

nStart

The zero-based index of the beginning page.

printParams

The printParams object containing the printing settings.
Note: The printParams parameter is available in Acrobat 6.0 or later. If this
parameter is passed, any other parameters are ignored.

In the first example below, pages 1-10 of the document are sent to the default printer, printed silently
without user interaction, and are shrunk to fit the imageable area of the pages:
this.print({
bUI: false,
bSilent: true,
bShrinkToFit: true,
nStart: 1,
nEnd: 10
});

The syntax above is used for versions of Acrobat previous to 6.0.
For Acrobat 6.0 or later, the recommend method is to pass a printParams object to the Doc.print
method. All the subsequent examples use this method.

Adobe Acrobat SDK
Developing Acrobat Applications Using JavaScript

Print Production
Silent printing

63

To print the document to a PostScript file, obtain the printParams object by invoking the Doc object
getPrintParams method. Set its printerName property to the empty string, and set its fileName
property to a string containing the device-independent path of the PostScript file to which it will be
printed, as shown in the following example:
var pp = this.getPrintParams();
pp.printerName = "";
// File name must be a safe path
pp.fileName = "/C/temp/myPSDoc.ps";
this.print(pp);

If you would like send the file to a particular printer, you can specify the printer by setting the
printerName property of the printParams object, as shown in the following example:
var pp = this.getPrintParams();
pp.interactive = pp.constants.interactionLevel.automatic;
pp.printerName = "Our office printer";
this.print(pp);

Silent printing
There are various ways to print a document without requiring user interaction. One way is to use the Doc
object print method and set the bSilent attribute to true, as the following example shows.
this.print({bUI: false, bSilent: true, bShrinkToFit: true});

Beginning with version 7.0, non-interactive printing can only be done in batch and console events. Using
the printParams object, this is the script for printing silently:
var pp = this.getPrintParams();
pp.interactive = pp.constants.interactionLevel.silent;
this.print(pp);

If you would like to print without requiring user interaction, and would like the progress monitor and
Cancel dialog box to be removed when printing is complete, use the interactive property as shown in
the following example:
var pp = this.getPrintParams();
pp.interactive = pp.constants.interactionLevel.automatic;

There are many options you can choose without requiring user interaction. For example, you can select
the paper tray:
var fv = pp.constants.flagValues;
pp.flags |= fv.setPageSize;

These coding approaches may be used in menus or buttons within a PDF file, may exist at the folder or
batch levels, and are available through Acrobat or Adobe Reader 6.0 or later. For more information, see the
JavaScript for Acrobat API Reference, as well as the Acrobat SDK samples SDKSilentPrint.js and
SDKJSSnippet1.pdf.

Adobe Acrobat SDK

Print Production

Developing Acrobat Applications Using JavaScript

Printing comments and forms

64

Printing comments and forms
The printContent property of the printParams object can be used to control whether document
content, form fields, and comments will be printed. In the following example, only the form field contents
will be printed (this is useful when sending data to preprinted forms):
var pp = this.getPrintParams();
pp.interactive = pp.constants.interactionLevel.silent;
pp.printContent = pp.constants.printContent.formFieldsOnly;
this.print(pp);

Booklet printing
Beginning with Acrobat 8.0, you can print booklets. To do so, begin by getting the printParams object:
var pp = this.getPrintParams();

Then set the pageHandling property to booklet:
pp.pageHandling = pp.constants.handling.booklet;

Use the booklet property of printParams to set the specialized printing parameters for booklet printing.
pp.booklet is an object with properties:
binding — determines the paper binding direction and the page arrange order
duplexMode — determines the duplex printing mode
subsetFrom — determines the first booklet sheet to be printed. Independently from the general

page range selection
subsetTo — determines the last booklet sheet to be printed

All the properties above take integers for their values.
The value for binding is set through the properties of the constants.bookletBindings object of
printParams, as illustrated in the following example.

Example 5.1

Set up booklet printing for right-side binding of text and print

var pp = this.getPrintParams();
pp.pageHandling = pp.constants.handling.booklet;
pp.booklet.binding = pp.constants.bookletBindings.Right;
this.print(pp);

The constants.bookBindings object has four properties: Left (the default), Right, LeftTall and
RightTall.
The value for duplexMode is set through the properties of the constants.bookletDuplexModes
object of printParams

Example 5.2

Print booklet in duplex mode, printing only the front pages

pp.pageHandling = pp.constants.handling.booklet;
pp.booklet.duplexMode = pp.constants.bookletDuplexModes.FrontSideOnly;
this.print(pp);
constants.bookletDuplexModes has three properties: BothSides, FrontSideOnly and
BackSideOnly. For printers that print only on one side, use FrontSideOnly first then reinsert the
printed pages and print again with BacksideOnly to complete a manual duplex printing.

Adobe Acrobat SDK
Developing Acrobat Applications Using JavaScript

Print Production
Setting advanced print options

65

Setting advanced print options
You can set the properties of the printParams object to specify advanced options including output, marks
and bleeds, transparency flattening, PostScript options, and font options.

Specifying output settings
You can obtain a listing of printer color spaces available by invoking the app object
printColorProfiles method. You can then assign one of these values to the printParams object
colorProfile property.
In addition, you can set the flags property of the printParams object to specify advanced output
settings, such as applying proof settings, shown in the example below:
var pp = this.getPrintParams();
var fv = pp.constants.flagValues;
pp.flags |= fv.applySoftProofSettings;
this.print(pp);

Specifying marks and bleeds
You can specify the types of tile marks and where overlap occurs by setting the tileMark property of the
printParams object. For example, in the following code, Western style tile marks are printed:
var pp = this.getPrintParams();
pp.tileMark = pp.constants.tileMarks.west;
this.print(pp);

Setting PostScript options
You can set the flags property of the printParams object to specify advanced PostScript settings, such as
emitting undercolor removal/black generation, shown in the example below:
var pp = this.getPrintParams();
var fv = pp.constants.flagValues;
pp.flags &= ~(fv.suppressBG | fv.suppressUCR);
this.print(pp);

In addition, you can set the psLevel property of the printParams object to specify the level of PostScript
emitted to PostScript printers. If the printer only supports PostScript level 1, set the printParams
object’s printAsImage property to true.

Setting font options
You can control the font policy by setting the fontPolicy property of the printParams object. There are
three values that may be used:
everyPage — emit needed fonts for every page, freeing fonts from the previous page. This is useful

for printers having a small amount of memory.
jobStart — emit all fonts at the beginning of the print job, free them at the end of the print job. This
is useful for printers having a large amount of memory.
pageRange — emit the fonts needed for a given range of pages, free them once those pages are

printed. This can be used to optimize the balance between memory and speed constraints.

Adobe Acrobat SDK
Developing Acrobat Applications Using JavaScript

Print Production
Setting advanced print options

66

In the following example, all the fonts are emitted at the beginning of the print job, and freed once the job
is finished:
var pp = this.getPrintParams();
pp.fontPolicy = pp.constants.fontPolicy.jobStart;
this.print(pp);

You can also control whether Type 1 fonts will be converted to alternative font representations, by setting
the useT1Conversion property of the printParams object. There are three values that can be used:
auto — let Acrobat decide whether to disable the conversion, based on its internal list of printers that

have problems with these fonts.
use — allow conversion of Type 1 fonts.
noUse — do not allow conversion of Type 1 fonts.

In the following example, conversion of Type 1 fonts is set to automatic:
var pp = this.getPrintParams();
pp.useT1Conversion = pp.usages.useT1Conversion.auto;
this.print(pp);

Finally, it is possible to send Far East fonts to the printer by setting the printParams object’s
downloadFarEastFonts property to true.

6

Using JavaScript in Forms
In this chapter you will learn how to extend the functionality of Acrobat forms through the application of
JavaScript. You will learn how to generate, modify, and enhance all types of PDF forms and the elements
they contain, and ensure the proper collection and export of information in various formats relevant to
your workflow needs. In addition, you will understand how to leverage the XML Forms Architecture (XFA)
so that your presentation format will be not only responsive to user input, but will also ensure that the
information can be exchanged with web services and enterprise infrastructures.
Topic

Description

See

Forms essentials

Discusses the various properties and methods of Acrobat page 67
forms, and how to process user interaction.

Task-based topics

Includes such tasks as highlighting required fields,
setting a field with a hierarchal naming scheme, setting
tab and calculation order.

Introduction to XML forms
architecture (XFA)

Gives on overview of XML forms and discusses the use of page 99
JavaScript for Acrobat in an XML context.

Making forms accessible

Guidelines for making an Acrobat form accessible.

Using JavaScript to secure forms

Discusses techniques for encrypting a document for a list page 110
of recipients.

page 86

page 107

Forms essentials
You can extend the capability of your forms by using JavaScript to automate formatting, calculations, and
data validation. In addition, you can develop customized actions assigned to user events. Finally, it is
possible for your forms to interact with databases and web services.

About PDF forms
There are two types of PDF forms: Acrobat forms and Adobe LiveCycle Designer forms (XML form object
model).
Acrobat forms present information using form fields. They are useful for providing the user with a
structured format within which to view or print information. Forms permit the user to fill in information,
select choices, and digitally sign the document. Once the user has entered data, the information within the
PDF form can be sent to the next step in the workflow for extraction or, in the case of browser-based forms,
immediately transferred to a database. If you are creating a new form, the recommended type is LiveCycle
Designer forms since its format readily allows for web service interactions and compatibility with
document processing needs within enterprise-wide infrastructures.
The XML form object model uses a document object model (DOM) architecture to manage the
components that comprise a form. These include the base template, the form itself, and the data

67

Adobe Acrobat SDK
Developing Acrobat Applications Using JavaScript

Using JavaScript in Forms
About PDF forms

68

contained within the form fields. In addition, all calculations, validations, and formatting are specified and
managed within the DOM and XML processes.
Static XML forms were supported in Acrobat 6.0, and dynamic XML forms are now supported in Acrobat 7.0.
Both types are created using LiveCycle Designer. A static XML form presents a fixed set of text, graphics,
and field areas at all times. Dynamic XML forms are created by dividing a form into a series of subforms and
repeating subforms. They support dynamically changing fields that can grow or shrink based on content,
variable-size rows and tables, and intelligent data import/export features.

Elements of Acrobat forms
The form fields used in Acrobat forms are the basis of interaction with the user. They include buttons,
check boxes, combo boxes, list boxes, radio buttons, text fields, and digital signature fields. In addition, you
can enhance the appearance and value of your forms through the use of tables, templates, watermarks,
and other user interface elements such as bookmarks, thumbnails, and dialog boxes. Finally, the JavaScript
methods you define in response to events will help customize the utility and behavior of the form within
the context of its workflow.
Text fields can be useful for either presenting information or collecting data entered by the user, such as an
address or telephone number.
Digital signature fields can be used to ensure the security of a document.
When presenting the user with decisions or choices, you can use check boxes and radio buttons for a
relatively small set of choices, or list boxes and combo boxes for a larger set of dynamically changing
choices.

Guidelines for creating a new form
When designing a PDF form, consider first its purpose and the data it must manage. It may be that the
same page is used in multiple contexts, depending on user interactions and decisions. In this case, there
may be multiple sets of form fields. When this occurs, treat each set of form fields as a different problem, as
though each set had its own page. This will also require extra logic applied to visibility settings. Your form
design may have dynamically changing features such as the current date, as well as convenience options
such as automatic generation of email messages. It may even have a dynamically changing appearance
and layout which is responsive to user interactions.
Usability is a major factor in the design of forms since they are essentially graphical user interfaces, so
layout and clarity will be a major consideration. Finally, consider the medium in which the form will be
presented: screens with limited resolution may affect your decisions, and printing characteristics may also
be relevant.
When creating forms programmatically, consider the form elements that will be needed for a given area.
Declare those variables associated with the form elements, and apply logical groupings to those elements
that belong to the same collections, such as radio buttons or check boxes. This will simplify the task of
assigning properties, formatting options, validation scripts, calculation scripts, and tabbing order to each
of the individual form elements.

Adobe Acrobat SDK

Using JavaScript in Forms

Developing Acrobat Applications Using JavaScript

Creating Acrobat form fields

69

The creation of a new form, whether done through the Acrobat layout tools or LiveCycle Designer, or
programmatically through JavaScript, will require that you consider the following:
●

How the form fields will be positioned.

●

Which form fields will be associated in collections so that their properties can be set with consistency
and efficiency.

●

How size, alignment, and distribution of form fields within the document will be determined.

●

When and how to set up duplicate form fields so that when the user types information into one form
field, that information automatically appears in the duplicate form fields.

●

When to create multiple form fields for array-based access and algorithms.

●

The tab order of form fields.

Creating Acrobat form fields
There are seven types of Acrobat form fields, each associated with a field type value as shown in the
following table.

Acrobat form field types
Form field

Field type value

Button

button

Check box

checkbox

Combo box

combobox

List box

listbox

Radio button

radiobutton

Text field

text

Digital signature

signature

You can use JavaScript to create a form field by invoking the addField method of the Doc object, which
returns a Field object. This method permits you to specify the following information:
●

The field name. This may include hierarchical syntax in order to facilitate logical groupings. For
example, the name myGroup.firstField implies that the form field firstField belongs to a
group of fields called myGroup. The advantage of creating logical hierarchies is that you can enforce
consistency among the properties of related form fields by setting the properties of the group, which
automatically propagate to all form fields within the group.

●

One of the seven field type values listed above, surrounded by quotes.

●

The page number where the form field is placed, which corresponds to a zero-based indexing scheme.
Thus, the first page is considered to be page 0.

●

The location, specified in rotated user space (the origin is located at the bottom left corner of the page),
on the page where the form field is placed. The location is specified through the use of an array of four
values. The first two values represent the coordinates of the upper left corner, and the second two
values represent the coordinates of the lower right corner: [upper-left x, upper-left y,
lower-right x, lower-right y].

Adobe Acrobat SDK

Using JavaScript in Forms

Developing Acrobat Applications Using JavaScript

Setting Acrobat form field properties

70

For example, suppose you would like to place a button named myButton on the first page of the
document. Assume that the button is one inch wide, one inch tall, and located 100 points in from the left
side of the page and 400 points up from the bottom of the page (there are 72 points in 1 inch). The code
for creating this button would appear as follows:
var
var
var
var
var

name = "myButton";
type = "button";
page = 0;
location = [100, 472, 172, 400];
myField = this.addField(name, type, page, location);

This approach to creating form fields is applicable to all fields, but it should be noted that radio buttons
require special treatment. Since a set of radio buttons represents a set of mutually exclusive choices, they
belong to the same group. Because of this, the names of all radio buttons in the same group must be
identical. In addition, the export values of the set of radio buttons must be set with a single statement, in
which an array of values are assigned by the exportValues property of the Field object.
For example, suppose we would like to create a set of three radio buttons, each 12 points wide and 12
points high, all named myRadio. We will place them on page 5 of the document, and their export values
will be Yes, No, and Cancel. They can be created as shown in the code given below:
var name = "myRadio";
var type = "radiobutton";
var page = 5;
var rb = this.addField(name, type, page, [400, 442, 412, 430]);
this.addField(name, type, page, [400, 427, 412, 415]);
this.addField(name, type, page, [400, 412, 412, 400]);
rb.exportValues=["Yes", "No", "Cancel"];

Setting Acrobat form field properties
Javascript provides a large number of properties and methods for determining the appearance and
associated actions of form fields. In this section you will learn what properties and methods are available,
and how to write scripts that control the appearance and behavior of form fields.
The list of topics in this section is given in the table below.
Form topics

Page

Field properties

page 71

Button fields

page 72

Check box fields

page 74

Combo box fields

page 75

List box fields

page 79

Radio button fields

page 81

Signature fields

page 82

Text fields

page 83

Validation scripts

page 84

Calculation script

page 85

Adobe Acrobat SDK

Using JavaScript in Forms

Developing Acrobat Applications Using JavaScript

Setting Acrobat form field properties

71

Field properties
A form field has certain properties that determines its appearance, printability, orientation, and the actions
performed when the user interacts with it. Some properties are common to all form fields, while others are
particular to certain types of fields. The properties of a field can be set not only through the UI, but also
programmatically with JavaScript.
The most basic property of every form field is its name, which provides the reference necessary for
subsequent access and modification. The key to setting the properties of a field is to first acquire the Field
object of that field using its name; this is done using the getField method of the Doc object:
var f = this.getField("myField");

The getField method takes as its argument the field name of the target field. The Field object can be
obtained using other methods as well, for example, the addField method returns the Field object of the
field it just created.
General properties that apply to all form fields include the display rectangle, border style, border line
thickness, stroke color, orientation, background color, and tooltip. In addition, you can choose whether it
should be read only, have the ability to scroll, and be visible on screen or in print.
There are also specific settings you can apply to text characteristics, button and icon size and position
relationships, button appearance when pushed, check box and radio button glyph appearance, and the
number and selection options for combo box and list box items.
All formatting options are listed and described in the following table.

Field properties
Property

Description

Field properties

display rectangle

Position and size of field on page.

rect

border style

Rectangle border appearance.

borderStyle

stroke color

Color of bounding rectangle.

strokeColor

border thickness

Width of the edge of the surrounding rectangle.

lineWidth

orientation

Rotation of field in 90-degree increments.

rotation

background color

Background color of field (gray, transparent,
RGB, or CMYK).

fillColor

tooltip

Short description of field that appears on
mouse-over.

userName

read only

Whether the user may change the field
contents.

readonly

scrolling

Whether text fields may scroll.

doNotScroll

display

Whether visible or hidden on screen or in print.

display

Adobe Acrobat SDK

Using JavaScript in Forms

Developing Acrobat Applications Using JavaScript

Setting Acrobat form field properties

Property

Description

Field properties

text

Font, color, size, rich text, comb format,
multiline, limit to number of characters, file
selection format, or password format.

textFont, textColor,
textSize, richText,
richValue, comb,
multiline, charLimit,
fileSelect, password

text alignment

Text layout in text fields.

alignment

button alignment

Alignment of icon on button face.

buttonAlignX,
buttonAlignY

button icon scaling

Relative scaling of an icon to fit inside a button
face.

buttonFitBounds,
buttonScaleHow,
buttonScaleWhen

highlight mode

Appearance of a button when pushed.

highlight

glyph style

Glyph style for checkbox and radio buttons.

style

number of items

Number of items in a combo box or list box.

numItems

editable

Whether the user can type in a combo box.

editable

multiple selection

Whether multiple list box items may be
selected.

multipleSelection

72

Button fields
We will begin by creating a button named myButton:
var f = this.addField("myButton", "button", 0, [200, 250, 250, 400]);

In most cases, however, a form field, such as this button, is created through the UI.
If the field already exists, get the Field object as follows:
var f = this.getField("myButton");

To create a blue border along the edges of its surrounding rectangle, we will set its strokeColor
property:
f.strokeColor = color.blue;

In addition, you can select from one of the following choices to specify its border style: solid (border.s),
beveled (border.b), dashed (border.d), inset (border.i), or underline (border.u). In this case we
will make the border appear beveled by setting its borderStyle property:
f.borderStyle = border.b;

To set the line thickness (in points) of the border, set its lineWidth property:
f.lineWidth = 1;

To set its background color to yellow, we will set its fillColor property:
f.fillColor = color.yellow;

Adobe Acrobat SDK
Developing Acrobat Applications Using JavaScript

Using JavaScript in Forms
Setting Acrobat form field properties

73

To specify the text that appears on the button, invoke its buttonSetCaption method:
f.buttonSetCaption("Click Here");

You can set the text size, color, and font:
f.textSize = 16;
f.textColor = color.red;
f.textFont = font.Times;

To create a tooltip that appears when the mouse hovers over the button, set its userName property:
f.userName = "This is a button tooltip for myButton.";

In addition to the text, it is also possible to specify the relative positioning of the icon and text on the
button’s face. In this case, we will set the layout so that the icon appears to the left of the text:
f.buttonPosition = position.iconTextH;

To specify whether the button should be visible either on screen or when printing, set its display
property:
f.display = display.visible;

To set the button’s appearance in response to user interaction, set its highlight property to one of the
following values: none (highlight.n), invert (highlight.i), push (highlight.p), or outline
(highlight.o). In this example, we will specify that the button appears to be pushed:
f.highlight = highlight.p;

It is possible to specify the scaling characteristics of the icon within the button face. You can determine
when scaling takes place by setting the button’s buttonScaleWhen property to one of the following
values: always (scaleWhen.always), never (scaleWhen.never), if the icon is too big
(scaleWhen.tooBig), or if the icon is too small (scaleWhen.tooSmall). In this case, we will specify
that the button always scales:
f.buttonScaleWhen = scaleWhen.always;

You can also determine whether the scaling will be proportional by setting the buttonScaleHow
property to one of the following values: buttonScaleHow.proportional or
buttonScaleHow.anamorphic. In this case, we will specify that the button scales proportionally:
f.buttonScaleHow = buttonScaleHow.proportional;

To guarantee that the icon scales within the bounds of the rectangular region for the button, set the
buttonFitBounds property:
f.buttonFitBounds = true;

You can specify the alignment characteristics of the icon by setting its buttonAlignX and
buttonAlignY properties. This is done by specifying the percentage of the unused horizontal space
from the left or the vertical space from the bottom that is distributed. A value of 50 would mean that 50
percent of the unused space would be distributed to the left or bottom of the icon (centered). We will
center our icon in both dimensions:
f.buttonAlignX = 50;
f.buttonAlignY = 50;

Adobe Acrobat SDK

Using JavaScript in Forms

Developing Acrobat Applications Using JavaScript

Setting Acrobat form field properties

74

Now that you have prepared the space within the button for the icon, you can import an icon into the
document and place it within the button’s area. There are two methods for importing an icon for a button
face and associating it with a button
●

Use the buttonImportIcon method of the Field object, this imports and associates in one step:
var retn = f.buttonImportIcon("/C/temp/myIcon.pdf");
if ( retn != 0 ) app.alert("Icon not imported");

If the argument of buttonImportIcon is empty, the user is prompted to choose an icon. This
approach works for Adobe Reader.
●

Import the icon using the importIcon method of the Doc object, then associate the icon with the
button using the buttonSetIcon method of the Field object.
this.importIcon({
cName: "myIconName", cDIPath: "/C/temp/myIcon.pdf", nPage: 0});
var myIcon = this.getIcon("myIconName");
f.buttonSetIcon(myIcon);

If the cDIPath parameter is specified, which is the case in this example, the importIcon method can
only be executed in batch and console events; however, this restrictions can be bypassed using the
techniques discussed in “Executing privileged methods in a non-privileged context” on page 45. When
cDIPath is not specified, the script works for Adobe Reader.
To rotate the button counterclockwise, set its rotation property:
f.rotation = 90;

Finally, you will undoubtedly wish to associate an action to be executed when the button is clicked. You
can do this by invoking the setAction method of the Field object, which requires a trigger (an indication
of the type of mouse event) and an associated script. The possible triggers are MouseUp, MouseDown,
MouseEnter, MouseExit, OnFocus, and OnBlur. The following code displays a greeting when the
button is clicked:
f.setAction("MouseUp", "app.alert('Hello');" );

Check box fields
The check box field supports many of the same properties as the button, and actions are handled in the
same manner. The properties common to both form fields are:
●

userName

●

readonly

●

display

●

rotation

●

strokeColor

●

fillColor

●

lineWidth

●

borderStyle

●

textSize

●

textColor

In the case of textFont, however, the font is always set to Adobe Pi.

Adobe Acrobat SDK
Developing Acrobat Applications Using JavaScript

Using JavaScript in Forms
Setting Acrobat form field properties

75

The style property of the Field object is used to set the appearance of the check symbol that appears
when the user clicks in the check box. Permissible values of the style property are check (style.ch),
cross (style.cr), diamond (style.di), circle (style.ci), star (style.st), and square (style.sq).
For example, the following code causes a check to appear when the user clicks in the check box:
f.style = style.ch;

The export value of the check box can be set using the exportValues property of the Field object. For
example, the code below associates the export value "buy" with the check box:
var f = this.getField("myCheckBox");
f.exportValues=["buy"];

If there are several check box fields, you can indicate that one particular form field is always checked by
default. To do this, you must do two things:
●

Invoke the defaultIsChecked method of the Field object. Note that since there may be several
check boxes that belong to the same group, the method requires that you specify the zero-based index
of the particular check box.

●

Reset the field to ensure that the default is applied by invoking the resetForm method of the Doc
object.

This process is shown in the following code:
var f = this.getField("myCheckBox");
f.defaultIsChecked(0); // 0 means that check box #0 is checked
this.resetForm([f.name]);

Other useful Field methods are
●

checkThisBox — used to check a box

●

isBoxChecked — used test whether a check box is checked

●

isDefaultChecked — use to test whether the default setting is the one selected by user

Combo box fields
The combo box has the same properties as the button and check box fields. Its primary differences lie in its
nature. Since the combo box maintains an item list in which the user may be allowed to enter custom text,
it offers several properties that support its formatting options.
If you would like the user to be permitted to enter custom text, set the editable property of the Field
object, as shown in the following code:
var f = this.getField("myComboBox");
f.editable = true;

You can specify whether the user’s custom text will be checked for spelling by setting its
doNotSpellCheck property. The following code indicates that the spelling is not checked:
f.doNotSpellCheck = true;

A combo box can interact with the user in one of two ways: either a selection automatically results in a
response, or the user first makes their selection and then takes a subsequent action, such as clicking a
Submit button.

Adobe Acrobat SDK
Developing Acrobat Applications Using JavaScript

Using JavaScript in Forms
Setting Acrobat form field properties

76

In the first case, as soon as the user clicks on an item in the combo box, an action can automatically be
triggered. If you would like to design your combo box this way, then set its commitOnSelChange
property to true. Otherwise, set the value to false. The following code commits the selected value
immediately:
f.commitOnSelChange = true;

To set the export values for the combo box items, invoke its setItems method, which can be used to set
both the face and export values. In this case, the face (or appearance) value (the value that appears in the
combo box) is the first value in every pair, and the export value is the second. The following code results in
the full state names appearing in the combo box (as the face or appearance values), and abbreviated state
names as their corresponding export values:
f.setItems( ["Ohio", "OH"], ["Oregon", "OR"], ["Arizona", "AZ"] );

In many cases, it is desirable to maintain a sorted collection of values in a combo box. In order to do this,
you will need to write your own sorting script. Recall that the JavaScript Array object has a sort method
that takes an optional argument which may be a comparison function.
This means that you must first define a compare function that accepts two parameters. The function must
return a negative value when the first parameter is less than the second, 0 if the two parameters are
equivalent, and a positive value if the first parameter is greater.
In the following example, we define a compare function that accepts two parameters, both of which are
user/export value pairs, and compares their user values. For example, if the first parameter is ["Ohio",
"OH"] and the second parameter is ["Arizona", "AZ"], the compare function returns 1, since
"Ohio" is greater than "Arizona":
function compare (a,b)
{
if (a[0] < b[0]) return -1; // index 0 means user value
if (a[0] > b[0]) return 1;
return 0;
}

Create a temporary array of values and populate it with the user/export value pairs in your combo box
field. The following code creates the array, iterates through the combo box items, and copies them into the
array:
var arr = new Array();
var f = this.getField("myCombobox");
for (var i = 0; i < f.numItems; i++)
arr[i] = [f.getItemAt(i,false), f.getItemAt(i)];

At this point you can invoke the sort method of the Array object and replace the items in the combo
box field:
arr.sort(compare); // Sort the array using your compare method
f.setItems(arr);

Responding to combo box changes
The Format tab of the Combo Box properties lists categories of formats available to combo box text. They
are None, Number, Percentage, Date, Time, Special and Custom. For all formatting categories, except None
and Custom, the JavaScript interpreter uses special formatting functions to properly process the text of a
combo box; these functions are undocumented now, so comments here are focused on the None and
Custom category.

Adobe Acrobat SDK
Developing Acrobat Applications Using JavaScript

Using JavaScript in Forms
Setting Acrobat form field properties

77

If the formatting category is set to None, then processing the combo box is easy. Whereas the combo box
does not process its own change in value, another form element can easily read the current setting of the
combo box. For example, if the name of the combo box is myComboBox, then the following code gets the
current value:
var f = this.getField("myComboBox");
var valueCombo = f.value;

The variable valueCombo contains the export value of the combo box. You cannot, by the way, get the
face value, if the export value is different from the face value.
When the formatting category is set to Custom, there are two types of formatting scripts, Custom
Keystroke Script and Custom Format Script.
The Custom Keystroke Script has the following general form:
if (event.willCommit) {
// Script that is executed when the choice is committed
} else {
// Script that is executed when the choice changes, or, if the
// combox box is editable, when text is typed in.
}

With regard to the Custom Keystroke Script, there are three event properties that can be read: value,
change and changeEx. To illustrate these event properties, let’s use the state combo box, defined above.
Here is the Custom Keystroke Script:
if (event.willCommit) {
console.println("Keystroke: willCommit")
console.println("event.value = " + event.value);
console.println("event.change = " + event.change);
console.println("event.changeEx = " + event.changeEx);
} else {
console.println("Keystroke: not Committed")
console.println("event.value = " + event.value);
console.println("event.change = " + event.change);
console.println("event.changeEx = " + event.changeEx);
}

The results of this script are listed below. Assume the combo box is set on a face value of "Arizona" and
you change the combo box to read "Ohio". Additional comments are inserted.
// Select Ohio, but not committed. Note that the value of event.value is still
// set to "Arizona", but event.change is now set to the face value of the new
// choice, and event.changeEx is set to the export value of the new selection.
Keystroke: not Committed
event.value = Arizona
event.change = Ohio
event.changeEx = OH
// The choice is committed. Note that the value of event.value is now "Ohio"
// and that event.change and event.changeEx are empty.
Keystroke: willCommit
event.value = Ohio
event.change =
event.changeEx =

Adobe Acrobat SDK

Using JavaScript in Forms

Developing Acrobat Applications Using JavaScript

Setting Acrobat form field properties

78

The only difference between the above sequence of events when f.commitOnSelChange=false
versus f.commitOnSelChange=true is that in the first case, after the user makes a (new) choice from
the combo box (and the “not committed” script is executed), the user must press the Enter key or click on a
white area outside the field to commit the change, at this point, the "willCommit" script will execute. When
f.commitOnSelChange=true, these two blocks of code will execute one after the other, with the “not
committed” code executing first.
A combo box can also be editable. An editable combo box is one where the user is allowed to type in, or
paste in, a selection. A combo box can be made editable by checking Allow User to Enter Custom Text in
the Options tab of the Combo Box Properties dialog box. For JavaScript, the editable field property is
used, as in the following example.
var f = this.getField("myComboBox");
f.editable = true;

The above output was captured in the console from a combo box that was not editable. The output is the
same when the user selects one of the items in the combo box; when the user types in a selection, the
output looks like this, assuming the user has already typed in the string "Te"and is now typing in "x":
/*
Note that when the selection is not committed, event.changeEx is empty. You
can test whether the user is typing in by using the conditional test
if ( event.changeEx == "" ) {} else {