0% found this document useful (0 votes)
219 views

Acrobat JavaScript Scripting Guide - Adobe Developer Support

All information contained herein is the property of Adobe Systems Incorporated. No part of this publication may be reproduced or transmitted without the prior written consent of the author. All instances of the name PostScript in the text are references to the PostScript language.

Uploaded by

Jose Luis Zimic
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
219 views

Acrobat JavaScript Scripting Guide - Adobe Developer Support

All information contained herein is the property of Adobe Systems Incorporated. No part of this publication may be reproduced or transmitted without the prior written consent of the author. All instances of the name PostScript in the text are references to the PostScript language.

Uploaded by

Jose Luis Zimic
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 280

Adobe Acrobat 7.

0
Acrobat JavaScript Scripting
Guide
July 19, 2005
Adobe Solutions Network http://partners.adobe.com
Copyright 2004 Adobe Systems Incorporated. All rights reserved.
NOTICE: All information contained herein is the property of Adobe Systems Incorporated. No part of this publication (whether in hardcopy or
electronic form) may be reproduced or transmitted, in any form or by any means, electronic, mechanical, photocopying, recording, or
otherwise, without the prior written consent of the Adobe Systems Incorporated.
PostScript is a registered trademark of Adobe Systems Incorporated. All instances of the name PostScript in the text are references to the
PostScript language as defined by Adobe Systems Incorporated unless otherwise stated. The name PostScript also is used as a product
trademark for Adobe Systems implementation of the PostScript language interpreter.
Except as otherwise stated, any reference to a PostScript printing device, PostScript display device, or similar item refers to a printing device,
display device or item (respectively) that contains PostScript technology created or licensed by Adobe Systems Incorporated and not to devices
or items that purport to be merely compatible with the PostScript language.
Adobe, the Adobe logo, Acrobat, the Acrobat logo, Acrobat Capture, Distiller, PostScript, the PostScript logo and Reader are either registered
trademarks or trademarks of Adobe Systems Incorporated in the United States and/or other countries.
Apple, Macintosh, and Power Macintosh are trademarks of Apple Computer, Inc., registered in the United States and other countries. PowerPC
is a registered trademark of IBM Corporation in the United States. ActiveX, Microsoft, Windows, and Windows NT are either registered
trademarks or trademarks of Microsoft Corporation in the United States and/or other countries. Verity is a registered trademark of Verity,
Incorporated. UNIX is a registered trademark of The Open Group. Verity is a trademark of Verity, Inc. Lextek is a trademark of Lextek
International. All other trademarks are the property of their respective owners.
This publication and the information herein is furnished AS IS, 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,
makes no warranty of any kind (express, implied, or statutory) with respect to this publication, and expressly disclaims any and all warranties
of merchantability, fitness for particular purposes, and noninfringement of third party rights.
Acrobat JavaScript Scripting Guide 3
Contents
Contents
Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
What is Acrobat JavaScript?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Audience. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Purpose and Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Assumptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
How To Use This Guide . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Font Conventions Used in This Book . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Related Documents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Chapter 1 Acrobat JavaScript Overview . . . . . . . . . . . . . . . . 19
Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Chapter Goals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Acrobat JavaScript Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Acrobat JavaScript Object Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
app. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
doc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
dbg. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
console. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
global . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
Util . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
dialog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
SOAP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
ADBC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
event . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
What Can You Do with Acrobat JavaScript? . . . . . . . . . . . . . . . . . . . . . . . . . 26
Chapter 2 Acrobat JavaScript Tools . . . . . . . . . . . . . . . . . . 29
Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
Chapter Goals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
Contents
4 Acrobat JavaScript Scripting Guide
Using the Acrobat JavaScript Console. . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
Opening the JavaScript Console. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
Executing JavaScript. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
Formatting Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Exercise: Working with the JavaScript Console . . . . . . . . . . . . . . . . . . . . . . . 32
Enabling JavaScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
Trying out the JavaScript Console . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
Using a JavaScript Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
Specifying the Default JavaScript Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Using the Built-in Acrobat JavaScript Editor . . . . . . . . . . . . . . . . . . . . . . . . . 42
Using an External Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Additional Editor Capabilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Specifying Additional Capabilities to Your Editor . . . . . . . . . . . . . . . . . . . . 43
Testing Whether Your Editor Will Open at Syntax Error Locations . . . . . . . . . . . 44
Using the Acrobat JavaScript Debugger . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Acrobat JavaScript Debugger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
Main Groups of Controls. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
Debugger View Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
Debugger Buttons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
Resume Execution. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
Interrupt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
Quit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
Step Over . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
Step Into . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
Step Out . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
Debugger Scripts Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
Accessing Scripts in the Scripts Window . . . . . . . . . . . . . . . . . . . . . . . . 52
Scripts Inside PDF Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
Scripts Outside PDF Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
Call Stack List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
Inspect Details Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
Inspect Details Window Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
Inspecting Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
Watches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
Breakpoints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
Starting the Debugger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
Debugging From the Start of Execution . . . . . . . . . . . . . . . . . . . . . . . . . 59
Debugging From an Arbitrary Point in the Script. . . . . . . . . . . . . . . . . . . . . 60
Exercise: Calculator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
Acrobat JavaScript Scripting Guide 5
Contents
Calculator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
Summary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
Chapter 3 Acrobat JavaScript Contexts . . . . . . . . . . . . . . . . 63
Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
Chapter Goals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
Introduction to Acrobat JavaScript Contexts . . . . . . . . . . . . . . . . . . . . . . . . . 64
Folder Level JavaScripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
Document Level JavaScripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
Field Level JavaScripts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
Batch Level JavaScripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
Summary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
Chapter 4 Creating and Modifying PDF Documents . . . . . . . . . . 67
Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
Chapter Goals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
Creating and Modifying PDF Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
Combining PDF Documents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
Creating PDF Files from Multiple Files . . . . . . . . . . . . . . . . . . . . . . . . . 69
Cropping and Rotating Pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
Extracting, Moving, Deleting, Replacing, and Copying Pages . . . . . . . . . . . . . . 72
Adding Watermarks and Backgrounds . . . . . . . . . . . . . . . . . . . . . . . . . 74
Adding Headers and Footers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
Converting PDF Documents to XML Format . . . . . . . . . . . . . . . . . . . . . . . . . 75
Chapter 5 Print Production . . . . . . . . . . . . . . . . . . . . . . . 77
Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
Chapter Goals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
Print Production . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
Printing PDF Documents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
Silent Printing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
Printing Documents with Layers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
Setting Advanced Print Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
Contents
6 Acrobat JavaScript Scripting Guide
Chapter 6 Using Acrobat JavaScript in Forms . . . . . . . . . . . . . 85
Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
Chapter Goals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
Forms Essentials. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
About PDF Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
Creating Acrobat Form Fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
Setting Acrobat Form Field Properties. . . . . . . . . . . . . . . . . . . . . . . . . . 91
Making a Form Fillable. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .102
Setting the Hierarchy of Form Fields. . . . . . . . . . . . . . . . . . . . . . . . . . .103
Creating Forms From Scratch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .103
Making PDF Forms Web-Ready . . . . . . . . . . . . . . . . . . . . . . . . . . . . .107
Using Custom JavaScripts in Forms. . . . . . . . . . . . . . . . . . . . . . . . . . .108
Introduction to XML Forms Architecture (XFA) . . . . . . . . . . . . . . . . . . . . .108
Forms Migration: Working with Forms Created in Acrobat 6.0 or Earlier . . . . . . . .114
Filling in PDF Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .114
Completing Form Fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .114
Importing and Exporting Form Data . . . . . . . . . . . . . . . . . . . . . . . . . . .115
Saving Form Data as XML or XML Data Package (XDP) . . . . . . . . . . . . . . . .115
Emailing Completed Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .115
Global Submit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .115
Making Forms Accessible . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .117
Text-To-Speech . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .117
Tagging Annotations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .119
Using JavaScript to Secure Forms. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .119
Chapter 7 Review, Markup, and Approval . . . . . . . . . . . . . . 123
Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .123
Chapter Goals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .123
Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .123
Online Collaboration Essentials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .124
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .124
Reviewing Documents with Additional Usage Rights . . . . . . . . . . . . . . . . . .124
Emailing PDF Documents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .125
Acrobat JavaScript-based Collaboration Driver . . . . . . . . . . . . . . . . . . . . .126
Using Commenting Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .128
Adding Note Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .129
Making Text Edits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .129
Acrobat JavaScript Scripting Guide 7
Contents
Highlighting, Crossing Out, and Underlining Text . . . . . . . . . . . . . . . . . . . .129
Adding and Deleting Custom Stamps . . . . . . . . . . . . . . . . . . . . . . . . . .129
Adding Comments in a Text Box. . . . . . . . . . . . . . . . . . . . . . . . . . . . .129
Adding Attachments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .130
Spell-checking in Comments and Forms . . . . . . . . . . . . . . . . . . . . . . . .132
Adding Commenting Preferences . . . . . . . . . . . . . . . . . . . . . . . . . . . .133
Changing Colors, Icons, and Other Comment Properties . . . . . . . . . . . . . . . .133
Adding Watermarks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .134
Approval . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .135
Managing Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .136
Selecting, Moving, and Deleting Comments. . . . . . . . . . . . . . . . . . . . . . .136
Using the Comments List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .137
Exporting and Importing Comments . . . . . . . . . . . . . . . . . . . . . . . . . . .139
Comparing Comments in Two PDF Documents . . . . . . . . . . . . . . . . . . . . .139
Aggregating Comments for Use in Excel . . . . . . . . . . . . . . . . . . . . . . . .139
Extracting Comments in a Batch Process . . . . . . . . . . . . . . . . . . . . . . . .139
Approving Documents Using Stamps (Japanese Workflows) . . . . . . . . . . . . . . . .140
Setting up a Hanko Approval Workflow . . . . . . . . . . . . . . . . . . . . . . . . .140
Participating in a Hanko Approval Workflow . . . . . . . . . . . . . . . . . . . . . . .141
Chapter 8 Working with Digital Media in PDF Documents . . . . . . 143
Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .143
Chapter Goals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .143
Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .143
Media Players: Control, Settings, Renditions, and Events . . . . . . . . . . . . . . . . . .144
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .144
Accessing a List of Active Players . . . . . . . . . . . . . . . . . . . . . . . . . . . .145
Specifying Playback Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .146
Monitors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .149
Integrating Media into Documents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .151
Adding Movie Clips . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .151
Adding Sound Clips . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .152
Adding and Editing Renditions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .152
Setting Multimedia Preferences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .153
Chapter 9 Acrobat Templates . . . . . . . . . . . . . . . . . . . . 155
Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .155
Chapter Goals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .155
Contents
8 Acrobat JavaScript Scripting Guide
Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .155
The Role of Templates in PDF Form Architecture . . . . . . . . . . . . . . . . . . . . . .156
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .156
Spawning Templates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .157
Dynamic Form Field Generation. . . . . . . . . . . . . . . . . . . . . . . . . . . . .157
Dynamic Page Generation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .157
Template Syntax and Usage. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .158
Chapter 10 Modifying the User Interface . . . . . . . . . . . . . . . 159
Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .159
Chapter Goals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .159
Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .159
Using Adobe Dialog Manager (ADM) in Acrobat JavaScript . . . . . . . . . . . . . . . . .160
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .160
ADM Object Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .161
Access to ADM through JavaScript . . . . . . . . . . . . . . . . . . . . . . . . . . .162
Adding Navigation to PDF Documents. . . . . . . . . . . . . . . . . . . . . . . . . . . .170
Thumbnails . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .171
Bookmarks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .171
Links . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .175
Using Actions for Special Effects . . . . . . . . . . . . . . . . . . . . . . . . . . . .178
Highlighting Form Fields and Navigational Components . . . . . . . . . . . . . . . .181
Setting Up a Presentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .182
Numbering Pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .185
Creating Buttons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .186
Working with PDF Layers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .187
About PDF Layers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .187
Navigating with Layers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .187
Editing the Properties of PDF Layers . . . . . . . . . . . . . . . . . . . . . . . . . .188
Merging Layers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .189
Flattening PDF Layers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .189
Combining PDF Layered Documents . . . . . . . . . . . . . . . . . . . . . . . . . .189
Chapter 11 Search and Index Essentials . . . . . . . . . . . . . . . 191
Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .191
Chapter Goals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .191
Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .191
Searching for Text in PDF Documents . . . . . . . . . . . . . . . . . . . . . . . . . . . .192
Acrobat JavaScript Scripting Guide 9
Contents
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .192
Finding Words in an PDF Document . . . . . . . . . . . . . . . . . . . . . . . . . .193
Searching Across Multiple PDF Documents. . . . . . . . . . . . . . . . . . . . . . .195
Indexing Multiple PDF Documents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .197
Creating, Updating, or Rebuilding Indexes . . . . . . . . . . . . . . . . . . . . . . .197
Searching Metadata . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .199
Using Acrobat JavaScript to Read and Search XMP Metadata . . . . . . . . . . . . .199
Chapter 12 Security . . . . . . . . . . . . . . . . . . . . . . . . . . 201
Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .201
Chapter Goals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .201
Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .201
Security Essentials. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .202
Methods for Adding Security to PDF Documents . . . . . . . . . . . . . . . . . . . .202
Digitally Signing PDF Documents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .205
Signing a PDF Document . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .205
Getting Signature Information from Another User . . . . . . . . . . . . . . . . . . . .208
Removing Signatures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .208
Certifying a Document . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .208
Validating Signatures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .209
Using Approval Stamps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .209
Setting Digital Signature Preferences . . . . . . . . . . . . . . . . . . . . . . . . . .210
Adding Security to PDF Documents . . . . . . . . . . . . . . . . . . . . . . . . . . . . .210
Adding Passwords and Setting Security Options . . . . . . . . . . . . . . . . . . . .210
Adding Usage Rights to a Document . . . . . . . . . . . . . . . . . . . . . . . . . .211
Encrypting PDF Files for a List of Recipients . . . . . . . . . . . . . . . . . . . . . .211
Encrypting PDF Files Using Security Policies . . . . . . . . . . . . . . . . . . . . . .213
Adding Security to Document Attachments . . . . . . . . . . . . . . . . . . . . . . .217
Digital IDs and Certification Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . .218
Digital IDs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .218
Managing Digital ID Certificates . . . . . . . . . . . . . . . . . . . . . . . . . . . . .224
Tokenized Acrobat JavaScript Security Model . . . . . . . . . . . . . . . . . . . . . .226
Chapter 13 Rights-Enabled PDF Files . . . . . . . . . . . . . . . . . 227
Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .227
Chapter Goals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .227
Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .227
Additional Usage Rights . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .228
Contents
10 Acrobat JavaScript Scripting Guide
LiveCycle Reader Extensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .228
Writing Acrobat JavaScript for Reader . . . . . . . . . . . . . . . . . . . . . . . . . . . .229
Enabling Collaboration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .233
Chapter 14 Interacting with Databases . . . . . . . . . . . . . . . . 237
Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .237
Chapter Goals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .237
Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .237
Introduction to ADBC. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .238
Establishing an ADBC Connection. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .238
Executing SQL Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .241
Chapter 15 SOAP and Web Services . . . . . . . . . . . . . . . . . . 243
Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .243
Chapter Goals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .243
Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .244
Using SOAP and Web Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .244
Using a WSDL Proxy to Invoke a Web Service . . . . . . . . . . . . . . . . . . . . .245
Synchronous and Asynchronous Information Exchange . . . . . . . . . . . . . . . .247
Using Document/Literal Encoding . . . . . . . . . . . . . . . . . . . . . . . . . . . .251
Exchanging File Attachments and Binary Data . . . . . . . . . . . . . . . . . . . . .252
Converting Between String and ReadStream Information. . . . . . . . . . . . . . . .253
Accessing SOAP Version Information . . . . . . . . . . . . . . . . . . . . . . . . . .254
Accessing SOAP Header Information . . . . . . . . . . . . . . . . . . . . . . . . . .254
Authentication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .255
Error Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .255
DNS Service Discovery . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .256
Managing XML-based Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .258
Workflow Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .260
Appendix A A Short Acrobat JavaScript FAQ . . . . . . . . . . . . . 261
Where can JavaScripts be found and how are they used? . . . . . . . . . . . . . . . . .261
How should I name my Acrobat form fields?. . . . . . . . . . . . . . . . . . . . . . . . .261
How do I use date objects? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .263
Converting from a Date to a String . . . . . . . . . . . . . . . . . . . . . . . . . . .263
Converting from a string to a date . . . . . . . . . . . . . . . . . . . . . . . . . . . .264
Date arithmetic. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .265
Acrobat JavaScript Scripting Guide 11
Contents
How can I make restricted Acrobat JavaScript methods available to users? . . . . . . . .266
How can I make my documents accessible?. . . . . . . . . . . . . . . . . . . . . . . . .267
Document Metadata . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .267
Short Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .267
Setting Tab Order . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .267
Reading Order . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .268
How can I define global variables in JavaScript? . . . . . . . . . . . . . . . . . . . . . .268
Making Global Variables Persistent . . . . . . . . . . . . . . . . . . . . . . . . . . .268
How can I hide an Acrobat form field based on the value of another?. . . . . . . . . . . .269
How can I query an Acrobat form field value in another open form? . . . . . . . . . . . .269
How can I intercept keystrokes one by one as they occur in Acrobat forms? . . . . . . . .269
How can I construct my own colors?. . . . . . . . . . . . . . . . . . . . . . . . . . . . .270
How can I prompt the user for a response in a dialog? . . . . . . . . . . . . . . . . . . .270
How can I fetch an URL from JavaScript? . . . . . . . . . . . . . . . . . . . . . . . . . .270
How can I determine if the mouse has entered/left a certain area on an Acrobat form? . .270
How can I disallow changes in scripts contained in my document? . . . . . . . . . . . . .271
How can I hide scripts contained in my document? . . . . . . . . . . . . . . . . . . . . .271
Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273
Contents
12 Acrobat JavaScript Scripting Guide
Acrobat JavaScript Scripting Guide 13
Preface
Preface
Introduction
Welcome to the Adobe

Acrobat

JavaScript Scripting Guide. This scripting guide is


designed to provide you with an overview of how you can use Acrobat JavaScript to
develop and enhance standard 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
Here you will find detailed information and examples of what the Acrobat JavaScript
capabilities are and how to access them, as well as descriptions of the usage of the SDK
tools. Acrobat JavaScript is a powerful means by which you can enhance and extend both
Acrobat and PDF document functionality.
What is Acrobat JavaScript?
Acrobat JavaScript is a language based on the core of 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 JavaScript implements extensions,
in the form of 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, Stri ng, Date, Array, and RegExp.
Preface
Introduction
14 Acrobat JavaScript Scripting Guide
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 Acrobat JavaScript and JavaScript used in a Web browser, also known as HTML
JavaScript:
Acrobat JavaScript does not have access to objects within an HTML page. Similarly,
HTML JavaScript cannot access objects within a PDF file.
HTML JavaScript is able to manipulate such objects as Wi ndow. Acrobat JavaScript
cannot access this particular object but it can manipulate PDF-specific objects.
If you have used previous versions of Acrobat JavaScript, please note that there are a
number of new JavaScript features and enhancements in version 7:
JavaScript Byte Code
Adobe PDF document creation
Additional usage rights
Engineering features
File attachments
Additional language support
Forms authoring and management
Review, markup, and approval
Document security and digital signatures
Accessibility
Print production
XML capabilities
Audience
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 Acrobats
web-based features, you will find it useful to understand XML, XSLT, SOAP, and Web
services. Finally, if you would like to utilize Acrobats database capabilities, you will need a
basic understanding of SQL.
Acrobat JavaScript Scripting Guide 15
Preface
How To Use This Guide
Purpose and Scope
The purpose of this guide is to:
Describe how you can use the Acrobat JavaScript language as the primary vehicle with
which to develop and deploy Acrobat workflow solutions.
Provide you with easily understood, detailed information and examples of the Acrobat
JavaScript scripting features.
Provide you with references to other resources where you can learn more about Acrobat
JavaScript and related technologies.
After reading this guide and completing the exercises, you should be equipped to start
using Acrobat JavaScript. During the development process, you will find that the
descriptions and examples in this guide will provide you with enough direction and
background to enable you to successfully complete your projects.
Assumptions
This guide assumes that you are familiar with the non-scripting elements of the Acrobat 7
user interface that are described in Acrobats accompanying online help documentation. To
work through the exercises in this guide, you will need to use Acrobat 7 Professional.
How To Use This Guide
This guide includes exercises that give you an opportunity to work directly with Acrobat
JavaScript. If you plan to practice any of the exercises, do the following:
1. Be sure that you have Acrobat Professional installed on your Windows

or Macintosh


workstation. The exercises are designed to work on Windows and Macintosh versions of
Acrobat, unless otherwise noted.
2. Create and use the same directory on your machine for all the JavaScript exercises you
would like to try. You will use this directory to store the PDF documents and other files
used in the exercises.
3. The Acrobat SDK contains a set of. zi p files you will need to work through the
exercises. You should extract the contents of these files to your local directory.
Preface
Font Conventions Used in This Book
16 Acrobat JavaScript Scripting Guide
Font Conventions Used in This Book
The Acrobat documentation uses text styles according to the following conventions.
Font Used for Examples
monospaced Paths and filenames C: \ t empl at es\ myt mpl . f m
Code examples set off
from plain text
These are variable declarations:
AVMenu commandMenu, hel pMenu;
monospaced bold Code items within plain
text
The GetExtensi onI Dmethod ...
Parameter names and
literal values in
reference documents
The enumeration terminates if proc
returns fal se.
monospaced italic Pseudocode ACCB1 voi d ACCB2 ExePr oc( voi d)
{ do somet hi ng }
Placeholders in code
examples
AFSi mpl e_Cal cul at e( cFunct i on,
cFi el ds)
blue Live links to Web pages The Adobe Solutions Network URL is:
http://partners.adobe.com/asn/
Live links to sections
within this document
See Using the SDK.
Live links to code items
within this document
Test whether an ASAtomexists.
bold PostScript language and
PDF operators,
keywords, dictionary
key names
The setpagedevice operator
User interface names The File menu
italic Document titles that are
not live links
Acrobat Core API Overview
New terms User space specifies coordinates for...
PostScript variables filename deletefile
Acrobat JavaScript Scripting Guide 17
Preface
Related Documents
Related Documents
This guide refers to the following sources for additional information about Acrobat
JavaScript and related technologies:
Acrobat JavaScript Scripting Reference
This document is the companion reference to this scripting guide. It provides detailed
descriptions of all the Acrobat JavaScript objects.
Adobe Acrobat Help
This online document is included with Acrobat.
Acrobat Solutions Network
http://partners.adobe.com/asn/
PDF Reference
Guide to SDK Samples
Developing for Adobe Reader
If, for some reason, you did not install the entire Acrobat SDK and you do not have all the
documents, please visit the Adobe Solutions Network Web site to find the documents you
need.
Preface
Related Documents
18 Acrobat JavaScript Scripting Guide
Acrobat JavaScript Scripting Guide 19
1
Acrobat JavaScript Overview
Introduction
This chapter introduces the Acrobat JavaScript objects and containment hierarchies, as well
as the primary Acrobat and PDF capabilities related to Acrobat JavaScript usage.
Chapter Goals
At the end of this chapter, you will be able to:
List the Acrobat JavaScript objects and describe their purposes.
Describe how Acrobat JavaScript can be used to extend the functionality of Acrobat.
Identify the primary workflows that may be achieved with Acrobat JavaScript.
Contents
Topics
Acrobat JavaScript Introduction
Acrobat JavaScript Object Summary
What Can You Do with Acrobat JavaScript?
Acrobat JavaScript Overview
Acrobat JavaScript Introduction
1
20 Acrobat JavaScript Scripting Guide
Acrobat JavaScript Introduction
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.
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 Acrobat JavaScript. You can tie Acrobat 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, but 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 JavaScript
extensions. You will find that using Acrobat JavaScript to perform a task such as adding a
menu to Acrobats user interface is much easier to do than writing a plug-in.
Acrobat JavaScripts can be created for batch processing of 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.
Acrobat JavaScript Scripting Guide 21
Acrobat JavaScript Overview
Acrobat JavaScript Object Summary
1
Acrobat JavaScript Object Summary
Acrobat JavaScript defines several objects that allow your code to interact with Acrobat, 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.
The most significant objects available control Acrobat, the Acrobat JavaScript debugger,
the Acrobat JavaScript console, the PDF document, the Adobe Dialog Manager

, Web
services, databases, security, searches, and JavaScript events.
TABLE 1.1 Primary Acrobat JavaScript Objects
Object Purpose
app Acrobat
doc PDF document
dbg JavaScript debugger
console JavaScript console
global Persistent and cross-document
information
util JavaScript utility methods
dialog Adobe Dialog Manager (ADM)
security Encryption and digital signatures
SOAP Web Services
search Searching and indexing
ADBC Database connections and queries
event JavaScript events
Acrobat JavaScript Overview
Acrobat JavaScript Object Summary
1
22 Acrobat JavaScript Scripting Guide
app
The appobject 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 appobject, 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 appto determine which Adobe product and version the end user is
using (such as Reader 6.0 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 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.
FIGURE 1.1 Doc Object Containment Hierarchy
Figure 1.1 represents the containment hierarchy of objects related to the doc object.
Accessing the doc object from JavaScript can be done in a variety of ways. The most
common method is using the thi s object, which is normally equivalent to the doc object
of the current underlying document.
doc
field sound
bookmark
annot
template data
Acrobat JavaScript Scripting Guide 23
Acrobat JavaScript Overview
Acrobat JavaScript Object Summary
1
dbg
You can use the dbgobject, available only in Acrobat Professional, to optionally control the
JavaScript debugger from a command line standpoint while the application is not
executing a modal dialog box. The dbgobject methods offer the same functionality as the
buttons in the JavaScript debugger dialog toolbar, which permit stepwise execution,
setting, removing, and inspecting breakpoints, and quitting the debugger.
console
The consol eobject is a static object available within Acrobat Professional that is used to
access the JavaScript console for displaying debug messages and executing JavaScript. It
does not function in Adobe Reader or Acrobat Standard. It is useful as a debugging aid and
as a means of interactively testing code.
global
The gl obal 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,
gl obal may 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 gl obal . If
information about the documents needs to be stored in a report object, it is assigned to a
set of properties within gl obal so it is accessible to the report object.
Util
The Uti l 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 di al ogobject is an object literal used by the appobjects execDi al og() method
to present a modal dialog box identical in appearance and behavior to those used across all
Adobe applications. The di al ogobject 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, checkboxes, radio buttons, listboxes,
textboxes, popup controls, and containers and frames for sets of controls.
Acrobat JavaScript Overview
Acrobat JavaScript Object Summary
1
24 Acrobat JavaScript Scripting Guide
security
The securi ty 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 securi ty 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 SOAPobject can be used to make remote procedure calls to a server and invoke Web
Services described by the Web Services Description Language (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 SOAPobject 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 XMLDataobject can be used to evaluate XPath
expressions and perform XSLT conversions on XML documents.
search
The searchobject 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 searchobject has properties that may 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.
ADBC
The ADBCobject is used in conjunction with the connecti on, and statement objects
to interface to a database. These Acrobat JavaScript objects constitute Acrobat Database
Connectivity (ADBC), and provide a simplified means of utilizing ODBC calls to connect to a
database and access its data. SQL statements are passed to the statement objects
execute() method in order to insert, update, retrieve, and delete data.
Acrobat JavaScript Scripting Guide 25
Acrobat JavaScript Overview
Acrobat JavaScript Object Summary
1
event
All JavaScript actions are executed when a particular event occurs. For each event, Acrobat
JavaScript creates an event object. 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 Viewer
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.
Acrobat JavaScript Overview
What Can You Do with Acrobat JavaScript?
1
26 Acrobat JavaScript Scripting Guide
What Can You Do with Acrobat JavaScript?
Acrobat JavaScript enables you to do a wide variety of things within Acrobat and Adobe
Reader, and within PDF documents. Acrobat JavaScript can be used to aid in 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
Setting comment repository preferences
Creating and managing comments
Approving documents using stamps
Integrating digital media into documents
Controlling and managing media players and monitors
Adding movie and sound clips
Adding and managing renditions
Setting multimedia preferences
Modifying the user interface
Using Adobe Dialog Manager (ADM)
Adding navigation to PDF documents
Managing PDF layers
Managing 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
Acrobat JavaScript Scripting Guide 27
Acrobat JavaScript Overview
What Can You Do with Acrobat JavaScript?
1
Securing documents
Creating and managing digital signatures
Adding and managing passwords
Adding usage rights
Encrypting files
Managing digital certificates
Managing usage rights
Writing JavaScript for Adobe Reader
Enabling collaboration
Security rights
Layer-specific rights
Interacting with databases
Establishing an ADBC connection
Executing 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
Handling file attachments
Exchanging compressed binary data
Document literal encoding
Serializing objects
XML streams
Applying DNS service discovery to find collaborative repositories on an Intranet
XML
Performing XSLT conversions on XML documents
Evaluating XPath expressions
Acrobat JavaScript Overview
What Can You Do with Acrobat JavaScript?
1
28 Acrobat JavaScript Scripting Guide
Acrobat JavaScript Scripting Guide 29
2
Acrobat JavaScript Tools
Introduction
Acrobat provides an integrated development environment that offers several tools with
which to develop and test Acrobat JavaScript functionality. These tools are the JavaScript
Editor, Console, and Debugger. In addition, Acrobat supports the use of third-party editors
for code development.
In this chapter, you will have the opportunity to practice using the editor, console, and
debugger to evaluate scripts.
Chapter Goals
At the end of this chapter, you will be able to:
Invoke the JavaScript console and use it to interactively execute code and display print
statements.
Use the editor to create and modify Acrobat JavaScript code.
Specify the default editor to be used in your development efforts.
Identify the extra capabilities that Acrobat supports on some external editors.
Identify and understand how to use the following debugger controls and features:
Start the debugger at any point within a script.
Interactively execute code and display output to the console window.
Set and manage customized watches and breakpoints.
Inspect the details of variables.
Start a new debugging session without exiting the debugger.
Acrobat JavaScript Tools
Introduction
2
30 Acrobat JavaScript Scripting Guide
Contents
Topics
Using the Acrobat JavaScript Console
Using a JavaScript Editor
Specifying the Default JavaScript Editor
Using the Built-in Acrobat JavaScript
Editor
Using an External Editor
Using the Acrobat JavaScript Debugger
Summary
Acrobat JavaScript Scripting Guide 31
Acrobat JavaScript Tools
Using the Acrobat JavaScript Console
2
Using the Acrobat JavaScript Console
The Acrobat 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 Acrobat JavaScript Console: either through an Acrobat
menu command or through the use of the static consol eobject within Acrobat
JavaScript code. In either case, it appears as a component of the Acrobat JavaScript
Debugger, and the primary means of displaying values and results is through the
consol e. pri ntl n() method.
Opening the JavaScript Console
To open the Acrobat JavaScript console from within Acrobat:
1. Open the debugger window using one of these methods:
Select Advanced > JavaScript > Debugger, or
Type Ctrl-j (Windows) or Command-j (Macintosh)
2. Select either Console or Script and Console from the debuggers View list.
To open and close the console from Acrobat JavaScript code, use consol e. show() and
consol e. hi de(), respectively.
Executing JavaScript
The Acrobat 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 type Ctrl+Enter on the regular keyboard.
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 type Ctrl+Enter on the regular
keyboard.
To evaluate multiple lines of code, highlight those lines and press either the Enter key
on the numeric keypad or type Ctrl+Enter on the regular keyboard.
In all cases, the result of the most recent single JavaScript statement executed is displayed
in the console.
Avanzadas/Proceso de Documentos/
Depurador de JavaScript
Acrobat JavaScript Tools
Exercise: Working with the JavaScript Console
2
32 Acrobat JavaScript Scripting Guide
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.
Exercise: Working with the JavaScript Console
NOTE: To complete this exercise, you will need Acrobat Professional installed on your
machine.
In this exercise you will verify that JavaScript is enabled for Acrobat and begin working with
the Acrobat JavaScript Console to edit and evaluate code.
At the end of the exercise you will be able to:
Enable or disable Acrobat JavaScript.
Enable or disable the JavaScript debugger.
Open the Acrobat Console.
Evaluate code in the console window.
Acrobat JavaScript Scripting Guide 33
Acrobat JavaScript Tools
Exercise: Working with the JavaScript Console
2
Enabling JavaScript
In order to use Acrobat JavaScript, you must first verify that JavaScript has been enabled. In
order to execute code from the Acrobat 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.
Enable JavaScript, the Debugger, and the Console by performing the following steps (see
Figure 2.1 below):
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.
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.
Acrobat JavaScript Tools
Exercise: Working with the JavaScript Console
2
34 Acrobat JavaScript Scripting Guide
FIGURE 2.1 Enabling JavaScript, Console, and Debugger
Acrobat JavaScript Scripting Guide 35
Acrobat JavaScript Tools
Exercise: Working with the JavaScript Console
2
Trying out the JavaScript Console
1. Select Advanced > JavaScript > Debugger (Ctrl+j) to open the JavaScript debugger.
2. In the debugger, select Console from the View window.
The console window should appear, as shown in Figure 2.2.
FIGURE 2.2 Console window in the JavaScript Debugger
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. Type the following code into the console:
var j sNum= 10;
5. With the mouse cursor positioned somewhere in this line of code, press Enter on the
numeric keypad or Ctrl+Enter on the regular keyboard to evaluate the code. You should
see the results shown in Figure 2.3 below.
Avanzadas/ Proceso de documentos/
Depurador de JavaScript
Acrobat JavaScript Tools
Exercise: Working with the JavaScript Console
2
36 Acrobat JavaScript Scripting Guide
FIGURE 2.3 Evaluating the variable declaration
After each Acrobat JavaScript statement executes, the console window prints out
undefi ned, 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 undefi neddoes not mean that the value of j sNumis
undefined; it just means that the entire JavaScript statements value is undefi ned.
6. A more convenient way to evaluate the j sNumvariable is to highlight the variable name
and execute it as a JavaScript expression, as shown below in Figure 2.4.
FIGURE 2.4 Evaluating jsNum
Acrobat JavaScript Scripting Guide 37
Acrobat JavaScript Tools
Exercise: Working with the JavaScript Console
2
7. Click the Close button to exit the console and debugger, as shown in Figure 2.5 below:
FIGURE 2.5 Console and Debugger Close Button
Acrobat JavaScript Tools
Using a JavaScript Editor
2
38 Acrobat JavaScript Scripting Guide
Using a JavaScript Editor
There are several ways to invoke the Arobat JavaScript Editor. To begin with, it is possible to
select JavaScripts from the Advanced 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 JavaScript as an action associated with a
part of the document, such as a page, bookmark, or form field. It would then make sense to
select the object of interest and edit its particular JavaScript.
For example, the following are the steps to write a JavaScript for a bookmark:
1. Right-click a bookmark. This triggers a context menu.
2. Select Properties and choose the Actions tab, as shown below in Figure 2.6.
Acrobat JavaScript Scripting Guide 39
Acrobat JavaScript Tools
Using a JavaScript Editor
2
FIGURE 2.6 Bookmark Properties
3. The Select Action drop-down list contains all the possible actions that can be
associated with the object, such as Run a JavaScript, Go to view, or Execute a menu
item.
4. Select Run a JavaScript from the Select Action drop-down list.
5. Click Add to open the JavaScript editor.
6. In the editor window, write the JavaScript code to be run when the user opens the page.
Acrobat JavaScript Tools
Using a JavaScript Editor
2
40 Acrobat JavaScript Scripting Guide
7. When the code is complete, click Close to close the editor.
If there are errors in your code, the JavaScript editor highlights the code line in question
and display an error message, as shown below in Figure 2.7.
FIGURE 2.7 Error detected by the JavaScript Editor
In Figure 2.7, the quotation mark to the right of the string is missing.
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.
Acrobat JavaScript Scripting Guide 41
Acrobat JavaScript Tools
Specifying the Default JavaScript Editor
2
Specifying the Default JavaScript Editor
You may 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, invoke the
Preferences dialog box as shown in Figure 2.1 above and in Figure 2.8 below:
1. Choose Edit > Preferences 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.
FIGURE 2.8 Selecting the Editor in Preferences
The Acrobat JavaScript Editor option sets the built-in Acrobat JavaScript Editor as the
default.
The External JavaScript Editor option sets an external editor as the default. To choose
this option, click Browse... to specify the path to the desired JavaScript editor.
NOTE: For some external editors, Acrobat provides extra command line options for
invoking the editor. For details, see Additional Editor Capabilities.
Acrobat JavaScript Tools
Using the Built-in Acrobat JavaScript Editor
2
42 Acrobat JavaScript Scripting Guide
Using the Built-in Acrobat JavaScript Editor
Like the Acrobat JavaScript Console, the built-in Acrobat 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.
In this case, the results of the JavaScript expressions or statements are displayed in the
Console window, so you will also need to open the Acrobat JavaScript Console to see them.
This is how you may keep the results separate from your Acrobat JavaScript code.
The Acrobat JavaScript Editor provides the same formatting options as those in the console
window. For details, see Formatting Code.
Using an External Editor
If an external editor program has been specified as the default application for editing
JavaScripts 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.
Acrobat 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 Macintosh-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 may add that parameter to the editor command line specified in the
Edit > Preferences > JavaScript dialog.
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).
Acrobat JavaScript Scripting Guide 43
Acrobat JavaScript Tools
Using an External Editor
2
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 may edit them. If no predefined
template is available for your editor, you may 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 Table 2.1below).
If your editor is not one that Acrobat currently supports, it will be necessary to check the
editors 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.
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 an Acrobat 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: \ Pr ogr amFi l es\ vsl i ck\ wi n\ 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 sytem shell. In the above case, if the
syntax error were on line 43, the command line generated would appear as follows:
"C: \ Pr ogr amFi l es\ vsl i ck\ wi n\ vs. exe" "C: \ Temp\ j sedi t . j s" +new - #43
NOTE: To insert %, [, or ] as characters in the command line, precede each of them with the
%escape character, thus using %%, %[, or %] respectively.
Acrobat JavaScript Tools
Using an External Editor
2
44 Acrobat JavaScript Scripting Guide
Testing Whether Your Editor Will Open at Syntax Error Locations
To determine whether Acrobat can open your editor on a line number, do the following:
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 automatically appears prompting you to fix the syntax error, check whether it
correctly specifies the line containing the error.
Saving and Closing a File with a Syntax Error
If you save and close a file containing a syntax error, Acrobat displays a dialog 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 line 123.
TABLE 2.1 Supported external JavaScript editors with command linetemplates.
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.gnusoftware.com/Emacs [ +%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]
Acrobat JavaScript Scripting Guide 45
Acrobat JavaScript Tools
Using the Acrobat JavaScript Debugger
2
Using the Acrobat JavaScript Debugger
The Acrobat JavaScript Debugger is a fully capable JavaScript 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 Acrobat JavaScript debugging is only available in Acrobat
Professional, the following instructions to make the complete debugger functionality
available in Adobe Reader on Windows and Macintosh platforms are provided as a
courtesy. 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 . j s, available at http://partners.adobe.com/asn/acrobat/docs.jsp or in
the SDK installation (Acr obat 7. 0 SDK/ J avaScr i pt Suppor t / Debugger / debugger . j s),
must be copied to the Acr obat 7. 0/ Reader / J avaScr i pt s folder.
2. Create key/value pairs in the registry settings, starting at the location
HKEY_CURRENT_USER\Software\Adobe\Acrobat Reader\7.0\JSPrefs\ on Windows
as shown below in Table 2.2, or in the property list file
<user>:Library:Preferences:com.adobe.Reader7.0.plist on the Macintosh. For the
Macintosh, use an appropriate editor for the property list file, and add the following
children under JSPrefs, using Type : Array in each case: Console Open, Console Input,
Enable Debugger, 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.
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).
TABLE 2.2 Registry Key/Value Pairs for Windows
bConsol eI nput REG_DWORD 0x00000001
bEnabl eDebugger REG_DWORD
0x00000001
i Excepti ons REG_DWORD
0x00000002
(this will break into the debugger
when exceptions occur)
Acrobat JavaScript Tools
Using the Acrobat JavaScript Debugger
2
46 Acrobat JavaScript Scripting Guide
As you learned earlier when opening the Acrobat JavaScript Console, which is integrated
with the debugger dialog box, the debugger may be activated in Acrobat Professional by
selecting Advanced > JavaScript > Debugger. In addition, the debugger automatically
opens if a running script throws an exception or encounters a previously set breakpoint.
NOTE: The Acrobat JavaScript Debugger cannot be used to analyze JavaScript stored in
HTML pages viewed by Web browsers such as NetScape or Internet Explorer, or any
other kind of scripting languages.
In order to make the debugger available for use, you will need to enable both JavaScript
and the debugger. As you did earlier, use the Edit > Preferences dialog to control the
behavior of the Acrobat JavaScript development environment. Enabling JavaScript and the
JavaScript editor are described in Enabling JavaScript. To enable the debugger, select
JavaScript from the list on the left in the Preferences dialog and make sure the Enable
JavaScript debugger... option is checked. 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, as shown above in Figure 2.1, and are explained below in Table 2.3.
Acrobat JavaScript Scripting Guide 47
Acrobat JavaScript Tools
Using the Acrobat JavaScript Debugger
2
TABLE 2.3 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:
Turn this option off.
Select Advanced > JavaScript > Document JavaScripts and
delete the ACRO_Breakpoi nts script.
Save the file.
When an exception
is thrown
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.
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 dialog box appears:
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.
Acrobat JavaScript Tools
Acrobat JavaScript Debugger
2
48 Acrobat JavaScript Scripting Guide
Acrobat JavaScript Debugger
You can open the Acrobat JavaScript Debugger at any time by selecting the Acrobat menu
item Advanced > JavaScript > Debugger. Familiarize yourself with the parts of the
window and the controls as described here before you attempt interactive debugging of a
script.
The section Accessing Scripts in the Scripts Window outlines the types and locations of
scripts that may be debugged. The section Starting the Debugger describes how to
automatically start the debugger for a script.
I MPORTANT: On Windows, while the Debugger is open and a debugging session is in
progress, Acrobat will be unavailable.
Main Groups of Controls
The debugger dialog, shown below in Figure 2.9, consists of three main groups of controls.
The toolbar on the top left contains six button controls that provide basic debugging
session functionality. See Figure 2.10 below for details.
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
Figure 2.9, and may be accompanied by the Script 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. Selecting entries in these lists enables you to view the nesting order of function
calls, and enable you to inspect the details of variables, watches, and breakpoints in the
Inspect details window.
Debugger View Windows
Below the main group of controls, the debugger provides a Views 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 Acrobat JavaScript Console.
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 Figure 2.9.
Acrobat JavaScript Scripting Guide 49
Acrobat JavaScript Tools
Acrobat JavaScript Debugger
2
FIGURE 2.9 Debugger Dialog Box
Acrobat JavaScript Tools
Debugger Buttons
2
50 Acrobat JavaScript Scripting Guide
Debugger Buttons
Figure 2.10 shows the debugger buttons on the toolbar, and Table 2.4 summarizes the
functionality of each button, followed by detailed descriptions below. An overview of their
usage is provided in Exercise: Calculator.
FIGURE 2.10 Debugger Buttons
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
TABLE 2.4 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 Interrupt Quit Step Over Step Into Step Out
Acrobat JavaScript Scripting Guide 51
Acrobat JavaScript Tools
Debugger Buttons
2
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.
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 in Figure 2.11:
FIGURE 2.11 Position Indicator at a Function Call
Excecution is currently halted before the call to cal l Me(). Assuming that there are no
errors or breakpoints in cal l Me(), clicking Step Over executes the entire cal l Me()
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. Refer again to Figure 2.11. Clicking Step Into at this
point advances the position indicator to the first statement within the cal l Me() function.
NOTE: Be aware that 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.
Acrobat JavaScript Tools
Debugger Scripts Window
2
52 Acrobat JavaScript Scripting Guide
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. The debugger
displays these in the Scripts window (see Figure 2.12 below for an example).
FIGURE 2.12 Scripts window
Accessing Scripts in the Scripts Window
To display the content 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 for the given function is available. As shown above
in Figure 2.12, a function has been defined for a mouse-up action on a button named
Button1. Click on the script icon to display its code.
Acrobat JavaScripts can be stored in several places, which may be either inside or outside
PDF files. The following sections describe their possible locations.
Acrobat JavaScript Scripting Guide 53
Acrobat JavaScript Tools
Debugger Scripts Window
2
Scripts Inside PDF Files
Table 2.5 below lists the types of scripts contained in PDF files. These can be accessed from
the Scripts window within the debugger dialog. You can edit them from inside the
debugger, and set breakpoints as described in Breakpoints on page 58.
NOTE: Changes to scripts do not take effect until the scripts are re-run; changes cannot be
applied to a running script.
Form Editing mode To switch to form editing mode, use the Acrobat Advanced Editing
toolbar. If it is not visible, select Tools > Advanced Editing > Show Advanced Editing
Toolbar. You may want to dock this toolbar, as you will use it frequently.
TABLE 2.5 Scripts inside PDF files
Location Access
Document level Advanced > JavaScript > Document JavaScripts
Document actions Advanced > JavaScript > Set Document Actions
Page actions Click the page on the Pages tab; select Options > Page Properties
Forms Double-click the form object in form editing mode (see below) to
bring up the Form Properties dialog
Bookmarks Click the bookmark on the Bookmarks tab; select Options >
Bookmark Properties
Links Double-click the link object in form editing mode to bring up the
Link Properties dialog
Acrobat JavaScript Tools
Debugger Scripts Window
2
54 Acrobat JavaScript Scripting Guide
Scripts Outside PDF Files
Scripts outside of Acrobat are also listed in the Scripts window and are available for
debugging in Acrobat. Table 2.6 lists these script types and how to access them.
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 for details.
TABLE 2.6 Scripts outside PDF files
Location Access
Folder level Stored as JavaScript (. j s) files in the App or User folder areas
Console Typed and evaluated in the console window
Batch Choose Advanced > Batch Processing
Acrobat JavaScript Scripting Guide 55
Acrobat JavaScript Tools
Call Stack List
2
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 below in Figure 2.13. 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 on that entry. They
appear in the Inspect details window immediately below the call stack list, as shown below
in Figure 2.13.
FIGURE 2.13 Call stack
You may 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.
Acrobat JavaScript Tools
Inspect Details Window
2
56 Acrobat JavaScript Scripting Guide
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 Figure 2.14
below, 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.
FIGURE 2.14 Inspect details window button controls
New Delete Edit
Acrobat JavaScript Scripting Guide 57
Acrobat JavaScript Tools
Inspect Details Window
2
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 appears, allowing you to enter a new value for the
variable as shown below in Figure 2.15.
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.
FIGURE 2.15 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, select Watches from the Inspect drop-down list. Click the New button, and
a dialog prompts you for the JavaScript variable or expression to be evaluated.
To change the value of a watch, select the watch from the list. Click the Edit button, which
displays a dialog prompting you to specify a new expression for evaluation. To delete a
watch, select it from the Inspect drop-down list and click the Delete button.
Acrobat JavaScript Tools
Inspect Details Window
2
58 Acrobat JavaScript Scripting Guide
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).
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
should cause 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 should subsequently disappear.
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,
f unct i on cal l Me( ) { / / cur l y br ace on same l i ne as f unct i on name
var a = 0;
}
Style 2: Place the left curly brace on a separate line, for example
f unct i on cal l Me( )
{ / / cur l y br ace i s on a separ at e l i ne
var a = 0;
}
If you would like to set a breakpoint at the function heading, use Style 1. Note that the
Acrobat 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 below in Figure 2.16. It is possible to set the breakpoint on the line below
the function heading for cal l Me(), 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.
FIGURE 2.16 Setting a Breakpoint at a Function Heading
Acrobat JavaScript Scripting Guide 59
Acrobat JavaScript Tools
Starting the Debugger
2
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 may edit and delete breakpoints using the
button controls just beneath the Inspect details window, as shown above in Figure 2.14.
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, select Breakpoint from the Inspect drop-down list and
click Edit. A dialog appears, prompting you to change the breakpoint condition.
Starting the Debugger
There are four ways to invoke the Acrobat 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 to proceed with the debugging session.
Debug From Start
Choose Advanced > JavaScript 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.
Acrobat JavaScript Tools
Exercise: Calculator
2
60 Acrobat JavaScript Scripting Guide
Click Interrupt
Open the debugger window and click the Interrupt button, 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.
Debugging From an Arbitrary Point in the Script
Define a Breakpoint
To start debugging from a specific point in your script, you can set a breakpoint. See
Breakpoints for details on how to set a breakpoint.
Using the debugger keyword
You can also 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.
Exercise: Calculator
NOTE: To complete the following exercises, unzip the file Test Debugger . zi p and open
Cal c. pdf .
In this exercise, you will set breakpoints in a script and create watches to view how a
variable changes as the script executes. At the end of this exercise you will be able to:
Start the debugger from a location within a script.
Interpret the contents of the Inspect details window.
Create, edit, and delete watches.
Set and clear breakpoints.
Use the debugger buttons to control how the interpreter executes the code in the script.
Calculator
Cal c. pdf uses document-level and form field-level scripts to simulate the behavior of a
simple calculator. The keypad consists of numeric and function keys, the period (. ), the
equals sign (=), and Cancel (C) and Cancel Entry (CE) keys.
Acrobat JavaScript Scripting Guide 61
Acrobat JavaScript Tools
Exercise: Calculator
2
How the Calculator Displays Output
Cal c. pdf uses the Acrobat Docs getFi el d() method to place values in the calculator
display window, which is the text field di spl ay. In this statement, getFi el d() binds
the variable di spl ay to this field:
var di spl ay = t hi s. get Fi el d( "Di spl ay") ;
Every time a numeric key is clicked, its value should be shown in the calculator display
window. To do this, we define a MouseUpaction for each numeric key in which the
number shown on the key is assigned to the calculator display window. For example, when
the user clicks the 7 button, the MouseUpaction associated with the button could assign
the value returned by di gi t_button(7) to the calculator window as shown below:
di spl ay. val ue = di gi t _but t on( 7) ;
Cal c. pdf uses a similar mechanism to display the strings representing arithmetic
operations to the func text field, which is used to display the operation (PLUS, MINUS,
MULT, DIV). In this statement, getFi el d() binds the variable func to this field:
var f unc = t hi s. get Fi el d( "Func") ;
The code below is contained in the MouseUpaction for the division (/ ) key, and represents
a call to the func_button() script:
f unc_but t on( "DI V") ;
The action passes the string "DI V" to the func_button() functions parameter named
req_func, which is thus bound to that value.
Later in the function, this statement is encountered:
f unc. val ue = r eq_f unc
Because getFi el d() has bound the func variable to the "Func" field, this statement
displays the string "DI V" in the field.
Values With More Than 1 Digit
To adjust for values greater than or equal to 10, the calculator multiplies the current value
by 10 and adds the value of the numeric key selected. For example, if the current value is 2
and the user clicks the 3 button, the new current value is 23 (10 times 2 plus 3).
For decimal values, a MouseUpaction is associated with the . button. In this action, the
calculator multiplies the divisor by 10. Subsequently, when other numeric keys are
selected, the calculator divides the selected value by the divisor, and adds that amount to
the current value. For example, if the current divisor is 1 and the user presses the 2, ., and 4
buttons, respectively, the current value is first updated to 2, the divisor becomes 10, and 4 is
divided by the divisor to obtain 0.4, which is added to 2 to obtain 2.4, which is assigned to
the new current value and shown in the display area.
Testing the Calculator
To familiarize yourself with the basic calculator operations, open Cal c. pdf in Acrobat and
try entering expressions and evaluating their results.
When you are familiar with the calculators operation, close this file.
Acrobat JavaScript Tools
Summary
2
62 Acrobat JavaScript Scripting Guide
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 is running. This may occur when debugging a
batch sequence. If a modal dialog 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. setI nterval () or
app. setTi meOut() method may trigger the appearance of a series of recurring alert
messages. If this occurs, press the Esc key after the modal dialog has exited.
Summary
The Acrobat JavaScript Debugger is a fully capable tool for troubleshooting problems in
Acrobat JavaScript scripts. In combination with the Edit > Preferences dialog box, the
debugger enables you to make decisions about how to control the behavior of your
Acrobat JavaScript development environment, which consists of three main sets of controls
for selecting and executing scripts. The six buttons provide basic control over execution,
the Scripts window enables you select a script for debugging, the Call Stack and Inspect
lists, in combination with an Inspect details window, provide a view of nested function calls
(stack frames) as well as details related to objects, variables, watches, and breakpoints. You
may utilize the Inspect details window controls to set and clear breakpoints, inspect
variable values while stepping through JavaScript code, and manage custom watches for
examination during script execution.
Acrobat JavaScript Scripting Guide 63
3
Acrobat JavaScript Contexts
Introduction
Acrobat JavaScript can be used to create scripts that are used for batch sequences and at
various levels within documents. This chapter discusses how to determine the appropriate
level for a JavaScript, and how to create and access Acrobat JavaScripts at all levels.
Chapter Goals
At the end of this chapter, you will be able to:
List the Acrobat JavaScript contexts and describe their purposes.
Describe how to create and edit scripts at all levels.
Contents
Topics
Introduction to Acrobat JavaScript Contexts
Folder Level JavaScripts
Document Level JavaScripts
Field Level JavaScripts
Batch Level JavaScripts
Acrobat JavaScript Contexts
Introduction to Acrobat JavaScript Contexts
3
64 Acrobat JavaScript Scripting Guide
Introduction to Acrobat JavaScript Contexts
Acrobat JavaScripts can be applied at a variety of levels:
folder level
document level
field level
batch level.
Each of these levels represents a context in which processing occurs, which has
implications about when the scripts are loaded and their accessibility inside and outside
documents.
In addition, the placement of a JavaScript 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 only visible to the form fields
with which they are associated.
NOTE: For instructions on how to disallow changes to scripts or hide scripts, see How can I
disallow changes in scripts contained in my document? and How can I hide scripts
contained in my document?
Folder Level JavaScripts
Folder level JavaScripts contain variables and functions that may be generally useful to
Acrobat, and are visible from all documents. 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 may create and store the scripts for
these in folder level JavaScripts.
Folder level JavaScripts are placed in separate files that have the ". j s" extension. App
folder level scripts are stored in the Acrobat applications J avaScr i pt s folder, and User
folder level scripts are stored in the users J avaScr i pt s folder. These scripts are loaded
when Acrobat starts execution, and are associated with the event objects Application
Initialization (App/ I ni t) event.
When Acrobat is installed on your machine, it provides you with several standard folder
level JavaScript files, including Af or m. j s, , Annot s. j s , and ADBC. j s. In addition, your
User folder may also contain gl ob. j s , which is programmatically generated and contains
cross-session application preferences set using the gl obal objects setPersi stent()
method, and Conf i g. j s, which is used to customize the look of the viewer by adjusting its
toolbar buttons and menu items. For example, app. addMenuI tem() calls would be
locaed in Conf i g. j s.
To create folder level JavaScripts, use an external editor running in parallel to Acrobat. Note
that the external editor cannot be invoked from Acrobat.
Acrobat JavaScript Scripting Guide 65
Acrobat JavaScript Contexts
Document Level JavaScripts
3
Document Level JavaScripts
Document level JavaScripts are function and variable definitions that are generally useful
to a given document, but are not applicable outside the document.
To create or access document level JavaScripts in Acrobat, select Advanced > JavaScript >
Document JavaScripts, which enables you to add, modify, or delete document level
scripts. Document level scripts are executed after the document has opened, and are stored
within the PDF document.
Field Level JavaScripts
You can associate a JavaScript with any component within a document. In the case of
dynamic XML forms, such scripts are only visible to that component and execute as actions
or events. For example, you may associate an action page open or page close events, as
well as a MouseUpevent for a bookmark, page, or form field. Field level scripts are
executed as the events occur, and are usually applied 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 JavaScripts. The most straightforward
manner is to right-click the form field, select Properties context menu item and choose the
Actions tab, as shown above in Figure 2.6. Additionally, you may select Advanced >
JavaScripts > Edit all JavaScripts ....
Batch Level JavaScripts
A batch level JavaScript is a script that can be applied to a collection of documents, and
operates at the application level. For example, you may define a batch script to print a
series of documents or apply security restrictions to them.
To create or edit a batch level JavaScript in Acrobat, select Advanced > Batch
Processing....
Acrobat JavaScript Contexts
Summary
3
66 Acrobat JavaScript Scripting Guide
Summary
Acrobat JavaScripts can be applied either within a document or outside a document. Inside
a document, scripts can be created so that they are visible throughout the document
(document level JavaScripts), or visible only to a given form field within the document
(field-level JavaScripts). Outside a document, scripts can be created so that they provide
generally useful functions or variables available to all documents (folder level JavaScripts),
or they can be created for the purpose of processing a collection of documents (batch level
JavaScripts).
The decision to place a JavaScript at a given level is based on its general applicability. If a
script is to have a specialized function applicable to a single component within a
document, it would be appropriate to create a field level JavaScript. If a script would be
generally useful to several form fields within a document, it would be appropriate to create
a document level JavaScript. If a function or variable can be used in a variety of situations
within many documents, it would be appropriate to create a folder level JavaScript.
Acrobat JavaScript Scripting Guide 67
4
Creating and Modifying PDF
Documents
Introduction
This chapter provides a detailed overview of how to apply Acrobat JavaScript in order to
dynamically create PDF files, modify them, and convert PDF files to XML format.
Chapter Goals
At the end of this chapter, you will be able to:
Describe how to use Acrobat JavaScript to create and modify PDF files.
Convert PDF documents to XML format.
Contents
Topics
Creating and Modifying PDF Files
Creating PDF Files from Multiple Files
Converting PDF Documents to XML Format
Creating and Modifying PDF Documents
Creating and Modifying PDF Files
4
68 Acrobat JavaScript Scripting Guide
Creating and Modifying PDF Files
Acrobat JavaScript provides 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
enhance the workflow process.
To create a new PDF file, invoke the appobjects newDoc() method, as shown in the
example below:
var myDoc = app. newDoc( ) ;
Once this statement has been executed, you may add content by invoking methods
contained within the doc object, as indicated below in Table 4.1:
TABLE 4.1 Acrobat JavaScript Usage for Creating Content in a PDF Document
Content Object Methods
page doc newPage, i nsertPages,
repl acePages
page templ ate spawn
annot doc addAnnot
field doc addFi el d
icon doc addI con
link doc addLi nk
document-level
JavaScript
doc addScri pt
thumbnails doc addThumbnai l s
bookmark doc. bookmarkRoot createChi l d,
i nsertChi l d
web link doc addWebLi nks
template doc createTempl ate
Acrobat JavaScript Scripting Guide 69
Creating and Modifying PDF Documents
Creating and Modifying PDF Files
4
Combining PDF Documents
You can take advantage of Acrobat JavaScript to customize and automate the process of
combining PDF documents.
If you would like to combine multiple PDF files into a single PDF document, you may do so
through a series of calls to the doc objects i nsertPages method. For example, the
following code creates a new document that is composed from two other documents:
/ / Cr eat e a new PDF document :
var newDoc = app. newDoc( ) ;
/ / I nser t doc1. pdf :
newDoc. i nser t Pages( {
nPage : - 1,
cPat h : "/ c/ doc1. pdf ",
}) ;
/ / I nser t doc2. pdf :
newDoc. i nser t Pages( {
nPage : newDoc. numPages,
cPat h : "/ c/ doc2. pdf ",
}) ;
/ / Save t he new document :
newDoc. saveAs( {
"/ c/ myNewDoc. pdf ") ;
}) ;
/ / Cl ose t he new document wi t hout not i f yi ng t he user :
newDoc. cl oseDoc( t r ue) ;
Creating PDF Files from Multiple Files
It is possible to dynamically add content from other sources into a new PDF file. The sources
may include files whose types conform to Multipurpose Internet Mail Extensions (MIME

)
type definitions. One simple approach would be to invoke the appobjects openDoc
method to convert and open other files with supported formats, and then save or combine
files as a PDF document.
Another way to import an external file into a PDF document is to invoke the doc objects
i mportDataObj ect method. After doing this, it is possible to extract information from
the external file for placement and presentation within the PDF document. For example,
the following code illustrates how to import an XML file and extract its content:
t hi s. i mpor t Dat aObj ect ( "myFi l e", "/ c/ myFi l e. xml ") ;
var myDat a = t hi s. get Dat aObj ect ( "myFi l e") ;
f or ( var i i n myDat a)
consol e. pr i nt l n( myDat a[ i ] ) ;
Creating and Modifying PDF Documents
Creating and Modifying PDF Files
4
70 Acrobat JavaScript Scripting Guide
If you would like to automate the insertion of multiple PDF files into a single PDF
document, you may do so through a series of calls to the doc objects i nsertPages and
repl acePages methods. For example, the following code inserts a cover page at the
beginning of the current document:
t hi s. i nser t Pages( {
nPage : - 1,
cPat h : "/ c/ myCover Page. pdf ",
nSt ar t : 0
}) ;
Finally, if you would like to use a portion of the current document to create a new
document, you may do so by invoking the doc objects extractPages method. For
example, suppose the 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 f i l ename = "i nvoi ce";
f or ( var i = 0; i < t hi s. numPages; i ++)
t hi s. ext r act Pages( {
nSt ar t : i ,
cPat h : f i l ename + i + ". pdf "
}) ;
Cropping and Rotating Pages
Cropping Pages
The Acrobat JavaScript 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
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
Acrobat JavaScript Scripting Guide 71
Creating and Modifying PDF Documents
Creating and Modifying PDF Files
4
For example, the following code crops pages 2-5 of the document to a 400 by 500 pixel
area:
t hi s. set PageBoxes( {
cBox: "Cr op",
nSt ar t : 2,
nEnd: 5,
r Box: [ 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 r ect = t hi s. get PageBox( "Cr op", 3) ;
Rotating Pages
You may use Acrobat 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 objects setPageRotati ons and getPageRotati onmethods are used to
set and retrieve page rotations.
The setPageRotati ons 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:
t hi s. set PageRot at i ons( 2, 5, 90) ;
To retrieve the rotation for a given page, invoke the doc objects getPageRotati on
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 r ot at i on = t hi s. get PageRot at i on( 3) ;
consol e. pr i nt l n( "Page 3 i s r ot at ed " + r ot at i on + " degr ees. ") ;
Creating and Modifying PDF Documents
Creating and Modifying PDF Files
4
72 Acrobat JavaScript Scripting Guide
Extracting, Moving, Deleting, Replacing, and Copying Pages
The Acrobat JavaScript doc object, in combination with the appobject, can be used to
extract pages from one document and place them in another, and moving or copying
pages within or between documents.
The appobject 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:
i nsertPages: inserts pages from the source document into the current document
del etePages: deletes pages from the document
repl acePages: 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 objects
del etePages 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:
t hi s. del et ePages( {nSt ar t : 2, nEnd: 5}) ;
Suppose you would like to copy pages from one document to another. Invoke the doc
objects i nsertPages method, which accepts four parameters:
nPage: the zero-based index of the page after which to insert the new 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
For example, the following code inserts pages 2 through 5 from mySour ce. pdf at the
beginning of the current document:
t hi s. i nser t Pages( {
nPage: - 1,
cPat h: "/ C/ mySour ce. pdf ",
nSt ar t : 2,
nEnd: 5
}) ;
Acrobat JavaScript Scripting Guide 73
Creating and Modifying PDF Documents
Creating and Modifying PDF Files
4
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 mySour ce. pdf and move them into myTar get . pdf :
/ / t hi s r epr esent s myTar get . pdf
/ /
/ / Fi r st copy t he pages f r omt he sour ce t o t he t ar get document
t hi s. i nser t Pages( {
nPage: - 1,
cPat h: "/ C/ mySour ce. pdf ",
nSt ar t : 2,
nEnd: 5
}) ;
/ /
/ / Now del et e t he pages f r omt he sour ce document
var sour ce = app. openDoc( "/ C/ mySour ce. pdf ") ;
sour ce. del et ePages( {nSt ar t : 2, nEnd: 5}) ;
To replace pages in one document with pages from another document, invoke the target
documents repl acePages 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 mySour ce. pdf replace pages 30 through
33 of myTar get . pdf :
/ / t hi s r epr esent s myTar get . pdf
t hi s. r epl acePages( {
nPage: 30,
cPat h: "/ C/ mySour ce. pdf ",
nSt ar t : 2,
nEnd: 5
}) ;
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 desired location in the original
document.
3. Delete the source pages from the original document.
Creating and Modifying PDF Documents
Creating and Modifying PDF Files
4
74 Acrobat JavaScript Scripting Guide
The following example moves pages 2-5 after page 30 in the document:
/ / Fi r st cr eat e t he t empor ar y document :
var t empDoc = app. newDoc( "/ C/ t emp. pdf ") ;
/ / Copy pages 2- 5 i nt o t he t empor ar y f i l e
t empDoc. i nser t Pages( {
cPat h: "/ C/ mySour ce. pdf ",
nSt ar t : 2,
nEnd: 5
}) ;
/ / Copy al l of t he t empor ar y f i l e pages back i nt o t he or i gi nal :
t hi s. i nser t Pages( {
nPage: 30,
cPat h: "/ C/ t emp. pdf "
}) ;
/ / Now del et e pages 2- 5 f r omt he sour ce document
t hi s. del et ePages( {nSt ar t : 2, nEnd: 5}) ;
Adding Watermarks and Backgrounds
The doc objects addWatermarkFromText and addWatermarkFromFi l emethods
create watermarks within a document, and place them in optional content groups (OCGs).
The addWatermarkFromFi l emethod adds a page as a watermark to the specified
pages in the document. The example below adds the first page of wat er mar k. pdf as a
watermark to the center of all pages within the current document:
t hi s. addWat er mar kFr omFi l e( "/ C/ wat er mar k. pdf ") ;
In the next example, the addWatermarkFromFi l emethod is used to add the second
page of wat er mar k. 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:
t hi s. addWat er mar kFr omFi l e( {
cDI Pat h: "/ C/ wat er mar k. pdf ",
nSour cePage: 1,
nEnd: 9,
nHor i zAl i gn: 0,
nVer t Al i gn: 0,
nHor i zVal ue: 144,
nVer t Val ue: - 72,
nRot at i on: 45
}) ;
Acrobat JavaScript Scripting Guide 75
Creating and Modifying PDF Documents
Converting PDF Documents to XML Format
4
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:
t hi s. addWat er mar kFr omText (
"Conf i dent i al ",
0,
f ont . Hel v,
24,
col or . r ed
) ;
Adding Headers and Footers
As you learned in Adding Watermarks and Backgrounds, you may use Acrobat JavaScripts
watermarking functionality to add headers and footers to your documents by invoking the
doc objects addWatermarkFromText method, which can be applied as a header or
footer by specifying the placement of the text at the top or bottom of the page. The
following example places a multiline header, one inch down and one inch over from the
top right corner of all the pages within the current document:
t hi s. addWat er mar kFr omText ( {
cText : "Conf i dent i al Document ",
nText Al i gn: 2,
nHor i zAl i gn: 2,
nVer t Al i gn: 0,
nHor i zVal ue: - 72,
nVer t Val ue: - 72
}) ;
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 objects 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 ASN
documentation. For XML, the conversion ID is " com. adobe. acr obat . xml - 1- 00" .
The following code converts the current PDF file to C: \ t est . xml :
t hi s. saveAs( " / c/ t est . xml " , " com. adobe. acr obat . xml - 1- 00" ) ;
Creating and Modifying PDF Documents
Converting PDF Documents to XML Format
4
76 Acrobat JavaScript Scripting Guide
Acrobat JavaScript Scripting Guide 77
5
Print Production
Introduction
This chapter will provide you with an in-depth understanding of the ways in which you may
manage print production workflows for PDF documents.
Chapter Goals
At the end of this chapter, you will be able to:
Use Acrobat JavaScript to automate and control print quality.
Determine whether a file will be sent to a printer or a PostScript file.
Control how PDF layers are printed.
Contents
Topics
Printing PDF Documents
Printing Documents with Layers
Setting Advanced Print Options
Print Production
Print Production
5
78 Acrobat JavaScript Scripting Guide
Print Production
Since printing involves sending pages to an output device, there are many options that can
affect print quality. Acrobat JavaScript can be used to enhance and automate the use of
these options in print production workflows, primarily through the use of the
pri ntParams object, whose properties and methods are described below in Table 5.1:
TABLE 5.1 PrintParams Properties
Property Description
bi naryOK Binary printer channel is supported
bi tmapDPI DPI used for bitmaps or rasterizing transparency
col orOverri de Uses color override settings
col orProfi l e Color profile based on available color spaces
constants Wrapper object for pri ntParams constants
downl oadFarEastFonts Sends Far East fonts to the printer
fi l eName Filename is used when printing to a file instead of a
printer
fi rstPage The first zero-based page to be printed
fl ags A bit field of flags to control printing options
fontPol i cy Used to determine when fonts are emitted
gradi entDPI The DPI used for rasterizing gradients
i nteracti ve Sets the level of interaction for the user
l astPage The last zero-based page to be printed
pageHandl i ng How pages will be handled (fit, shrink, or tiled)
pageSubset Even, odd, or all pages are printed
pri ntAsI mage Sends pages as large bitmaps
pri ntContent Determines whether form fields and comments will be
printed
pri nterName The name of the destination printer
psLevel The level of PostScript emitted to the printer
rasterFl ags A bit field of flags for outlines, clips, and overprint
Acrobat JavaScript Scripting Guide 79
Print Production
Print Production
5
In addition to the pri ntParams objects properties, the appobjects
pri ntCol orProfi l es and pri nterNames properties provide a list of available color
spaces and printer names, respectively. Also, the fi el dobjects pri nt method can be
used to determine whether an individual field will be printed.
Printing PDF Documents
It is possible to use Acrobat 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
objects pri nt method. Its parameters are described below in Table 5.2:
reversePages Prints pages in reverse order
ti l eLabel Labels each page of tiled output
ti l eMark Output marks to cut the page and where overlap
occurs
ti l eOverl ap The number of points that tiled pages have in
common
ti l eScal e The amount that tiled pages are scaled
transparencyLevel The degree to which high level drawing operators are
preserved
userPri nterCRD Determines whether the printer Color Rendering
Dictionary is used
useT1Conversi on Determines whether Type 1 fonts will be converted
TABLE 5.2 Print Method Parameters
Parameter Description
bUI Determines whether to present a user interface to the
user
nStart The zero-based index of the beginning page
nEnd The zero-based index of the last page
bSi l ent Suppresses the Cancel dialog box while the document
is printed
bShri nkToFi t Determines whether the page is shrunk to fit the
imageable area of the printed page
TABLE 5.1 PrintParams Properties
Property Description
Print Production
Print Production
5
80 Acrobat JavaScript Scripting Guide
In the first example below, pages 1-10 of the document are sent to the default printer, print
silently without user interaction, and are shrunk to fit the imageable area of the pages:
t hi s. pr i nt ( {
bUI : f al se,
bSi l ent : t r ue,
bShr i nkToFi t : t r ue,
nSt ar t : 1,
nEnd: 10
}) ;
To print the document to a PostScript file, obtain the pri ntParams object by invoking
the doc objects getPri ntParams method. Set its pri nterNameproperty to the
empty string, and set its fi l eNameproperty 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 = t hi s. get Pr i nt Par ams( ) ;
pp. pr i nt er Name = "";
pp. f i l eName = "/ C/ myPSDoc. ps";
t hi s. pr i nt ( pp) ;
If you would like send the file to a particular printer, you may specify the printer by setting
the pri nterNameproperty of the pri ntParams object, as shown in the following
example:
var pp = t hi s. get Pr i nt Par ams( ) ;
pp. i nt er act i ve = pp. const ant s. i nt er act i onLevel . aut omat i c;
pp. pr i nt er Name = "hp of f i cej et d ser i es";
t hi s. pr i nt ( pp) ;
bPri ntAsI mage Determines whether to print each page as an image
bReverse Determines whether to print in reverse page order
bAnnotati ons Determines whether to print annotations
pri ntParams The pri ntParams object containing the printing
settings
TABLE 5.2 Print Method Parameters
Parameter Description
Acrobat JavaScript Scripting Guide 81
Print Production
Print Production
5
Silent Printing
There are various ways to print a document without requiring user interaction. One way is
to use the doc objects pri nt method and set the bSi l ent attribute to true, as shown
in Printing PDF Documents on page 79 and in the following example:
t hi s. pr i nt ( {bUI : f al se, bSi l ent : t r ue, bShr i nkToFi t : t r ue}) ;
If you would like to print without requiring user interaction, but would like to display a
progress monitor and automatically disappearing cancel dialog box, use the interactive
property as shown in the following example:
var pp = t hi s. get Pr i nt Par ams( ) ;
pp. i nt er act i ve = pp. const ant s. i nt er act i onLevel . aut omat i c;
There are many options you may choose without requiring user interaction. For example,
you can select the paper tray:
var f v = pp. const ant s. f l agVal ues;
pp. f l ags | = f v. set PageSi ze;
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 Acrobat JavaScript Scripting Reference, as well as the Acrobat
SDK samples SDKSilentPrint.js and SDKJSSnippet1.pdf.
Printing Documents with Layers
The pri ntParams objects pri ntContent property 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 = t hi s. get Pr i nt Par ams( ) ;
pp. i nt er act i ve = pp. const ant s. i nt er act i onLevel . si l ent ;
pp. pr i nt Cont ent = pp. const ant s. pr i nt Cont ent . f or mFi el dsOnl y;
t hi s. pr i nt ( pp) ;
Print Production
Print Production
5
82 Acrobat JavaScript Scripting Guide
Setting Advanced Print Options
You can set the pri ntParams objects properties to specify advanced options including
output, marks and bleeds, transparency flattening, PostScript options, and font options.
Specifying Output Settings
You may obtain a listing of printer color spaces available by invoking the appobjects
pri ntCol orProfi l es method. You may then assign one of these values to the
pri ntParams objects col orProfi l eproperty.
In addition, you may set the pri ntParams objects fl ags property to specify advanced
Output settings, such as applying proof settings, shown in the example below:
var pp = t hi s. get Pr i nt Par ams( ) ;
var f v = pp. const ant s. f l agVal ues;
pp. f l ags | = f v. appl ySof t Pr oof Set t i ngs;
t hi s. pr i nt ( pp) ;
Specifying Marks and Bleeds
You can specify the types of tile marks and where overlap occurs by setting the
pri ntParams objects ti l eMarkproperty. For example, in the following code, Western
style tile marks are printed:
var pp = t hi s. get Pr i nt Par ams( ) ;
pp. t i l eMar k = pp. const ant s. t i l eMar ks. west ;
t hi s. pr i nt ( pp) ;
Setting PostScript Options
You may set the pri ntParams objects fl ags property to specify advanced PostScript
settings, such as emitting undercolor removal/black generation, shown in the example
below:
var pp = t hi s. get Pr i nt Par ams( ) ;
var f v = pp. const ant s. f l agVal ues;
pp. f l ags &= ~( f v. suppr essBG | f v. suppr essUCR) ;
t hi s. pr i nt ( pp) ;
In addition, you may set the pri ntParams objects psLevel property to specify the
level of PostScript emitted to PostScript printers. In addition, if the printer only supports
PostScript level 1, set the pri ntParams objects pri ntAsI mageproperty to true.
Acrobat JavaScript Scripting Guide 83
Print Production
Print Production
5
Setting Font Options
You can control the font policy by setting the pri ntParams objects fontPol i cy
property. 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.
j obStart: 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 may be used to optimize the balance between memory and
speed constraints.
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 = t hi s. get Pr i nt Par ams( ) ;
pp. f ont Pol i cy = pp. const ant s. f ont Pol i cy. j obSt ar t ;
t hi s. pr i nt ( pp) ;
You may also control whether Type 1 fonts will be converted to alternative font
representations, by setting the pri ntParams objects useT1Conversi onproperty.
There are three values that may 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 = t hi s. get Pr i nt Par ams( ) ;
pp. useT1Conver si on = pp. usages. useT1Conver si on. aut o;
t hi s. pr i nt ( pp) ;
Finally, it is possible to send Far East fonts to the printer by setting the pri ntParams
objects downl oadFarEastFonts property to true.
Print Production
Print Production
5
84 Acrobat JavaScript Scripting Guide
Acrobat JavaScript Scripting Guide 85
6
Using Acrobat JavaScript in Forms
Introduction
In this chapter you will learn how to extend the functionality of Acrobat forms through the
application of Acrobat 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.
Chapter Goals
At the end of this chapter, you will be able to:
Use Acrobat JavaScript to create and enhance all types of PDF forms.
Create and modify form fields and their properties.
Use Acrobat JavaScript to make your forms secure, accessible, and web-ready.
Create XML forms and migrate legacy forms to XFA format.
Automate the collection and export of form data.
Make forms accessible, secure, and web-ready.
Contents
Topics
Forms Essentials
Filling in PDF Forms
Making Forms Accessible
Using JavaScript to Secure Forms
Using Acrobat JavaScript in Forms
Forms Essentials
6
86 Acrobat JavaScript Scripting Guide
Forms Essentials
Introduction
Acrobat JavaScript can be integrated into your forms to enhance their interactive
capabilities. You can extend the capability of your forms by using Acrobat 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.
Forms Essentials Topics
About PDF Forms
Creating Acrobat Form Fields
Setting Acrobat Form Field Properties
Making a Form Fillable
Setting the Hierarchy of Form Fields
Creating Forms From Scratch
Using Custom JavaScripts in Forms
Introduction to XML Forms Architecture (XFA)
Forms Migration: Working with Forms Created in Acrobat 6.0 or Earlier
Acrobat JavaScript Scripting Guide 87
Using Acrobat JavaScript in Forms
Forms Essentials
6
About PDF Forms
Types of PDF Forms
There are two types of PDF forms: Acrobat forms and XML forms.
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 in data, the information within the PDF 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 most recommended type is a XML form since
its format readily allows for Web service interactions and compatibility with document
processing needs within enterprise-wide infrastructures.
The new Adobe XML forms 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 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 Adobe 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 dialogs. Finally, the Acrobat 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 may 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.
Using Acrobat JavaScript in Forms
Forms Essentials
6
88 Acrobat JavaScript Scripting Guide
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 essential graphical user
interfaces, so layout and clarity will be a major consideration. Finally, consider the medium
on 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.
The creation of a new form, whether done through the Acrobat layout tools or LiveCycle


Designer, or programmatically through Acrobat 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.
Acrobat JavaScript Scripting Guide 89
Using Acrobat JavaScript in Forms
Forms Essentials
6
Creating Acrobat Form Fields
There are seven types of Acrobat form fields, each associated with a field type value as
shown below in Table 6.1:
You can use Acrobat JavaScript to create a form field by invoking the doc objects
addFi el d() method, which returns a fi el dobject. This method permits you to specify
the following information:
1. The field name. This may include hierarchical syntax in order to facilitate logical
groupings. For example, the name myGroup. fi rstFi el dimplies that the form field
fi rstFi el dbelongs 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.
2. One of the seven field type values listed above, surrounded by quotes.
3. 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.
4. 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 4 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 - l ef t x, upper - l ef t y, l ower - r i ght x, l ower - r i ght y].
TABLE 6.1 Acrobat Form Field Types
Form Field Field Type Value
Button button
Check Box checkbox
Combo Box combobox
List Box l i stbox
Radio Button radi obutton
Text Field text
Digital Signature si gnature
Using Acrobat JavaScript in Forms
Forms Essentials
6
90 Acrobat JavaScript Scripting Guide
For example, suppose you would like to place a Button named myButtonon 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 name = "myBut t on";
var t ype = "but t on";
var page = 0;
var l ocat i on = [ 100, 472, 172, 400] ;
var myFi el d = t hi s. addFi el d( name, t ype, page, l ocat i on) ;
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 through a call to the radio button collections setExportVal ues method.
For example, suppose we would like to create a set of three radio buttons, each 12 points
wide and 12 points high, all named myRadi o. 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 = "myRadi o";
var t ype = "r adi obut t on";
var page = 5;
t hi s. addFi el d( name, t ype, page, [ 400, 442, 412, 430] ) ;
t hi s. addFi el d( name, t ype, page, [ 400, 427, 412, 415] ) ;
var r b = t hi s. addFi el d( name, t ype, page, [ 400, 412, 412, 400] ) ;
r b. set Expor t Val ues( [ "Yes", "No", "Cancel "] ) ;
This code actually creates an array of 3 radio buttons, named myRadi o. 0, myRadi o. 1,
and myRadi o. 2.
Acrobat JavaScript Scripting Guide 91
Using Acrobat JavaScript in Forms
Forms Essentials
6
Setting Acrobat Form Field Properties
Acrobat 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 JavaScripts that control the
appearance and behavior of form fields.
Form Field Properties Topics
Format Options
Button Properties
Checkbox Properties
Combo Box Properties
Listbox Properties
Radio Button Properties
Signature Properties
Text Field Properties
Validation Options
Calculation Options
Highlighting Required Form Fields
Alerting Users Automatically for Required Form Fields
Using Acrobat JavaScript in Forms
Forms Essentials
6
92 Acrobat JavaScript Scripting Guide
Format Options
Format options applicable to form fields are applied to appearance, validation of data, and
calculation of results, and differ according to field type. The fi el dclass contains many
properties that may be used to set the format of a given form field. The most basic property
of every form field is its name, which provides the reference necessary for subsequent
access and modification.
General formatting options 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 below in Table 6.2.
TABLE 6.2 Format Options
Format Description Field Properties
display
rectangle
position and size of field on
page
rect
border style rectangle border appearance borderStyl e
stroke color applied to edge of surrounding
rectangle
strokeCol or
border
thickness
width of the edge of the
surrounding rectangle
l i neWi dth
orientation rotation of field in 90-degree
increments
rotati on
background
color
background color of field (gray,
transparent, RGB, or CMYK)
fi l l Col or
tooltip short description of field that
appears on mouse-over
userName
read only whether the user may change
the field contents
readonl y
scrolling whether text fields may scroll doNotScrol l
display visible or hidden on screen or in
print
di spl ay
Acrobat JavaScript Scripting Guide 93
Using Acrobat JavaScript in Forms
Forms Essentials
6
text font, color, size, rich text, comb
format, multiline, limit to
number of characters, file
selection format, or password
format
textFont, textCol or,
textSi ze, ri chText,
ri chVal ue, comb,
mul ti l i ne, charLi mi t,
fi l eSel ect, password
text alignment controls text layout in text fields al i gnment
button
alignment
controls alignment of icon on
button face
buttonAl i gnX,
buttonAl i gnY
button icon
scaling
relative scaling of an icon to fit
inside a button face
buttonFi tBounds,
buttonScal eHow,
buttonScal eWhen
highlight mode indicates how a button will
appear when pushed
hi ghl i ght
glyph style for checkbox and radio buttons styl e
number of
items
number of items in a combo
box or list box
numI tems
editable whether the user can type in a
combo box
edi tabl e
multiple
selection
whether multiple listbox items
may be selected
mul ti pl eSel ecti on
TABLE 6.2 Format Options
Format Description Field Properties
Using Acrobat JavaScript in Forms
Forms Essentials
6
94 Acrobat JavaScript Scripting Guide
Button Properties
We will begin by creating a button named myButton:
var f = t hi s. addFi el d( "myBut t on", "but t on", 0, [ 200, 250, 250, 400] ) ;
To create a blue border along the edges of its surrounding rectangle, we will set its
strokeCol or property:
f . st r okeCol or = col or . bl ue;
In addition, you may 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
borderStyl eproperty:
f . bor der St yl e = bor der . b;
To set the line thickness (in points) of the border, set its l i neWi dthproperty:
f . l i neWi dt h = 1;
To set its background color to yellow, we will set its fi l l Col or property:
f . f i l l Col or = col or . yel l ow;
To specify the text that appears on the button, invoke its buttonSetCapti onmethod:
f . but t onSet Capt i on( "Cl i ck Her e") ;
You may set the text size, color, and font:
f . t ext Si ze = 16;
f . t ext Col or = col or . r ed;
f . t ext Font = f ont . Ti mes;
To create a tooltip that appears when the mouse hovers over the button, set its userName
property:
f . user Name = "Thi s i s a but t on t ool t i p f or myBut t on. ";
In addition to the text, it is also possible to specify the relative positioning of the icon and
text on the buttons face. In this case, we will set the layout so that the icon appears to the
left of the text:
f . but t onPosi t i on = posi t i on. i conText H;
To specify whether the button should be visible either on screen or when printing, set its
di spl ay property:
f . di spl ay = di spl ay. vi si bl e;
To set the buttons appearance in response to user interaction, set its hi ghl i ght
property to one of the following values: none ( hi ghl i ght. n) , invert ( hi ghl i ght. i ) ,
push ( hi ghl i ght. p) , or outline ( hi ghl i ght. o) . In this example , we will specify that
the button appears to be pushed:
f . hi ghl i ght = hi ghl i ght . p;
Acrobat JavaScript Scripting Guide 95
Using Acrobat JavaScript in Forms
Forms Essentials
6
It is possible to specify the scaling characteristics of the icon within the button face. You
may determine when scaling takes place by setting the buttons buttonScal eWhen
property to one of the following values: always (scal eWhen. al ways), never
(scal eWhen. never), if the icon is too big (scal eWhen. tooBi g), or if the icon is too
small (scal eWhen. tooSmal l ). In this case, we will specify that the button always scales:
f . but t onScal eWhen = scal eWhen. al ways;
You may also determine whether the scaling will be proportional by setting the
buttonScal eHowproperty to one of the following values:
buttonScal eHow. proporti onal or buttonScal eHow. anamorphi c. In this case,
we will specify that the button scales proportionally:
f . but t onScal eHow = but t onScal eHow. pr opor t i onal ;
To guarantee that the icon scales within the bounds of the rectangular region for the
button, set the buttonFi tBounds property:
f . but t onFi t Bounds = t r ue;
You can specify the alignment characteristics of the icon by setting its buttonAl i gnX
and buttonAl i gnYproperties. 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 50would mean that the 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 . but t onAl i gnX = 50;
f . but t onAl i gnY = 50;
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 buttons area. To import an icon, invoke the
doc objects i mportI conmethod. To place the icon in the button, invoke the button
objects setI conmethod. Assuming you have already made the icon available in the
document and that its variable name is myI con, the following code would cause the icon
to appear on the buttons face:
f . set I con( myI con) ;
To rotate the button counterclockwise, set its rotati onproperty:
f . r ot at i on = 90;
Finally, you will undoubtedly wish to associate an action to be executed when the button is
clicked. You may do this by invoking the buttons setActi onmethod, which requires a
trigger (an indication of the type of mouse event) and an associated script. The possible
triggers are MouseUp, MouseDown, MouseEnter, MouseExi t, OnFocus, and OnBl ur.
The following code displays a greeting when the button is clicked:
f . set Act i on( "MouseUp", "app. al er t ( Hel l o ) ; " ) ;
Using Acrobat JavaScript in Forms
Forms Essentials
6
96 Acrobat JavaScript Scripting Guide
Checkbox Properties
The checkbox field supports many of the same properties as the button, and actions are
handled in the same manner. The properties common to bothform fields are:
userName
readonl y
di spl ay
rotati on
strokeCol or
fi l l Col or
l i neWi dth
borderStyl e
textSi ze
textCol or
In the case of textFont, however, the font is always set to Adobe Pi .
You may choose from six different glyph styles (the appearance of the check symbol that
appears when the user clicks in the check box): check (styl e. ch), cross (styl e. cr),
diamond (styl e. di ), circle (styl e. ci ), star (styl e. st), and square (styl e. sq). For
example, the following code causes a check to appear when the user clicks in the check
box:
f . st yl e = st yl e. ch;
When the user selects a check box, an export value may be associated with the option
invoking the fi el dobjects setExportVal ues property. For example, the code below
associates the export value "buy" with the check box:
f . set Expor t Val ues( [ "buy"] ) ;
If there are several check box fields, you may wish to indicate that one particular form field
is always checked by default. To do this, you must do two things:
1. Invoke the fields defaul tI sCheckedmethod. 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.
2. Reset the field to ensure that the default is applied by invoking the doc objects
resetFormmethod.
This process is shown in the following code:
f . def aul t I sChecked( 0) ; / / 0 means t hat check box #0 i s checked
t hi s. r eset For m( [ f . name] ) ;
Acrobat JavaScript Scripting Guide 97
Using Acrobat JavaScript in Forms
Forms Essentials
6
Combo Box Properties
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 fields edi tabl e
property, as shown in the following code:
f . edi t abl e = t r ue;
You may decide whether the users custom text will be checked for spelling by setting its
doNotSpel l Check property. The following code indicates that the spelling is not
checked:
f . doNot Spel l Check = t r ue;
A combo box may 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.
In the first case, as soon as the user clicks on an item in the combo box, an action may
automatically be triggered. If you would like to design your combo box this way, then set its
commi tOnSel Changeproperty to true. Otherwise, set the value to fal se. The
following code commits the selected value immediately:
f . commi t OnSel Change = t r ue;
To set the export values for the combo box items, invoke its setI tems method, which can
be used to set both the user and export values. In this case, the user 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, with
abbreviated state names as their corresponding export values:
f . set I t ems( [ "Ohi o", "OH"] , [ "Or egon", "OR"] , [ "Ar i zona", "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 comparefunction 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.
Using Acrobat JavaScript in Forms
Forms Essentials
6
98 Acrobat JavaScript Scripting Guide
In the following example, we define a comparefunction that accepts two parameters,
both of which are user/export value pairs, and compares their user values. For example, if
the first parameter is[ "Ohi o", "OH"] and the second parameter is [ "Ar i zona", "AZ"] ,
the comparefunction returns 1, since "Ohi o" is greater than "Ar i zona":
f unct i on compar e ( a, b)
{
i f ( a[ 0] < b[ 0] ) r et ur n - 1; / / i ndex 0 means user val ue
i f ( a[ 0] > b[ 0] ) r et ur n 1;
r et ur n 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 ar r = new Ar r ay( ) ;
var f = t hi s. get Fi el d( "myCombobox") ;
f or ( var i = 0; i < f . numI t ems; i ++)
ar r [ i ] = [ f . get I t emAt ( i , f al se) , f . get I t emAt ( i ) ] ;
At this point you may invoke the Array objects sort method and replace the items in the
combo box field:
ar r . sor t ( compar e) ; / / sor t t he ar r ay usi ng your compar e met hod
f . cl ear I t ems( ) ;
f . set I t ems( ar r ) ;
To specify whether the combo box automatically formats its entries as numbers,
percentage values, or other specialized formats, you may use the functions shown below in
Table 6.3. Their definitions are located in the file J avascr i pt s\ af or m. j s :
In all cases, invoke the method and pass in the "Format" trigger name as the first
parameter, followed by a script containing a call to one of the functions. For example, the
code below sets up the Number format:
f . set Act i on( "For mat ", AFNumber For mat ( 2, 0, 0, 0, "\ u20ac", t r ue) ) ;
NOTE: You may also create Custom formatting.
TABLE 6.3 Combobox Formatting Functions
Format Function
Number AFNumber_Format
Percentage AFPercent_Format
Date AFDate_FormatEx
Time AFTi me_Format
Special AFSpeci al Format
Acrobat JavaScript Scripting Guide 99
Using Acrobat JavaScript in Forms
Forms Essentials
6
Listbox Properties
A list box has many of the same properties as buttons and combo boxes, except for the fact
that the user may not enter custom text and, consequently, that spellchecking is not
available.
However, the user may select multiple entries. To enable this feature, set its
mul ti pl eSel ecti onproperty to true, as shown in the code below:
f . mul t i pl eSel ect i on = t r ue;
To set up an action associated with a selected item, invoke its setActi onmethod and
pass in the"Keystroke" trigger name as the first parameter, as shown in the code below:
f . set Act i on( "Keyst r oke", "myLi st boxJ avascr i pt ( ) ; " ) ;
Radio Button Properties
The unique nature of radio buttons is that they are always created in sets, and represent a
collection of mutually exclusive choices. This means that when you create a set of radio
buttons, you must give all of them identical names and access them with zero-based
numeric indices, as you learned earlier in Creating Acrobat Form Fields.
Radio buttons have many of the same properties as buttons and check boxes.
Signature Properties
Signature fields have many of the same properties as buttons. You may set the action of a
signature field by invoking its setActi onmethod and passing in the "Format" trigger
name as the first parameter. When the user signs the form, you may reformat other form
fields with the script you pass into the setActi onmethod.
Once a document is signed, you may wish to lock certain form fields within the document.
You may do so by creating a script containing a call to the signature fields setLock
method and passing that script as the second parameter to the signature fields
setActi on method.
The setLock method requires a Lock object, which you will obtain by invoking the form
fields getLock method. Once you obtain the Lock object, set its acti onand fi el ds
properties. The acti onproperty can be set to one of 3 values: "Al l " (lock all fields),
"excl ude" (lock all fields except for these), or "i ncl ude" (lock only these fields). The
fi el ds property is an array of fields.
For example, suppose you created a signature and would like to lock the form field whose
name is myFi el dafter the user signs the document. The following code would lock
myFi el d:
var oLock = f . get Lock( ) ;
oLock. act i on = "i ncl ude";
oLock. f i el ds = new Ar r ay( "myFi el d") ;
f . set Lock( oLock) ;
To actually sign a document, you must do two things: choose a security handler, and then
invoke the signature fields si gnatureSi gnmethod. The following code is an example of
how to choose a handler and actually sign the document:
Using Acrobat JavaScript in Forms
Forms Essentials
6
100 Acrobat JavaScript Scripting Guide
var ppkl i t e = secur i t y. get Handl er ( "Adobe. PPKLi t e") ;
var oPar ams = {
passwor d: "myPasswor d",
cDI Pat h: "/ C/ si gnat ur es/ myName. pf x" / / di gi t al si gnat ur e pr of i l e
};
ppkl i t e. l ogi n( oPar ams) ;
f . si gnat ur eSi gn( ppkl i t e,
{
passwor d: "myPasswor d",
l ocat i on: "San J ose, CA",
r eason: "I amappr ovi ng t hi s document ",
cont act I nf o: "user Name@adobe. com",
appear ance: "Fancy"
}
) ; / / end of si gnat ur e
Text Field Properties
The text field has many of the same properties as buttons and combo boxes. In addition, it
offers the following specialized properties shown below in Table 6.4:
TABLE 6.4 Text Field Formatting
Property Description Example
al i gnment justify text f . al i gnment = "cent er ";
defaul tVal ue set a default text string f . def aul t Val ue = "Name: ";
mul ti l i ne allow multiple lines in the
area
f . mul t i l i ne = t r ue;
doNotScrol l permit scrolling of long text f . doNot Scr ol l = t r ue;
ri chText set rich text formatting f . r i chText = t r ue;
charLi mi t limit on number of
characters in area
f . char Li mi t = 40;
password use special formatting to
protect the users password
f . passwor d = t r ue;
fi l eSel ect format field as a file
pathname
f . f i l eSel ect = t r ue;
doNotSpel l Check set spell checking f . doNot Spel l Check = t r ue;
comb comb of characters subject
to limitation set by
charLi mi t
f . comb = t r ue;
Acrobat JavaScript Scripting Guide 101
Using Acrobat JavaScript in Forms
Forms Essentials
6
Validation Options
You may use validation to enforce valid ranges, values, or characters entered in form fields.
The main reason to use validation is to ensure that users are only permitted to enter valid
data into a form field.
To apply validation to a field action, invoke the fields setActi onmethod, and pass
"Val i date" as the first parameter and a script containing a call to
AFRange_Val i dateas the second parameter. The function AFRange_Val i dateis
located in J avascr i pt s\ af or m. j s, and requires 4 parameters: bGreaterThan(boolean
value), nGreaterThan(first value in the range), bLessThan(boolean value), and
nLessThan(last value in the range).
For example, the following code ensures that all values entered in the form field are from 0
to 100, inclusive:
f . set Act i on(
"Val i dat e",
AFRange_Val i dat e( t r ue, 0, t r ue, 100)
) ;
Calculation Options
Calculation options make it possible to automate mathematical calculations associated
with form fields. To apply a calculation to a form field action, invoke the form fields
setActi onmethod, pass "Cal cul ate" as the first parameter, and pass a script
containing a call to a calculation script as the second parameter.
If you would like to perform simple calculations on an array of form field values, you may
use a convenient script already written for you called AFSi mpl e_Cal cul atein the
second parameter. The function AFSi mpl e_Cal cul ateis located in
J avascr i pt s\ af or m. j s, and requires 2 parameters: cFuncti on(the type of calculation
to be performed) and cFi el ds (a field list that may be separated by commas or spaces, or
may be an array). The first parameter specifies the type of calculation, which may be a sum
("SUM"), product ("PRD"), average ("AVG"), minimum ("MI N"), or maximum ("MAX").
For example, the following code calculates the sum of the values entered into two text
areas on a form:
var ar r = new Ar r ay( "l i ne. 1", "l i ne. 2") ;
f . set Act i on(
"Cal cul at e",
AFSi mpl e_Cal cul at e( "SUM", ar r )
) ;
Using Acrobat JavaScript in Forms
Forms Essentials
6
102 Acrobat JavaScript Scripting Guide
Highlighting Required Form Fields
Some text fields on a form may not be left blank: these are called required form fields. It is
helpful to the user to highlight them so that they can be easily recognized. To do this,
create a Highlight annotation as shown in the following example:
t hi s. addAnnot ( {
page: 2,
st r okeCol or : col or . yel l ow,
t ype: "Hi ghl i ght ",
quads: t hi s. get PageNt hWor dQuads( 2, 3) ,
}) ;
Alerting Users Automatically for Required Form Fields
A user action such as clicking a Submit button or leaving a page could trigger validation
scripts detecting either bad input or blank form fields that alert the user to the fact that
some required form fields require their attention.
For example, suppose the user has forgotten to fill in the text field myText and has clicked
the Submit button. The following script would alert the user to the problem, and could be
followed with code that highlights the text:
app. al er t ( "You f or got t he f i el d shown i n yel l ow. ") ;
Making a Form Fillable
In order for a form to be fillable, its text fields or combo boxes must be formatted so that
the user can edit them.
Enabling Typing
If you would like a text area to be enabled for typing, set its readonl y property to fal se,
as shown in the following code:
f . r eadonl y = f al se;
If you would like a combo box to be enabled for typing, set its edi tabl eproperty to
true, as shown in the following code:
f . edi t abl e = t r ue;
Acrobat JavaScript Scripting Guide 103
Using Acrobat JavaScript in Forms
Forms Essentials
6
Setting the Hierarchy of Form Fields
The hierarchy of form fields is determined according to a naming strategy that uses "dot"
notation. For example, suppose you have 4 radio buttons that all belong to the same group.
The group could be named myGroup. The 4 radio buttons would then be named
myGroup. 0, myGroup. 1, myGroup. 2, and myGroup. 3. The convenience of this
naming system becomes most apparent when you decide that all members of the group
should have the same property characteristics. For example, to set the glyph style of all 4
radio buttons, you can do this with one line of code as shown below:
var f = t hi s. get Fi el d( "myGr oup") ;
f . st yl e = st yl e. ch; / / gl yph st yl e f or al l r adi o but t ons
This notation is certainly more convenient than typing in 4 nearly identical lines of code.
Suppose that you have 3 different groups, each of which has several radio buttons. You can
extend the hierarchical naming to this situation as well. Suppose that you would like to be
able to assign common property values to all 3 groups. To do this, you could create a parent
name for all the groups, such as mySet. The 3 groups would be named mySet. 0,
mySet. 1, and mySet. 2. Suppose the first group, mySet. 0, has 2 radio buttons in it.
They would be named mySet. 0. 0and mySet. 0. 1. To set the glyph style for all 3 groups
of radio buttons, you can do this, again, with just a single line of code as shown below:
var f = t hi s. get Fi el d( "mySet ") ;
f . st yl e = st yl e. ch; / / gl yph st yl e f or al l 3 gr oups
You can also differentiate the groups within the hierarchy. Suppose you would like to
designate a yellow background color for the third set. You could do so with the following
statements:
var f = t hi s. get Fi el d( "mySet . 2") ;
f . f i l l Col or = col or . yel l ow; / / af f ect s onl y t he 3r d gr oup
Creating Forms From Scratch
Positioning Form Form Fields
Remember that form field positioning takes place in Rotated User Space, in which the origin
of a page is located at the bottom left corner. This differs from Info Space and may require
that you occasionally perform transformations.
For example, suppose that you use the Info panel to obtain the coordinates of a given
rectangle. Use the doc objects getPageBox method to obtain the coordinates in Rotated
User Space for the page, and then subtract the Info Space y-coordinates from the page
height provided by the getPageBox method.
Using Acrobat JavaScript in Forms
Forms Essentials
6
104 Acrobat JavaScript Scripting Guide
If you are accustomed to calculating the positions of form fields from the top left corner of a
page, the following example will serve as a template for obtaining the correct position. In
this example, we will position a 1 inch by 2 inch form field 0.5 inches from the top of the
page and 1 inch from the left side:
/ / 1 i nch = 72 poi nt s
var i nch = 72;
/ / obt ai n t he page coor di nat es i n Rot at ed User Space
var aRect = t hi s. get PageBox( {nPage: 2}) ;
/ / posi t i on t he t op l ef t cor ner 1 i nch f r omt he l ef t si de
aRect [ 0] += 1 * i nch;
/ / make t he r ect angl e 1 i nch wi de
aRect [ 2] = aRect [ 0] + 1*i nch;
/ / t op l ef t cor ner i s 0. 5 i nch down f r omt he t op of t he page
aRect [ 1] - = 0. 5*i nch;
/ / make t he r ect angl e 2 i nches t al l
aRect [ 3] = aRect [ 1] - 2*i nch;
/ / dr aw t he but t on
var f = t hi s. addFi el d( "myBut t on", "but t on", 2, aRect ) ;
Duplicating Form Fields
It may sometimes be useful to duplicate information typed in by the user in other pages of
the document. For example, you might wish to display the users name on every page of
the document.
To automate this, give all such form fields the same name and actions. Then whenever the
user triggers a related action, the same information appears in all form fields containing
that name.
To duplicate form fields in general, assign the same name and actions to each of them. In
the example below, we will create duplicate text fields, each named myFi el d, on page 2 of
the document, and we will set the background color of every instance to yellow:
f or ( var i = 0; i < 5; p++)
{
var aRect = [ 36, 36+100*i , 72, 144+100*i ] ;
var f = t hi s. addFi el d( "myFi el d", "t ext ", 2, aRect ) ;
f . f i l l Col or = yel l ow;
}
Acrobat JavaScript Scripting Guide 105
Using Acrobat JavaScript in Forms
Forms Essentials
6
Creating Multiple Form Fields
The best approach to creating a row, column, or grid of form fields is to use array notation
in combination with hierarchical naming.
For example, the following code creates a column of 3 text fields:
var myCol umn = new Ar r ay( 3) ;
myCol umn[ 0] = "myFi el dCol . name";
myCol umn[ 1] = "myFi el dCol . bi r t hday";
myCol umn[ 2] = "myFi el dCol . ssn";
var aRect = [ 36, 36, 72, 144] ;
f or ( var i =0; i <myCol umn. l engt h; i ++)
{
aRect [ 1] += 100; / / move t he next f i el d down 100 poi nt s
aRect [ 3] += 100; / / move t he next f i el d down 100 poi nt s
var f = t hi s. addFi el d( myCol umn[ i ] , "t ext ", 0, aRect ) ;
Creating Form Fields That Span Multiple Pages
From a programmatic standpoint, duplicating form fields across multiple pages requires
the same steps as duplicating form fields in general (see Duplicating Form Fields). The only
difference is specifying the page number.
To duplicate form fields in general, assign the same name and actions to each of them. In
the example below, we will create duplicate text fields, each named myFi el d, on every
page of the document, and we will set the background color of every instance to yellow:
f or ( var p = 0; p < t hi s. numPages; p++)
{
var aRect = [ 36, 36, 72, 144] ;
var f = t hi s. addFi el d( " myFi el d" , " t ext " , p, aRect ) ;
f . f i l l Col or = yel l ow;
}
Defining the Tabbing Order
You may specify the tabbing order on a given page by invoking the doc objects
setPageTabOrder method, which requires two parameters: the page number and the
order to be used.
There are three options for tabbing order: you may specify tabbing by rows ("rows"),
columns ("col umns"), or document structure ("structure").
For example, the following code sets up tabbing by rows for page 2 of the document:
t hi s. set PageTabOr der ( 2, " r ows" ) ;
Using Acrobat JavaScript in Forms
Forms Essentials
6
106 Acrobat JavaScript Scripting Guide
Defining Form Field Calculation Order
When you add a text field or combo box that has a calculation script to a document, the
new form fields name is appended to the calculation order array. When a calculation event
occurs, the calculation script for each of the form fields in the array runs, beginning with the
first element in the array (array index 0) and continuing in sequence to the end of the array.
If you would like one form field to have calculation precedence over another, you can
change its calculation index, accessed through the fi el dobjects cal cOrderI ndex
property. A form field script with a lower calculation index executes first. The following
code guarantees that the calculation script for form field awill run before the one for form
field b:
b. cal cOr der I ndex = a. cal cOr der I ndex + 1;
Acrobat JavaScript Scripting Guide 107
Using Acrobat JavaScript in Forms
Forms Essentials
6
Making PDF Forms Web-Ready
PDF forms can be used in workflows that require the exchange of information over the
Web. You can create forms that run in Web browsers, and can submit and retrieve
information between the client and server by making a Submit button available in the
form. The button can perform similar tasks to those of HTML scripting macros.
You will need a CGI application on the Web server that can facilitate the exchange of your
forms information with a database. The CGI application must be able to retrieve
information from forms in HTML, FDF, or XML formats.
In order to enable your PDF forms for data exchange over the Web, be sure to name your
form fields so that they match those in the CGI application. In addition, be sure to specify
the export values for radio buttons and check boxes.
The client side form data may be posted to the server using the HTML, FDF, XFDF, or PDF
formats. Note that the use of XFDF format results in the submission of XML-formatted data
to the server, which will need an XML parser or library to read the XFDF data. The
equivalent MIME types for all posted form data are shown below in Table 6.5.
Creating Submit Buttons
When you use the Button tool, use the MouseUptrigger and select Submit a Form. You
may specify which data format is used when you select the Export Format option. If it is
necessary for the server to be able to recognize and reconstruct a digital signature, it is
advisable that you choose the Incremental Changes to the PDF option.
Creating Reset Form Buttons
In this case, when you create the MouseUptrigger, select Reset a Form. Now you will be
able to specify which form fields are reset.
Creating Import Data Buttons
First set up an FDF file with common data. In this case, when you create the MouseUp
trigger, select Import Form Data.
TABLE 6.5 MIME Types for Data Formats
Data Format MIME Type
HTML application/x-www-form-urlencoded
FDF application/vnd.fdf
XFDF application/vnd.adobe.xfdf
PDF application/pdf
XML application/xml
Using Acrobat JavaScript in Forms
Forms Essentials
6
108 Acrobat JavaScript Scripting Guide
Defining CGI Export Values
If you are storing the form data in a database and the data is either different from the item
designated by the form field (such as those in combo boxes or list boxes) or the form field is
a radio button or check box (all of which must have different export values), then you will
need to define CGI export values, which represents identifying information about the form
field to the CGI application.
Using Custom JavaScripts in Forms
The most common uses for Acrobat JavaScript in enhancing the interactive behavior of
forms are in formatting, calculating, and validating data. In addition, you may write custom
scripts for different types of mouse actions, as well as database connectivity.
Introduction to XML Forms Architecture (XFA)
The XML Forms Architecture (XFA) is an XML-based architecture which supports the
production of business form documents through the use of templates based on the XML
language. Its features address a variety of workflow needs including dynamic reflow,
dynamic actions based on user interaction or automated server events, headers, footers,
and complex representations of forms capable of large-scale data processing.
XFA can be understood in terms of two major components: templates and content. The
templates define presentation, calculation, and interaction rules, and are based on XML.
Content is the static or dynamic data, stored in the document, that is bound to the
templates.
Dynamic XFA indicates that the content will be defined later after binding to a template.
This also means that the following is possible:
Form fields may be moved or resized.
Form fields automatically grow or shrink according to the amount of text added or
removed.
As a form field grows, it can span multiple pages.
Repeating subforms may be spawned as needed, and page contents shift accordingly.
Elements on the page are shown or hidden as needed.
To take advantage of the rich forms functionality offered by the XFA plug-in, use Adobe
LiveCycle Designer

to create or edit the templates and save your forms in the XML Data
Package format (XDP) or as a PDF document. Use XDP if the data is processed by server
applications, and PDF if the data is processed by Acrobat.
Acrobat JavaScript Scripting Guide 109
Using Acrobat JavaScript in Forms
Forms Essentials
6
Enabling Dynamic Layout and Rendering
In order to enable dynamic layout and rendering for a form, save it from LiveCycle Designer
as a "Dynamic PDF Form File".
Growable Form Fields
The elements, which include Fields, Subforms, Areas, Content Areas, and Exclusion Groups,
expand to fit the data they contain. They may relocate in response to changes in the
location or extent of their containing elements, or if they flow together with other elements
in the same container.
If the element reaches the nominal content region of the containing page, then it splits so
that it may be contained across both pages.
Variable-Size Rows and Tables
Subforms may repeat to accommodate incoming data. For example, when importing a
variable number of subforms containing entries for name, address, and telephone number,
form fields need to be added or removed based on the volume of data. This means that the
number of rows in a table may increase.
Multiple Customized Forms within a Form Based on User Input
Subforms may also be subject to conditions. For example, form fields for dependent
children would become visible if the user checks a box indicating that there are dependent
children. In addition, XFA allows multiple form fields with the same name and multiple
copies of the same form.
Handling Image Data
Images are handled as data and are considered to have their own field type. There is
automatic support for browsing images in all standard raster image formats (including
PNG, GIF, TIFF, and JPEG).
Dynamic Tooltips
XFA forms support dynamic tooltips, including support for individual radio buttons in a
group.
XFA-Specific JavaScript Methods
Acrobat JavaScript provides access to the XFA appModel container, which provides the
properties and methods indicated below in Table 6.6 and Table 6.7.
TABLE 6.6 appModel Properties
appModel Property Description
al i asNode The node represented by the alias for this model
al l Returns all nodes with the same name or class
appModel Name Returns xfa
Using Acrobat JavaScript in Forms
Forms Essentials
6
110 Acrobat JavaScript Scripting Guide
cl assAl l Returns all nodes with the same class name
cl assI ndex Returns the position of this node in the collection of
nodes having the same class name
cl assName Returns the class name of the object
context The current node (needed for resolveNode and
resolveNodes)
i d The ID of the current node
i ndex Returns the position of this node in the collection of
nodes having the same name
i sContai ner Returns true if this is a container object
i sNul l Returns true if the node has a null value
model Returns the XFA model for this node
name The name of this node
nodes A list of child nodes for this node
ns The namespace for this node (or XFAModel)
oneOfChi l d Retrieves or sets the child that has the XFA::oneOfChild
relationship to its parent
parent Retrieves the parent of this node
somExpressi on Retrieves the SOM expression for this node
thi s Retrieves the current node (starting node for
resolveNode and resolveNodes)
TABLE 6.6 appModel Properties
appModel Property Description
Acrobat JavaScript Scripting Guide 111
Using Acrobat JavaScript in Forms
Forms Essentials
6
TABLE 6.7 XFA appModel Methods
appModel Method Description
appl yXSL Performs an XSL transformation of the current node
assi gnNode Sets the value of the node, and creates one if necessary
cl earErrorLi st Clears the current list of errors
cl one Clones a node (and its subtree if specified)
createNode Creates a new XFA node based on a valid classname
getAttri bute Retrieves a specified attribute value
getEl ement Retrieves a specified property element
i sCompati bl eNS Determines if two namespaces are equivalent
i sPropertySpeci f i ed Checks if a specific property has been defined for the
node
l oadXML Loads and appends the current XML document to the
node
resol veNode Obtains the node corresponding to the SOM
expression
resol veNodes Obtains the XFATreeList corresponding to the SOM
expression
saveXML Saves the current node to a string
setAttri bute Sets a specified attribute value
setEl ement Sets a specified property element
Using Acrobat JavaScript in Forms
Forms Essentials
6
112 Acrobat JavaScript Scripting Guide
The XFA DOM model contains a root object that consists of either a treeLi st or a Tree.
A treeLi st consists of a list of nodes (which is why it is sometimes called a NodeLi st).
A Treeconsists of a hierarchical structure of nodes, each of which may contain content, a
model, or a textNode.
The following properties and methods are available in a treeLi st object:
Properties:
l ength
Methods:
append, i nsert, i tem, namedI tem, and remove.
The following properties and methods are available in a Treeobject:
Properties:
al l , cl assAl l , cl assI ndex, i ndex, name, nodes,
parent, somExpressi on
Methods:
resol veNode, resol veNodes
Each Nodeelement represents an element and its children in the XML DOM. To obtain a
string representation of the node, invoke its saveXML method. To apply an XSL transform
(XSLT) to the node and its children, invoke its appl yXSL method. The following properties
and methods are available in a Nodeobject:
Properties:
i d, i sContai ner, i sNul l , model , ns, oneOfChi l d
Methods:
appl yXSL, assi gnNode, cl one, getAttri bute, getEl ement,
i sPropertySpeci fi ed, l oadXML, saveXML, setAttri bute,
setEl ement
There are two approaches to accessing content in an XML stream. In the first approach, XFA
syntax may be used to manipulate the XML DOM. In the second approach, you may use
standard XPath syntax.
The Acrobat JavaScript XML object provides two methods useful for manipulating XML
documents: appl yXPathand parse.
The appl yXPathpermits the manipulation of an XML document via an XPath, and the
parsemethod creates an object representing an XML document tree. Both of these return
an XFAobject.
The first approach involves the usage of the XFL objects parsemethod for accessing and
manipulating XML streams. The second approach involves the usage of the XFL objects
appl yXPathmethod.
Both approaches are illustrated below.
Acrobat JavaScript Scripting Guide 113
Using Acrobat JavaScript in Forms
Forms Essentials
6
In this first example, the usage of the parsemethod is illustrated below:
/ / Cr eat e t he XML st r eam
var par seSt r i ng = "<pur chase>";
par seSt r i ng += "<pr oduct >";
par seSt r i ng += "<pr i ce>299. 00</ pr i ce>";
par seSt r i ng += "<name>i Pod</ name>";
par seSt r i ng += "</ pr oduct >";
par seSt r i ng += "<pr oduct >";
par seSt r i ng += "<pr i ce>49. 95</ pr i ce>";
par seSt r i ng += "<name>case</ name>";
par seSt r i ng += "</ pr oduct >";
par seSt r i ng += "</ pur chase>";
/ / Now cr eat e t he DOM:
var x = XML. par se( par seSt r i ng) ;
/ / Use t he XFA API t o obt ai n t he XFA t r ee l i st f or pr oduct s:
var pr oduct s = x. r esol veNodes( "pr oduct ") ;
/ / Obt ai n t he i Pod pr oduct :
var i Pod = pr oduct s. i t em( 0) ;
/ / Obt ai n t he i Pod pr i ce:
var pr i ce = i Pod. get El ement ( "pr i ce") . val ue;
/ / Conver t t he pr i ce t o a st r i ng:
var pr i ceSt r i ng = pr i ce. saveXML( ) ;
This next example accomplishes the same task through the usage of the appl yXPath
method:
/ / Cr eat e t he XML st r eam
var par seSt r i ng = "<pur chase>";
par seSt r i ng += "<pr oduct >";
par seSt r i ng += "<pr i ce>299. 00</ pr i ce>";
par seSt r i ng += "<name>i Pod</ name>";
par seSt r i ng += "</ pr oduct >";
par seSt r i ng += "<pr oduct >";
par seSt r i ng += "<pr i ce>49. 95</ pr i ce>";
par seSt r i ng += "<name>case</ name>";
par seSt r i ng += "</ pr oduct >";
par seSt r i ng += "</ pur chase>";
/ / Now cr eat e t he DOM:
var x = XMLDat a. par se( par seSt r i ng, f al se) ;
/ / Set up t he XPat h expr essi on:
var xPat hExpr = "/ / pur chase/ pr oduct / [ name=' i Pod' ] / pr i ce";
/ / Now get t he i Pod pr i ce:
var pr i ce = XMLDat a. appl yXPat h( x, xPat hExpr ) ;
Using Acrobat JavaScript in Forms
Filling in PDF Forms
6
114 Acrobat JavaScript Scripting Guide
JavaScript Methods Not Enabled in XML Forms
The following Acrobat JavaScript doc methods are not available from an XML form:
getFi el d
getNthFi el dName
addNewFi el d
addFi el d
removeFi el d
setPageTabOrder
ADO Support for Windows
It is now possible to access both individual and multiple records. Forms can be enabled
with ADO support for more direct database interaction.
Forms Migration: Working with Forms Created in Acrobat 6.0 or Earlier
Detecting XML Forms and Earlier Form Types
To determine whether a document is an XML form, invoke the doc objects
dynami cXFAFormmethod, which returns a boolean result. Note that an Acrobat form
does not have an xfaobject.
Filling in PDF Forms
Completing Form Fields
Completing Form Fields Automatically
In many cases, you may wish to assign a character limit to text fields. For example, when
collecting credit card or social security numbers, you may require that the number be split
across several text fields. For example, the social security number 555-55-5555 would
require three text fields of lengths 3, 2, and 4, respectively.
Spell-Checking Text in Forms
You can spell-check text typed in note comments and form fields, but not in the underlying
PDF document.
Acrobat JavaScript Scripting Guide 115
Using Acrobat JavaScript in Forms
Filling in PDF Forms
6
Importing and Exporting Form Data
Form data can be exported to a separate file, which can then be sent using email or over
the Web. When doing this, save either to Forms Data Format (FDF) or XML-based FDF
(XFDF). This creates an export file much smaller than the original PDF file.
When importing XFDF data, you will need an XML parser or library to read the XFDF data.
Note that Acrobat forms support the FDF, XFDF, tab-delimited text, and XML formats, and
that XML forms support XML and XDP formats.
Saving Form Data as XML or XML Data Package (XDP)
To save your form data in XML format, invoke the doc objects saveAs method using the
conversion ID for XML, as shown in the code below:
t hi s. saveAs( "myDoc. xml ", "com. adobe. acr obat . xml - 1- 00") ;
To take advantage of XFA functionality, you may save your forms in the XML Data Package
format (XDP). This simply requires the usage of the conversion ID for XDP, as shown in the
code below:
t hi s. saveAs( "myDoc. xml ", "com. adobe. acr obat . xdp") ;
Emailing Completed Forms
To email a completed form in FDF format, invoke the doc objects mai l Formmethod,
which exports the data to FDF and sends it via email.
To make an interactive email session, pass trueto the first parameter, which specifies
whether a user interface should be used, as shown in the code below:
t hi s. mai l For m( t r ue) ;
To send the exported FDF data automatically, pass fal seto the first parameter, and
specify the cTO, cCc, cBcc, cSubj ect, and cMsgfields (all of which are optional), as
shown in the code below:
t hi s. mai l For m( f al se, "r eci pi ent @adobe. com") ;
Global Submit
Suppose you have a document that contains multiple attachments, from which you would
like to compile information for submission to a server in XML format. You can create a
Global Submit button whose MouseUpaction contains a script that collects the data from
each of the attachments and creates a unified collection in XML format.
To do this, you will need to invoke the doc objects openDataObj ect method in order to
open the attachments, followed by its submi tFormmethod to upload the combined XML
data to the server.
Using Acrobat JavaScript in Forms
Filling in PDF Forms
6
116 Acrobat JavaScript Scripting Guide
The following example merges the data from several XML form attachments and submits it
to a server:
var oPar ent = event . t ar get ;
/ / Get t he l i st of at t achment s:
var oDat aObj ect s = oPar ent . dat aObj ect s;
i f ( oDat aObj ect s == nul l )
app. al er t ( "Thi s f or mhas no at t achment s! ") ;
el se {
/ / Cr eat e t he r oot node f or t he gl obal submi t :
var oSubmi t Dat a = oPar ent . xf a. dat aSet s. cr eat eNode(
"dat aGr oup",
"gl obal Submi t Root Node"
) ;
/ / I t er at e t hr ough al l t he at t achment s:
var nChi l dr en = oDat aObj ect s. l engt h;
f or ( var i Chi l d = 0; i Chi l d < nChi l dr en; i ++) {
/ / Open t he next at t achment :
var oNext Chi l d = oPar ent . openDat aObj ect (
oDat aObj ect s[ i Chi l d] . name
) ;
/ / Tr ansf er i t s dat a t o t he XML col l ect i on:
oSubmi t Dat a. nodes. append(
oNext Chi l d. xf a. dat a. nodes. i t em( 0)
) ;
cl ose t he at t achment / /
oNext Chi l d. cl oseDoc( ) ;
}
/ / Submi t t he XML dat a col l ect i on t o t he ser ver
oPar ent . submi t For m( {
cURL: "ht t p: / / t heser ver . com/ cgi - bi n/ t hescr i pt . cgi ",
cSubmi t As: "XML",
oXML: oSubmi t Dat a
}) ;
}
Acrobat JavaScript Scripting Guide 117
Using Acrobat JavaScript in Forms
Making Forms Accessible
6
Making Forms Accessible
Making a PDF Form accessible to users who have impaired motor or visual ability requires
that the document be structured, which means that PDF tags present in the document
ensure that the content is organized according to a logical structure tree. This means that
you will have added tags to the document. Once you do this, you may specify alternative
text within the tags.
You can make forms accessible through the use of Text-To-Speech engines and tagged
annotations containing alternative text.
Text-To-Speech engines can translate structured text in a PDF document into audible
sound, and tagged annotations containing alternative text can provide substitute content
for graphical representations, which cannot be read by a screen reader. It is useful to
consider embedding alternative text in links and bookmarks, as well as specifying the
language of the document.
It is not necessary to sacrifice security in order to make a document accessible. Select
Document Properties > Security > Enable Text Access for Screen Reader Devices for
the Visually Impaired.
Text-To-Speech
In order for Text-To-Speech engines to be able to work with your document, it must be
structured. You can create structured documents using Adobe FrameMaker

7.0 or Adobe
FrameMaker SGML 6.0 running in Structured mode.
To access the Text-To-Speech engine from Acrobat JavaScript, use the TTS object, which
has methods to render text as digital audio and present it in spoken form to the user.
For example, the following code displays a message stating whether the TTS engine is
available:
consol e. pr i nt l n( "TTS avai l abl e: " + t t s. avai l abl e) ;
The next code sample illustrates how to enumerate through all available speakers, queue a
greeting into the TTS object for each one, and present the digital audio version of it to the
user:
f or ( var i =0; i <t t s. numSpeaker s; i ++) {
var cSpeaker = t t s. get Nt hSpeaker Name( i ) ;
consol e. pr i nt l n( "Speaker [ " + i + "] = " + cSpeaker ) ;
t t s. speaker = cSpeaker ;
t t s. qText ( "Hel l o") ;
t t s. t al k( ) ;
}
Using Acrobat JavaScript in Forms
Making Forms Accessible
6
118 Acrobat JavaScript Scripting Guide
The properties and methods of the TTSobject are summarized below in Table 6.8 and
Table 6.9.
TABLE 6.8 TTS Properties
Property Description
avai l abl e Returns trueif the Text-To-Speech engine is available
numSpeakers Returns the number of speakers in the engine
pi tch The baseline pitch between 0 and 10
speaker A speaker with desired tone quality
speechRate The rate in words per minute
vol ume The volume between 0 and 10
Acrobat JavaScript Scripting Guide 119
Using Acrobat JavaScript in Forms
Using JavaScript to Secure Forms
6
Tagging Annotations
Tagged files provide the greatest degree of accessibility, and are associated with a logical
structure tree that supports the content. Annotations can be dynamically associated with a
new structure tree that is separate from the original content of the document, thus
supporting accessibility without modifying the original content. The annotation types
supported for accessibility are:
Text, FreeText, Line, Square, Circle, Polygon, Polyline, Highlight,
Underline, Squiggly, Strikeout, Stamp, Caret, Ink, Popup, FileAttachment, Sound
To add an accessible tag, select Advanced > Accessibility and choose Add Tags to
Document.
Using JavaScript to Secure Forms
As you learned earlier in Signature Properties, you can lock any form fields you deem
appropriate once a document has been signed. In addition, you may also encrypt a
document.
Acrobat JavaScript provides a number of objects that support security. These are managed
by the securi ty and securi tyHander objects for building certificates and signatures,
as well as the certi fi cate, di rectory, si gnatureI nfo, and di rConnecti on
objects which are used to access the user certificates. (The certi fi cateobject provides
read-only access to an X.509 public key certificate).
TABLE 6.9 TTS Methods
Method Description
getNthSpeakerName Retrieves Nth speaker in current Text-To-Speech engine
pause Pauses the audio output
qSi l ence Queues a period of silence into the text
qSound Inserts a sound cue using a .wav file
qText Inserts text into the queue
reset Stops playback, flush the queue, reset all Text-To-Speech
properties
resume Resumes playback on a paused TTSobject
stop Stops playback and flush the queue
tal k Sends queue contents to Text-To-Speech engine
Using Acrobat JavaScript in Forms
Using JavaScript to Secure Forms
6
120 Acrobat JavaScript Scripting Guide
These objects, in combination, provide you with the means to digitally sign or encrypt a
document. Once you have built a list of authorized recipients, you may then encrypt the
document using the doc objects encryptForReci pi ents method, save the
document to commit the encryption, and email it to them.
For example, you can obtain a list of recipients for which the encrypted document is
available, and then encrypt the document:
/ / I nvoke t he r eci pi ent s di al og t o sel ect whi ch r eci pi ent s
/ / wi l l be aut hor i zed t o vi ew t he encr ypt ed document :
var oOpt i ons = {
bAl l owPer mGr oups: f al se,
cNot e: "Reci pi ent s wi t h emai l and cer t i f i cat es",
bRequi r eEmai l : t r ue,
bUser Cer t : t r ue
};
var oGr oups = secur i t y. chooseReci pi ent sDi al og( oOpt i ons) ;
/ / Bui l d t he mai l i ng l i st
var numCer t s = oGr oups[ 0] . user Ent i t i es. l engt h;
var cMsg = "Encr ypt ed f or t hese r eci pi ent s: \ n";
var mai l Li st = new Ar r ay;
f or ( var i =0; i <numCer t s; i ++) {
var ue = oGr oups[ 0] . user Ent i t i es[ i ] ;
var oCer t = ue. def aul t Encr ypt Cer t ;
i f ( oCer t == nul l ) oCer t = ue. cer t i f i cat es[ 0] ;
cMsg += oCer t . subj ect CN + ", " + ue. emai l + "\ n";
var oRDN = oCer t . subj ect DN;
i f ( ue. emai l ) mai l Li st [ i ] = ue. emai l ;
el se i f ( oRDN. e) mai l Li st [ i ] = oRDN. e;
}
/ / Now encr ypt t he document
t hi s. encr ypt For Reci pi ent s( oGr oups) ;
Acrobat JavaScript Scripting Guide 121
Using Acrobat JavaScript in Forms
Using JavaScript to Secure Forms
6
The securi ty objects properties and methods are described below in Table 6.10 and
Table 6.11.
TABLE 6.10 Security Properties
Property Description
handl ers Returns an array of security handler names
val i dateSi gnaturesOnOpen User preference to be automatically validated
when document opens
TABLE 6.11 Security Methods
Method Description
chooseReci pi entsDi al og Opens a dialog to choose a list of recipients
getHandl er Obtains a security handler object
exportToFi l e Saves a Certi fi cateobject to a local disk
i mportFromFi l e Reads in a Certi fi cateobject from a local disk
Using Acrobat JavaScript in Forms
Using JavaScript to Secure Forms
6
122 Acrobat JavaScript Scripting Guide
Acrobat JavaScript Scripting Guide 123
7
Review, Markup, and Approval
Introduction
In this chapter you will learn how to make use of Acrobats ability to facilitate online
collaborative reviews for many types of content. At the heart of this process is the set of
commenting, markup, and approval tools available to the reviewers, and the tools available
to the initiator for managing the review.
You will be able to use Acrobat JavaScript features to customize the review process and
how comments are handled, add additional annotations, and configure a SOAP-based
online repository.
Chapter Goals
At the end of this chapter, you will be able to:
Specify the different types of review workflows.
Initiate a document review.
Participate in a document review.
Use the commenting, markup, and approval tools.
Manage comments.
Contents
Topics
Online Collaboration Essentials
Using Commenting Tools
Managing Comments
Approving Documents Using Stamps (Japanese Workflows)
Review, Markup, and Approval
Online Collaboration Essentials
7
124 Acrobat JavaScript Scripting Guide
Online Collaboration Essentials
Introduction
You may initiate several types of review workflows for PDF documents:
Email the document to all reviewers, and import the returned comments into the
original document.
Set up an automated email-based review.
Set up an automated browser-based review through the use of a shared server.
Initiate an email-based approval workflow.
Initiate an Acrobat JavaScript-based review.
Reviewing Documents with Additional Usage Rights
For email-based reviews, the specification of additional usage rights within a document
enables extra capabilities within Adobe Reader. This enables the reviewer to add
comments, import and export form-related content, save the document, or apply a digital
signature.
For example, when using the doc objects encryptForReci pi ents method, you may
specify the following permissions for reviewers:
al l owAl l : permits full and unrestricted access to the entire document.
al l owAccessi bi l i ty: permits content accessed for readers with visual or motor
impairments.
al l owContentExtracti on: permits content copying and extraction.
al l owChanges: permits either no changes, or changes to part or all of the document
assembly, content, forms, signatures, and notes.
al l owPri nti ng: permits no printing, low-quality printing, or high-quality printing.
Online Collaboration Essentials Topics
Reviewing Documents with Additional Usage Rights
Emailing PDF Documents
Acrobat JavaScript-based Collaboration Driver
Acrobat JavaScript Scripting Guide 125
Review, Markup, and Approval
Online Collaboration Essentials
7
The following code allows full and unrestricted access to the entire document for one set of
users (i mportantUsers), and allows high quality printing for another set of users
(otherUsers):
var sh = secur i t y. get Handl er ( "Adobe. PPKMS") ;
var di r = sh. di r ect or i es[ 0] ;
var dc = di r . connect ( ) ;
dc. set Out put Fi el ds( {oFi el ds: [ "cer t i f i cat es"] }) ;
var i mpor t ant User s = dc. sear ch( {oPar ams: {l ast Name: "Smi t h"}}) ;
var ot her User s = dc. sear ch( {oPar ams: {l ast Name: "J ones"}}) ;
t hi s. encr ypt For Reci pi ent s( {
oGr oups: [
{
oCer t s: i mpor t ant User s,
oPer mi ssi ons: { al l owAl l : t r ue }
},
{
oCer t s: ot her User s,
oPer mi ssi ons: { al l owPr i nt i ng: "hi ghQual i t y" }
}
] ,
bMet aDat a: t r ue
}) ;
Emailing PDF Documents
In addition to the Email options available in the Acrobat menu and toolbar, it is also
possible to use Acrobat JavaScript to set up an automated email review workflow. This may
be done through the doc objects mai l Doc method. In the code shown below, the
document is automatically sent to [email protected]:
t hi s. mai l Doc(
f al se,
"r eci pi ent @adobe. com", "", "",
"Revi ew",
"Pl ease r evi ew t hi s document and r et ur n. Thank you. "
) ;
NOTE: For Windows systems, the default mail program must be MAPI-enabled.
Review, Markup, and Approval
Online Collaboration Essentials
7
126 Acrobat JavaScript Scripting Guide
Acrobat JavaScript-based Collaboration Driver
Acrobat JavaScript can be used to describe the workflow for a given document review, and
can be used in review management. This is done by specifying a state model for the types
of annotations a reviewer may use and creating an annotation store on the server for
customized comment and review within browser-based workflows. The Col l abobject
provides you with control over the possible states annot objects may have, and may be
used in conjunction with the SOAPobject to create an annotation store.
There are several methods available within the Dol l abobject that enable you to describe
the state model for the review: these include addStateModel , getStateI nModel ,
transi ti onToState, and removeStateModel .
The addStateModel method is used to add a new state model to Acrobat describing the
possible states for an annot object using the model, and the removeStateModel
method removes the model, though it does not affect previously created annot objects.
Their usage is shown in the code below:
/ / Add a st at e model
t r y{
var mySt at es = new Obj ect ;
mySt at es[ "i ni t i al "] = {cUI Name: "Haven t r evi ewed i t "};
mySt at es[ "appr oved"] = {cUI Name: "I appr ove"};
mySt at es[ "r ej ect ed"] = {cUI Name: "For get i t "};
mySt at es[ "r esubmi t "] = {cUI Name: "Make some changes"};
Col l ab. addSt at eModel ( {
cName: "Revi ewSt at es",
cUI Name: "My Revi ew",
oSt at es: mySt at es,
cDef aul t : "i ni t i al "
}) ;
/ / Now t r ansi t i on myAnnot t o t he "appr oved" st at e:
myAnnot . t r ansi t i onToSt at e( "Revi ewSt at es", "appr oved") ;
}
cat ch( e) {consol e. pr i nt l n( e) ; }
/ / Now r emove t he st at e model
t r y {Col l ab. r emoveSt at eModel ( "Revi ewSt at es") ; }
cat ch( e) {consol e. pr i nt l n( e) ; }
Acrobat JavaScript Scripting Guide 127
Review, Markup, and Approval
Online Collaboration Essentials
7
You may also use the SOAPobjects connect, request, and responsemethods to
create customized commenting and review within browser-based workflows. You can do
this by setting up a SOAP-based annotation store on the server using the Col l abobjects
addAnnotStoreand setStoreSetti ngs methods.
The Col l abobjects addAnnotStoremethod requires three parameters:
cI ntName: The internal name for the annotation store.
cDi spName: The display name for the annotation store.
cStore: The definition for the new Col l abstore class.
The new Col l abstore class must contain the following definitions for the functions used
to add, delete, update, and enumerate through the array of annotations:
enumerate: Communicates with the Web service to request the array of annotations
stored on the server. It is used when the PDF document is loaded for online review, or
when the user clicks Upload or Send on the Commenting Toolbar.
compl ete: Passes the annotation data to the collaboration server so that it can be
updated.
update: Uploads new and modified annotations to the server.
The class SDKSampl eSOAPAnnotStore, as shown in the sample code below, is defined
in sdkSOAPCol l abSampl e. j s in the Acrobat SDK, and contains complete definitions of the
three functions described above.
The sample code below provides a standard example of how to use the SOAPand Col l ab
objects to customize your online collaborative review. Note that all of the reviewers must
have a copy of the JavaScript collaboration store code. In Acrobat 7.0, the Custom
collaboration store type allows you to put the JavaScript on the server. The store type used
is CUSTOM, and the setting is a URL to the JavaScript file:
/ / Her e i s t he URL f or a SOAP HTTP ser vi ce:
var mySet t i ng = "ht t p: / / sampl eSi t e/ comment s. asmx?WSDL";
/ / Her e i s t he i nt er nal name f or t he col l abor at i ve st or e:
var myType = "mySOAPCol l abSampl e";
/ / Set t he connect i on set t i ngs f or t he SOAP col l ab st or e:
Col l ab. set St or eSet t i ngs( mySet t i ng, myType) ;
/ / Set t he def aul t col l ab st or e:
Col l ab. def aul t St or e = myType;
Review, Markup, and Approval
Using Commenting Tools
7
128 Acrobat JavaScript Scripting Guide
/ / Add t he col l ab st or e t o t he Acr obat Col l ab ser ver s:
i f ( t ypeof SOAPFi l eSys == "undef i ned")
Col l ab. addAnnot St or e(
myType,
"SOAP Sampl e",
{
/ / Annot st or e i nst ant i at i on f unct i on i s r equi r ed:
cr eat e: f unct i on( doc, user , set t i ngs)
{
i f ( set t i ngs && set t i ngs ! = "")
r et ur n new SDKSampl eSOAPAnnot St or e(
doc, user , set t i ngs
) ;
el se
r et ur n nul l ;
}
}
) ;
Using Commenting Tools
The Commenting and Advanced Commenting toolbars provide reviewers with the tools
necessary to create comments, which may be placed in the document in the form of notes,
highlighting, and other markup.
Topics
Adding Note Comments
Making Text Edits
Highlighting, Crossing Out, and Underlining Text
Adding and Deleting Custom Stamps
Adding Comments in a Text Box
Adding Attachments
Spell-checking in Comments and Forms
Adding Commenting Preferences
Changing Colors, Icons, and Other Comment Properties
Adding Watermarks
Approval
Acrobat JavaScript Scripting Guide 129
Review, Markup, and Approval
Using Commenting Tools
7
Adding Note Comments
The Acrobat JavaScript support for note comments is available through the annot objects
Text and FreeText types.
Making Text Edits
Text edit comments, also known as markup, are used to indicate text that should either be
removed or inserted. Text that should be removed appears to be crossed out, and text that
should be inserted appears in a popup window triggered by a caret appearing within the
text. The Acrobat JavaScript support for text edits is available through the annot objects
Text and Stri keOut types.
Highlighting, Crossing Out, and Underlining Text
The Acrobat JavaScript support for highlighting, crossing out, and underlining text is
available through the annot objects Hi ghLi ght, Stri keOut, and Underl i netypes.
Adding and Deleting Custom Stamps
A stamp can be created from a set of predefined stamps, dynamically created using system
and identity information, or customized from PDF files or common graphic formats. There
are a number of predefined stamps available through the annot objects APmethod.
Adding Comments in a Text Box
You may include a text box comment in a document and control its border, background
color, alignment, font, and size characteristic. The Acrobat JavaScript support for text box
comments is available through the annot objects Squareand Li netypes, as shown in
the example below:
t hi s. addAnnot ( {
page: 0,
t ype: "Squar e",
r ect : [ 0, 0, 100, 100] ,
name: "OnMar ket Shar e",
aut hor : "A. C. Robat "
cont ent s: "Thi s sect i on needs r evi si on"
}) ;
Review, Markup, and Approval
Using Commenting Tools
7
130 Acrobat JavaScript Scripting Guide
Adding Attachments
You may use Acrobat JavaScript to embed sound clips, images, and files within comments.
The Acrobat support for sound and file attachments within comments is available through
the annot objects Soundand Fi l eAttachment types. Also, you may pass an Icon
Stream Generic Object as an optional property (oI con) of the oStates object literal used
in the Col l abobjects addStateModel method.
Sound Attachments
To add a sound attachment using Acrobat JavaScript, invoke the doc objects
i mportSound method to attach the sound file to the PDF. Then create an annotation
using the doc objects addAnnot method, and associate the Soundobject with the
annotation by assigning the name of the Soundobject to the annot objects soundI con
property. An example is given below:
/ / At t ach t he sound f i l e t o t he PDF f i l e
t hi s. i mpor t Sound( "mySound", "/ C/ mySound. wav") ;
/ / Cr eat e t he annot at i on and assi gn i t s soundIcon pr oper t y
t hi s. addAnnot ( {
page: 0,
t ype: "Sound",
r ect : [ 0, 0, 100, 100] ,
name: "mySoundAnnot ",
soundI con: "mySound"
}) ;
File Attachments
To add a file attachment to a document, invoke one of the doc objects i mport methods,
such as i mportDataObj ect. Once the file contents have been imported they can be
accessed using such methods as getDataObj ect, and either merged with your
document content or saved to a disk location. For example, the following code imports the
contents of myFi l e. xml and displays its contents:
/ / Open t he f i l e at t achment named myFi l e. xml
t hi s. i mpor t Dat aObj ect ( myDat a, "/ C/ myFi l e. xml ") ;
/ / Access i t s cont ent s:
var cont ent s = t hi s. get Dat aObj ect ( "myDat a") ;
/ / Di spl ay i t s cont ent s:
f or ( var i i n cont ent s) consol e. pr i nt l n( cont ent s[ i ] ) ;
To create an attachment annotation, set the annot objects attachI conproperty. At this
point, you may decide how to associate the attachments name with the icon.
Acrobat JavaScript Scripting Guide 131
Review, Markup, and Approval
Using Commenting Tools
7
Personalizing Attachments with a Description
To add a description to any annotation, set its contents property. In the case of file or
sound attachments, the property should be used to describe the contents of the
attachment, as shown in the code below:
t hi s. addAnnot ( {
page: 0,
t ype: "Sound",
r ect : [ 0, 0, 100, 100] ,
name: "mySoundAnnot ",
soundI con: "mySound"
cont ent s: "Thi s i s a sound f i l e. "
}) ;
Opening and Saving Attachments
You may use Acrobat JavaScript to open any attachment. The general-purpose way to do
this is to invoke the doc objects getDataObj ectContents method. The following
code opens an attachment and displays its contents in the console:
var oFi l e = t hi s. get Dat aObj ect Cont ent s( "MyAt t achment ") ;
var cFi l e = ut i l . st r i ngFr omSt r eam( oFi l e) ;
consol e. pr i nt l n( cFi l e) ;
To save and possibly open an attachment, invoke the doc objects exportDataObj ect
method. The method has an optional parameter called nLaunchwhich may be set to one
of three values: 0 (do not open, default), 1 (prompt the user for a save path, and open), 2
(do not prompt the user for a save path, and open). When using documents having
extensions other than PDF, include the extension in the file name. The method usage is
shown in the examples below:
/ / j ust save and do not open
t hi s. expor t Dat aObj ect ( "MyAt t achment ") ;
/ / save and open
t hi s. expor t Dat aObj ect ( {
cName: "MyComment s. xl s", nLaunch: 1}
) ;
Review, Markup, and Approval
Using Commenting Tools
7
132 Acrobat JavaScript Scripting Guide
Saving Modified Files into the Primary Document
Once an attached file has been modified, it may be saved once again. To embed its
contents into the primary document, invoke the doc objects
getDataObj ectContents method in order to begin accessing its contents, and
setDataObj ectContents in order to save the modified contents, as shown in the code
sample below:
/ / Open t he f i l e:
t hi s. i mpor t Dat aObj ect ( "myFi l e. t xt ", "/ C/ myFi l e. t xt ") ;
/ / access t he Fi l eSt r eam( af t er whi ch you may modi f y i t ) :
var oFi l e = t hi s. get Dat aObj ect Cont ent s( "myFi l e. t xt ") ;
var cFi l e = ut i l . st r i ngFr omSt r eam( oFi l e, "ut f - 8") ;
/ / now modi f y t he st r i ng cFi l e
/ / . . .
/ / Conver t t he modi f i ed st r i ng back t o a Fi l eSt r eam:
oFi l e = ut i l . st r eamFr omSt r i ng( cFi l e, "ut f - 8") ;
/ / Save t he modi f i ed Fi l eSt r eamcont ent s:
t hi s. set Dat aObj ect Cont ent s( "myFi l e. t xt ", oFi l e) ;
Linking Between Files
You may set up links between files by setting the "Go to View" action of a link annotation. In
the case of nested PDF documents, intermediate documents automatically open. To use
Acrobat JavaScript to create a link, invoke the doc objects addLi nk method. To cause the
link to open a file, set the MouseUpaction to open the file.
Deleting Attachments
You may use Acrobat JavaScript to remove a file attachment from a document by invoking
the doc objects removeDataObj ect method, as shown in the code below:
t hi s. r emoveDat aObj ect ( "myAt t achment ") ;
Spell-checking in Comments and Forms
You may check the spelling of any word using the spel l objects checkWordmethod.
This can be applied to any form field or annotation. First retrieve the contents, and submit
each word to the method.
Setting Spelling Preferences
To set the dictionary order, first retrieve the array of dictionaries using the doc objects
spel l Di cti onaryOrder property. Then modify the order of the array entries, and
assign the array to the same property. An array of currently available dictionaries can be
obtained using the spel l objects di cti onaryNames property.
Acrobat JavaScript Scripting Guide 133
Review, Markup, and Approval
Using Commenting Tools
7
To set the language order, perform a similar algorithm using the doc objects
spel l LanguageOrder property. An array of currently available dictionaries can be
obtained using the spel l objects l anguages property.
Adding Words to a Dictionary
You may use Acrobat JavaScript to add words to a dictionary by invoking the spel l
objects addWordmethod, as shown in the code sample below:
spel l . addWor d( myDi ct i onar y, "myNewWor d") ;
Adding Commenting Preferences
To use Acrobat JavaScript to set commenting preferences, create an object literal
containing common properties to be applied to your comments. Then for every
annotation, pass the object literal to its annot objects setProps method, as shown in
the code sample below:
/ / Cr eat e t he common pr oper t i es i n an obj ect l i t er al :
var myPr ops = {
st r okeCol or : col or . r ed,
popupOpen: t r ue,
ar r owBegi n: "Di amond",
ar r owEnd: "OpenAr r ow"
};
/ / Assi gn t he common pr oper t i es t o a pr evi ousl y cr eat ed annot :
myAnnot . set Pr ops( myPr ops) ;
Changing Colors, Icons, and Other Comment Properties
You may use Acrobat JavaScript to change the properties of any type of annotation. To
change the background color of a comment, assign a new value to its fi l l Col or
property. To change the icon, assign a value to its attachI con, noteI con, or
soundI conproperty. All the comment properties are available through the annot
object, and may be set by invoking its setProps method.
Review, Markup, and Approval
Using Commenting Tools
7
134 Acrobat JavaScript Scripting Guide
Adding Watermarks
A watermark is an area containing text or graphics appearing underneath or over existing
document content when a document is printed. This is often referred to as layered content,
and may appear differently in print than it does on the screen. For example, the word
"Confidential" could appear as a watermark within a document.
You can add watermarks through Acrobat JavaScript by invoking the doc objects
addWatermarkFromFi l eor addWatermarkFromText method, and you may also
create stamp annotations. The addWatermarkFromFi l emethod places, into a
specified location and at a particular scale factor and rotation, a single page from any
document format that Acrobat can convert to PDF (such as JPEG, PNG, TIFF, Word, or
AutoCAD).
The Stamping User Interface
You may create an annotation using the Stamp type, and invoke the annot objects AP
property to determine the appearance of the stamp in the document. The following
appearance options are available for stamp annotations:
Approved
AsI s
Confi denti al
Departmental
Draft
Experi mental
Expi red
Fi nal
ForComment
ForPubl i cRel ease
NotApproved
NotForPubl i cRel ease
Sol d
TopSecret
Acrobat JavaScript Scripting Guide 135
Review, Markup, and Approval
Using Commenting Tools
7
For example, the following code adds an "Approved" stamp to the document:
var annot = t hi s. addAnnot ( {
page: 0,
t ype: "St amp",
aut hor : "Me",
name: "mySt amp",
r ect : [ 400, 400, 550, 500] ,
cont ent s: "Good wor k! ",
AP: "Appr oved"
}) ;
Header and Footer Functionality
You may use Acrobat JavaScript to add headers and footers to your documents. For
example, you may use the doc objects addWatermarkFromText method, which has
several properties useful for this specific purpose:
cText: The actual text displayed in the header or footer.
nTextAl i gn: How the text is aligned in the header or footer.
vTextAl i gn: How the watermark is aligned vertically: a value of 0 aligns it at the top
of the page (header), and a value of 2 aligns it at the bottom of the page (footer).
nStart: The starting page for the watermark. A value of -1 causes the resultant header
or footer to appear on every page of the document.
Control of Font, Size, Placement, Rotation, and Opacity
There are several properties to the doc objects watermark addition methods useful for
controlling font, size, placement, rotation and opacity. These are listed below:
cFont: The font name.
cFontSi ze: The font size (in points).
nTextAl i gn: The text alignment.
nRotati on: The rotation in degrees.
nOpaci ty: The opacity from 0.0 to 1.0, where 0 means transparent and 1 means
opaque.
Approval
Approval workflows may include an automated process in which a PDF document is
automatically sent via email to a recipient for their approval. For example, this may be
accomplished through the usage of the doc objects mai l Doc method. The user may then
use a standard approval stamp (set through the annot objects APproperty), use a custom
stamp, or use a Hanko stamp to create a secure digital signature.
Review, Markup, and Approval
Managing Comments
7
136 Acrobat JavaScript Scripting Guide
Managing Comments
Selecting, Moving, and Deleting Comments
Just as you can access the Comments List in the Acrobat user interface, you may likewise
do so through Acrobat JavaScript, using the doc objects syncAnnotScanand
getAnnots methods. The syncAnnotScanmethod guarantees that all annotations in
the documents are scanned, and the getAnnots method returns a list of annotations
satisfying specified criteria.
For example, the following code scans all the annotations on page 2 of the document and
captures them all in the variable myAnnotList:
t hi s. syncAnnot Scan( ) ;
var myAnnot Li st = t hi s. get Annot s( {nPage: 2}) ;
To move a comment, use the corresponding annot objects setProps method to specify
a new location or page. To delete the comment, invoke the corresponding annot objects
destroy method. In the code sample below, all the free text comments on page 2 of the
document are deleted:
f or ( var i =0; i <myAnnot Li st . l engt h; i ++)
i f ( myAnnot Li st [ i ] . t ype == "Fr eeText ")
myAnnot Li st [ i ] . dest r oy( ) ;
Topics
Selecting, Moving, and Deleting Comments
Using the Comments List
Exporting and Importing Comments
Comparing Comments in Two PDF Documents
Aggregating Comments for Use in Excel
Extracting Comments in a Batch Process
Acrobat JavaScript Scripting Guide 137
Review, Markup, and Approval
Managing Comments
7
Using the Comments List
Once you have acquired the comments list through the doc objects syncAnnotScan
and getAnnots methods, you may change their status, appearance, order, and visibility.
In addition, you will be able to search for comments having certain characteristics.
Changing the Status of Comments
To change the status of a comment using Acrobat JavaScript, invoke the corresponding
annot objects transi ti onToStatemethod, as shown in the code below:
/ / Tr ansi t i on myAnnot t o t he "appr oved" st at e:
myAnnot . t r ansi t i onToSt at e( "Revi ewSt at es", "appr oved") ;
Changing the Appearance of Comments
You may change the appearance of a comment in a variety of ways. If the comment is a
stamp annotation, you may change its appearance by setting its APproperty. In general,
the appearance of any comment may be changed by invoking the annot objects
setProps method, as shown in the code below:
myAnnot . set Pr ops( {
page: 0,
poi nt s: [ [ 10, 40] , [ 200, 200] ] ,
st r okeCol or : col or . r ed,
popupOpen: t r ue,
popupRect : [ 200, 100, 400, 200] ,
ar r owBegi n: "Di amond",
ar r owEnd: "OpenAr r ow"
}) ;
Marking Comments with Checkmarks
You may use the Acrobat user interface to place checkmarks next to comments, or use
Acrobat JavaScript to do the equivalent by changing the status of a comment (see
Changing the Status of Comments).
Review, Markup, and Approval
Managing Comments
7
138 Acrobat JavaScript Scripting Guide
Sorting Comments
If you would like to sort comments using Acrobat JavaScript, you may do so by submitting
an optional parameter to the doc objects getAnnots method. The nSortBy parameter
may be assigned one of the following values:
ANSB_None: Do not sort.
ANSB_Page: Sort by page number.
ANSB_Author: Sort by author.
ANSB_ModDate: Sort by modification date.
ANSB_Type: Sort by annotation type.
In addition, you may specify that the sorting be performed in reverse order by submitting
the optional bReverseparameter to the method.
The code sample given below shows how to obtain a list of comments from page 2 of the
document, sorted in reverse order by author:
t hi s. syncAnnot Scan( ) ;
var myAnnot Li st = t hi s. get Annot s( {
nPage: 2,
nSor t By: ANSB_Aut hor ,
bRever se: t r ue
}) ;
Showing and Hiding Comments
To use Acrobat JavaScript to show or hide a comment, set its corresponding annot objects
hi ddenproperty. For example, the following code hides myAnnot:
myAnnot . hi dden = t r ue;
Finding Comments
There are two ways to use Acrobat JavaScript to find a comment. If you know the name of
the comment, you may invoke the doc objects getAnnot method. Otherwise you may
obtain all the comments by invoking the doc objects getAnnots method, and iterate
through the list.
The getAnnot method requires two parameters: the page number and the name of the
annotation. The following code sample shows how to obtain a comment on page 2 named
knownName:
var comment = t hi s. get Annot ( 2, "knownName") ;
Acrobat JavaScript Scripting Guide 139
Review, Markup, and Approval
Managing Comments
7
Exporting and Importing Comments
To use Acrobat JavaScript to export all the comments in a file, invoke the doc objects
exportAsFDF or exportAsXFDF methods. In both cases, set the bAnnotati ons
parameter to true, as shown in the code sample below, which exports only the comments
and nothing else:
t hi s. expor t AsFDF( {bAnnot at i ons: t r ue}) ;
To use Acrobat JavaScript to import comments from an FDF or XFDF into a file, invoke the
doc objects i mportAnFDFor i mportAnXFDFmethods.
Comparing Comments in Two PDF Documents
While the Acrobat user interface provides you with a menu choice for comparing two
documents, it is possible to customize your comparisons using Acrobat JavaScript. To gain
access to multiple documents, invoke the appobjects openDoc method for each
document you would like to analyze. Each doc object exposes the contents of each
document, such as an array of annotations. You may then compare and report any
information using customized algorithms. For example, the code below reports how many
annotations exist in the two documents:
var doc2 = app. openDoc( "/ C/ secondDoc. pdf ") ;
var annot sDoc1 = t hi s. get Annot s( ) ;
var annot sDoc2 = doc2. get Annot s( ) ;
consol e. pr i nt l n( "Doc 1: " + annot sDoc1. l engt h + " annot s. ") ;
consol e. pr i nt l n( "Doc 2: " + annot sDoc2. l engt h + " annot s. ") ;
Aggregating Comments for Use in Excel
The doc objects exportDataObj ect method may be used to create a tab-delimited
text file, which can then be used in Excel. To use Acrobat JavaScript to aggregate comments
for use in Excel, collect all the comments using the doc objects getAnnots method,
iterate through them and save them into a tab-delimited string, create a text file
attachment object using the doc objects createDataObj ect method, and pass the
string to the cVal ueparameter in the exportDataObj ect method.
Extracting Comments in a Batch Process
In a batch process, you may open any number of doc objects using the appobjects
openDoc method. For each open document, you may invoke its corresponding doc
objects getAnnots method to collect the comments in that file. If you would like to put
all the comments together in one file, you may do so by creating a new document and
saving the various arrays of comments into that new file.
Review, Markup, and Approval
Approving Documents Using Stamps (Japanese Workflows)
7
140 Acrobat JavaScript Scripting Guide
Approving Documents Using Stamps (Japanese Workflows)
Approval workflows are similar to other email-based collaborative reviews, and provide you
with the ability to set the order in which participants are contacted. This means that, based
on the approval issued by a participant, the document may be mailed to the next
participant, and an email may be sent to the initiator.
Setting up a Hanko Approval Workflow
A registered Hanko is a stamp used in Japanese document workflows, and may be used to
sign official contracts. Every registered hanko is unique and is considered a legal form of
identification.
A personal Hanko is not registered, and is used for more common types of signatures, such
as those used in meeting notes or budget proposals. Everyone in an organization who is
involved in a document review must add their Hanko to the document in order for it to gain
final approval.
Adding Instructions
Acrobat provides an assistant to help you set up an approval workflow. You may customize
your workflow as well, by adding form fields to the document containing recipient lists to
be chosen by the participant. This way, in case there are multiple directions for a given
branch in the workflow, the participant may invoke automated functions that send the
document to the correct participants, as well as an email to the initiator containing a record
of activity.
Sending a Document by Email for Approval
You may use Acrobat JavaScript to automate various steps within the workflow by sending
the document and other information by email by via the doc objects mai l Doc method.
Topics
Setting up a Hanko Approval Workflow
Participating in a Hanko Approval Workflow
Acrobat JavaScript Scripting Guide 141
Review, Markup, and Approval
Approving Documents Using Stamps (Japanese Workflows)
7
Participating in a Hanko Approval Workflow
A participant receives an email with instructions for opening the document and
completing their portion of the approval process. As noted above, this can be customized
and automated through the use of form fields if the workflow is complex.
Applying a Hanko or Inkan Stamp
A Hanko stamp is a commenting tool used in approval workflows, and an Inkan stamp is a
unique image that can represent an individuals identity and may be used in place of a
signature. Both are created, customized, and managed through the Acrobat user interface.
In order to use a Hanko or Inkan stamp, you will need to create a custom stamp and add
digital signature information. Once the stamp has been created, you may apply it in your
workflows.
Using Other Stamps and Comments
You may use Acrobat JavaScript to create other stamps by creating a stamp annotation and
setting its corresponding annot objects APproperty. You can obtain a list of stamp names
available in the document by accessing the doc objects i cons property.
Installing and Customizing Hanko Stamps
Creating custom Hanko stamp information involves the combination of user information
and a digital signature. Once you have set this up, it may be saved in a PDF file which is
stored in the St amps folder.
Creating Custom Inkan Stamps
To create an Inkan stamp, add your name, title, department, and company, choose a layout,
and provide a name to use for the stamp. You may also import a PDF form to add
customized features and additional fields containing personal information. In addition, it is
possible to add secure digital signature information to an Inkan stamp.
Deleting Custom Stamps
You may delete any Hanko and Inkan stamps that you created, though it is not possible to
delete any of the predefined stamps in the Stamps palette.
Review, Markup, and Approval
Approving Documents Using Stamps (Japanese Workflows)
7
142 Acrobat JavaScript Scripting Guide
Acrobat JavaScript Scripting Guide 143
8
Working with Digital Media in PDF
Documents
Introduction
In this chapter you will learn how to use Acrobat JavaScript to extend Acrobats ability to
integrate digital media into PDF documents. You will learn how to set up, control, and
customize properties and preferences for media players and monitors, how to integrate
movie and sound clips into your documents, and how to add, edit, and control the settings
for their renditions.
Chapter Goals
At the end of this chapter, you will be able to:
Customize the settings, renditions, and events associated with media players.
Access and control the properties for all monitors connected to the system.
Add movie and sound clips.
Add and edit renditions.
Control rendition settings.
Set multimedia preferences that apply throughout a document.
Contents
Topics
Media Players: Control, Settings, Renditions, and Events
Monitors
Integrating Media into Documents
Setting Multimedia Preferences
Working with Digital Media in PDF Documents
Media Players: Control, Settings, Renditions, and Events
8
144 Acrobat JavaScript Scripting Guide
Media Players: Control, Settings, Renditions, and Events
Introduction
There are several objects provided in Acrobat JavaScript that provide you with the means
to customize the control, settings, renditions, and events related to media players. These
are shown below in Table 8.1.
TABLE 8.1 Media Player Objects
Object Description
App. medi a Primary object for media control, settings, and renditions
Medi aOffset Time or frame position within a media clip
Event A multimedia event fired by a Rendi ti onobject
Events A collection of multimedia event objects
Medi aPl ayer An instance of a multimedia player
Marker A location representing a frame or time value in a media clip
Markers Aall the markers in the currently loaded media clip
Medi aRej ect Contains error information when a Rendi ti onobject is
rejected
Medi aSel ecti on A media selection object used to create the Medi aSetti ngs
object
Medi aSetti ngs An object containing settings used to create a Medi aPl ayer
object
Moni tor A display monitor used for playback
Moni tors An array of display monitors connected to the users system
Pl ayerI nfo An available media player
Pl ayerI nfoLi st An array of Pl ayerI nfoobjects
Rendi ti on Contains information needed to play a media clip
ScreenAnnot A display area used for media playback
Acrobat JavaScript Scripting Guide 145
Working with Digital Media in PDF Documents
Media Players: Control, Settings, Renditions, and Events
8
Accessing a List of Active Players
To obtain a list of available players, call the app. medi aobjects getPl ayers method,
which accepts an optional parameter specifying the MIME type and returns a
Pl ayerI nfoLi st object. The Pl ayerI nfoLi st object is an array of Pl ayerI nfo
objects that can be filtered using its sel ect method.
The following code sample shows how to obtain a list of all available players:
var mp = app. medi a. get Pl ayer s( ) ;
The following code sample shows how to obtain a list of all available MP3 players and prints
them out to the console:
var mp = app. medi a. get Pl ayer s( "audi o/ MP3") ;
f or ( var i = 0; i < mp. l engt h; i ++) {
consol e. pr i nt l n( "\ nmp[ " + i + "] Pr oper t i es") ;
f or ( var p i n mp[ i ] )
consol e. pr i nt l n( p + ": " + mp[ i ] [ p] ) ;
}
To filter the list of players using the Pl ayerI nfoLi st objects sel ect method, you may
supply an optional obj ect parameter which may contain any combination of i d, name,
and versi onproperties, each of which may be either a string or a regular expression. For
example, the following code obtains the QuickTime media player:
var mp = app. medi a. get Pl ayer s( ) . sel ect ( {i d: / qui ckt i me/ i }) ;
In addition, the doc. medi aobjects getOpenPl ayers method returns an array of all
currently open Medi aPl ayer objects. With this array, you can stop or close all players,
and manipulate any subset of the open players. The following example stops all running
players in the document:
var pl ayer s = doc. medi a. get OpenPl ayer s( oDoc) ;
f or ( var i i n pl ayer s)
pl ayer s[ i ] . st op( ) ;
Media Players Topics
Accessing a List of Active Players
Specifying Playback Settings
Working with Digital Media in PDF Documents
Media Players: Control, Settings, Renditions, and Events
8
146 Acrobat JavaScript Scripting Guide
Specifying Playback Settings
You can use Acrobat JavaScript to obtain and adjust the media settings offered by a player.
To do this, invoke the Rendi ti onobjects getPl aySetti ngs method, which returns a
Medi aSetti ngs object, as shown in the code below:
var set t i ngs = myRendi t i on. get Pl aySet t i ngs( ) ;
In additon to the App. medi aproperties and methods, a Medi aSetti ngs object, which
is used to create a Medi aPl ayer object, contains many properties related to the
functional capabilities of players. These are described below in Table 8.2:
TABLE 8.2 MediaSettings Object Properties
Property Description
autoPl ay Determines whether to play media clip automatically
when the player is opened
baseURL Used to resolve any relative URLs used in the media clip
bgCol or Specifies the background color for the media player
window
bgOpaci ty Specifies the background opacity for the media player
window
endAt Defines the ending time or frame for playback
data The contents of the media clip (Medi aDataobject)
durati on The number of seconds required for playback
fl oati ng An object containing the location and size properties of a
floating window used for playback
l ayout A value indicating whether and how the content should
be resized to fit the window
moni tor Defines the rectangle containing the display monitor
used for playback
moni torType The category of display monitor used for playback (such
as primary, secondary, best color depth, etc)
page The document page number used in case a docked
media player is used
pal i ndrome Indicates that the media can play from beginning to end,
and then in reverse from the end to the beginning
pl ayers The list of available players for this rendition
rate The playback speed
Acrobat JavaScript Scripting Guide 147
Working with Digital Media in PDF Documents
Media Players: Control, Settings, Renditions, and Events
8
The example below illustrates how to customize the number of repetitions for playback:
/ / obt ai n t he Medi aSet t i ngs obj ect , and st or e i t s r epeat val ue
var nRepeat = event . act i on. r endi t i on. get Pl aySet t i ngs( ) . r epeat ;
i f ( nRepeat == 1)
nRepeat = 2;
el se
nRepeat = 1;
/ / set t he new r epeat val ue when openi ng t he medi a pl ayer
var ar gs = { set t i ngs: {r epeat : nRepeat } };
app. medi a. openPl ayer ( ar gs) ;
The example below illustrates how to play a docked media clip in a Screen annotation:
app. medi a. openPl ayer ( {
r endi t i on: t hi s. medi a. get Rendi t i on( "myCl i p") ,
annot : t hi s. medi a. get Annot ( {
nPage: 0,
cAnnot Ti t l e: "myScr een"
}) ,
set t i ngs: {
wi ndowType: app. medi a. Wi ndowType. docked
}
}) ;
repeat The number of times the playback repeats
showUI Indicates whether the media player controls will be
visible
startAt Defines the starting time or frame for playback
vi si bl e Indicates whether the media player will be visible
vol ume The playback volume
wi ndowType An enumeration obtained from
App. medi a. Wi ndowTypeindicating whether the
media player window will be docked or floating
TABLE 8.2 MediaSettings Object Properties
Property Description
Working with Digital Media in PDF Documents
Media Players: Control, Settings, Renditions, and Events
8
148 Acrobat JavaScript Scripting Guide
The next example illustrates how to play back the alternate text of a rendition in a floating
window:
/ / set up t he al t er nat e t ext
var r endi t i on = t hi s. medi a. get Rendi t i on( "myCl i p") ;
var set t i ngs = r endi t i on. get Pl aySet t i ngs( ) ;
var ar gs = {
set t i ngs: set t i ngs,
showAl t Text : t r ue,
showEmpt yAl t Text : t r ue
};
var sel ect i on = r endi t i on. sel ect ( ) ;
set t i ngs = app. medi a. get Al t Text Set t i ngs( ar gs, sel ect i on) ;
set t i ngs. dat a = "A. C. Robat ") ;
/ / set up t he f l oat i ng wi ndow
set t i ngs. wi ndowType = app. medi a. wi ndowType. f l oat i ng;
set t i ngs. f l oat i ng = {
canResi ze: app. medi a. canResi ze. keepRat i o,
hasCl ose: t r ue,
wi dt h: 400,
hei ght : 100
};
/ / pl ay t he al t er nat e t ext i n t he f l oat i ng wi ndow
ar gs = {
r endi t i on: r endi t i on,
annot : t hi s. medi a. get Annot ( {
nPage: 0,
cAnnot Ti t l e: "myScr een"
}) ,
set t i ngs: set t i ngs
};
app. medi a. openPl ayer ( ar gs) ;
Acrobat JavaScript Scripting Guide 149
Working with Digital Media in PDF Documents
Monitors
8
Monitors
The Acrobat JavaScript Moni tors object is a read-only array of Moni tor objects, each of
which represents a display monitor connected to the users system. It is available as a
property of the appobject, and you may write customized Acrobat JavaScript code to
iterate through this array to obtain information about the available monitors and select one
for a full-screen or popup media player.
It is possible to apply filtering criteria to select a monitor. For example, you can select the
monitor with the best color, or if there are multiple instances, additionally select the
monitor with the greatest color depth. These criteria are methods of the Moni tor object,
and are listed below in Table 8.3.
TABLE 8.3 Monitors Filter Criteria Methods
Method Description
bestCol or Returns the monitors with the greatest color depth
bestFi t Returns the smallest monitors with minimum specified
dimensions
desktop Creates a new monitor representing the entire virtual
desktop
document Returns the monitors containing the greatest amount of
the document
fi l ter Returns the monitors having the highest rank according
to a ranking function supplied as a parameter
l argest Returns the monitors with the greatest area in pixels
l eastOverl ap Returns the monitors overlapping the least with a given
rectangle
mostOverl ap Returns the monitors overlapping the most with a given
rectangle
nonDocument Returns the monitors displaying the least amount (or
none) of the document
pri mary Rreturns the primary monitor
secondary Returns all monitors except for the primary one
sel ect Returns monitors filtered by monitor type
tal l est Returns the monitors with the greatest height in pixels
wi dest Returns the monitors with the greatest width in pixels
Working with Digital Media in PDF Documents
Monitors
8
150 Acrobat JavaScript Scripting Guide
In addition to the capabilities within the Moni tors object, the Moni tor object provides
the properties shown below in Table 8.4:
The example below illustrates how to obtain the primary monitor and check its color depth:
var moni t or s = app. moni t or s. pr i mar y( ) ;
i f ( moni t or s. l engt h > 0)
consol e. pr i nt l n( "Col or dept h: " + moni t or s[ 0] . col or Dept h) ;
The next example llustrates how to obtain the monitor with the greatest color depth, with a
minimum specified depth of 32:
var moni t or s = app. moni t or s. best Col or ( 32) ;
i f ( moni t or s. l engt h > 0)
consol e. pr i nt l n( "Found t he best col or dept h over 32! ") ;
The next example llustrates how to obtain the monitor with the greatest width in pixels,
and determines whether it is the primary monitor:
var moni t or s = app. moni t or s. wi dest ( ) ;
var i sI sNot = ( moni t or s[ 0] . i sPr i mar y) ? " i s " : " i s not ";
consol e. pr i nt l n( "Wi dest moni t or " + i sI sNot + "t he pr i mar y. ") ;
TABLE 8.4 Monitor Object Properties
Property Description
col orDepth The color depth of the monitor in bits per pixel
i sPri mary Returns trueif the monitor is the primary one
rect The boundaries of the monitor in virtual desktop
coordinates
workRect The monitors workspace boundaries in virtual desktop
coordinates
Acrobat JavaScript Scripting Guide 151
Working with Digital Media in PDF Documents
Integrating Media into Documents
8
Integrating Media into Documents
You may use Acrobat JavaScript to integrate media into documents, which may be played
in either Screen Annot objects or floating windows. The doc. medi aobject is useful for
accessing Screen Annot objects in which the media clips can be played.
Adding Movie Clips
It is possible to embed a movie in a document or create a link to one. To add a movie clip to
a document, you must first obtain a media player capable of playing it. Do this by invoking
the app. medi aobjects getPl ayers method, which accepts an optional parameter
specifying the MIME type. For example, the code below shows how to obtain a player that
can play a movie:
/ / cr eat e t he medi a pl ayer obj ect
var pl ayer = app. medi a. cr eat ePl ayer ( ) ;
/ / f i l t er f or t hose t hat can pl ay a movi e ( speci f y MI ME t ype)
pl ayer . set t i ngs. pl ayer s = app. medi a. get Pl ayer s( "vi deo/ x- mpg") ;
/ / choose whi ch f i l e t o pl ay
pl ayer . set t i ngs. dat a = "myCl i p. mpg";
/ / open t he pl ayer
pl ayer . open( ) ;
Topics
Adding Movie Clips
Adding Sound Clips
Adding and Editing Renditions
Setting Multimedia Preferences
Working with Digital Media in PDF Documents
Integrating Media into Documents
8
152 Acrobat JavaScript Scripting Guide
Adding Sound Clips
The procedure for adding a sound clip is similar to that for movie clips. Specify the MIME
type and the sound data to be played. In the example below, a sound clip is loaded from a
URL and played in a floating window:
var myURLCl i p = "ht t p: / / myWebSi t e. com/ mySoundCl i p. mp3";
var ar gs = {
URL: myURLCl i p,
mi meType: "audi o/ mp3",
doc: t hi s,
set t i ngs: {
pl ayer s: app. medi a. get Pl ayer s( "audi o/ mp3") ,
wi ndowType: app. medi a. wi ndowType. f l oat i ng,
dat a: app. medi a. get URLDat a( myURLCl i p, "audi o/ mp3") ,
f l oat i ng: {hei ght : 400, wi dt h: 600}
},
};
app. medi a. openPl ayer ( ar gs) ;
Adding and Editing Renditions
A rendi ti onobject contains information needed to play a media clip, including
embedded media data (or a URL), and playback settings, and corresponds to the Rendition
in the Acrobat user interface. When you add a movie or sound clip to your document, a
default rendition is listed in the Multimedia Properties dialog box and is assigned to a
MouseUpaction. In case the rendition cannot be played, you may add other renditions or
edit the existing ones.
If you add alternate versions of the media clip, these become new renditions that can serve
as alternates in case the default choice cannot be played. It is then possible to invoke the
rendi ti onobjects sel ect method to obtain the available media players for each
rendition.
There are several types of settings that can be specified for a given rendition: media
settings, playback settings, playback location, system requirements, and playback
requirements. You can use Acrobat JavaScript to customize some of these settings through
the rendi ti onobject. There are several properties to which you have read-only access
when editing a rendition. These are listed below in Table 8.5.
Acrobat JavaScript Scripting Guide 153
Working with Digital Media in PDF Documents
Setting Multimedia Preferences
8
In addition to these properties, you may invoke the rendi ti onobjects
getPl aySetti ngs method, which returns a Medi aSetti ngs object. As you learned
earlier in Specifying Playback Settings, you can adjust the settings through this object. You
may also invoke its testCri teri amethod, with which you can test the rendition against
any criteria specified in the PDF file, such as minimum bandwidth.
Setting Multimedia Preferences
In general, you may choose which media player should be used to play a given clip,
determine whether the Player Finder dialog box is displayed, and set accessibility options
for impaired users (these include subtitles, dubbed audio, or supplemental text captions).
In addition, you may use Acrobat JavaScript to access or customize multimedia preferences.
For example, the doc. medi aobjects canPl ay property may be used to indicate
whether multimedia playback is allowed for the document. The Medi aSetti ngs objects
bgCol or property can be used to specify the background color for the media player
window. Examples of each are given below:
var canPl ay = doc. medi a. canPl ay;
i f ( canPl ay. no) {
/ / det er mi ne whet her secur i t y set t i ngs pr ohi bi t pl ayback:
i f ( canPl ay. no. secur i t y) {
i f ( canPl ay. canShowUI )
app. al er t ( "Secur i t y pr ohi bi t s pl ayback. ") ;
el se
consol e. pr i nt l n( "Secur i t y pr ohi bi t s pl ayback. ") ;
}
}
/ / Set t he backgr ound col or t o r ed:
set t i ngs. bgCol or = [ "RGB", 1, 0, 0] ;
TABLE 8.5 Rendition Object Properties
Property Description
al tText The alternate text string for the rendition
doc The document that contains the rendition
fi l eName Returns the filename or URL of an external media clip
type A Medi aRendi ti onobject or a rendition list
ui Name The name of the rendition
Working with Digital Media in PDF Documents
Setting Multimedia Preferences
8
154 Acrobat JavaScript Scripting Guide
Acrobat JavaScript Scripting Guide 155
9
Acrobat Templates
Introduction
This chapter will help you gain a greater depth of understanding of the purpose and usage
of templates. You will understand the role of templates in PDF form structures, and the
options and implications related to their usage. Finally, you will learn the details related to
the proper usage of the parameters defined for the templ ateobjects methods.
Chapter Goals
At the end of this chapter, you will be able to:
Understand the role of templates within the architecture of PDF forms.
Understand the implications of spawning templates.
Understand the details of how templates handle form fields in dynamic page
generation.
Specify the proper syntax and usage of all the parameters available in the templ ate
objects methods.
Create templates and use them to dynamically create content in your documents.
Contents
Topics
The Role of Templates in PDF Form Architecture
Spawning Templates
Acrobat Templates
The Role of Templates in PDF Form Architecture
9
156 Acrobat JavaScript Scripting Guide
The Role of Templates in PDF Form Architecture
Introduction
Acrobat JavaScript defines a templ ateobject that supports interactive form
architectures. In this context, a templ ateis a named page within a PDF document that
provides a convenient format within which to automatically generate and manipulate a
large number of form fields. These pages contain visibility settings, and can be used to
spawn new pages containing identical sets of form controls to those defined within the
template.
As you learned earlier, it is possible to use templates to dynamically generate new content
within a document. Templates can be used to assure that your content is reusable, and can
be used for replicating the logic you previously created.
A template is used to reproduce the logic on a given page at any new location in the
document. This logic may include form fields such as text fields and buttons, digital
signatures, and embedded logic such as JavaScripts that email form data to another user.
To create a template based on a page, invoke the doc objects createTempl ate
method, in which you will name your template and specify the page from which it will be
created. The code below creates a template called myTempl atebased on page 5 of the
current document:
t hi s. cr eat eTempl at e( {cName: " myTempl at e" , nPage: 5}) ;
There are two steps required to generate pages based on a template contained in the
document:
1. Select a template from the doc objects templ ates property, which is an array of
templ ateobjects.
2. Spawn a page invoking the templ ateobjects spawnmethod.
The following code adds a new page at the end of the current document that is based on
the first template contained in the document:
var myTempl at eAr r ay = t hi s. t empl at es;
var myTempl at e = myTempl at eAr r ay[ 0] ;
myTempl at e. spawn( t hi s. numPages, f al se, f al se) ;
Acrobat JavaScript Scripting Guide 157
Acrobat Templates
Spawning Templates
9
Spawning Templates
Dynamic Form Field Generation
When spawning templates, you may specify whether the form fields are renamed on the
new page or retain the same names as those specified in the template. This is done through
the optional bRenameparameter. If you set the parameters value to true, the form fields
on each spawned page have unique names, and values entered into any of those fields do
not affect values in their counterparts on other pages. This would be useful, for example, in
forms containing expense report items. If you set the parameters value to fal se, the form
fields on each spawned page have the same name as their counterparts on all the other
spawned pages. This might be useful if you would like, for example, to duplicate a button or
display the date on every page, since entering it once results in its duplication throughout
all the spawned pages.
Suppose the bRenameparameter is trueand the field name on the template is
myFi el d. If the template is named myTempl ateand is spawned onto page 4, the new
corresponding field name is P. 4. myTempl ate. myFi el d. The page number embedded
in the new field guarantees its uniqueness.
Dynamic Page Generation
When templates are used to spawn new pages, those pages contain an identical set of form
fields to those defined in the template. Depending on the parameters used, this process
may result in a size inflation problem. This is because there are two ways to specify page
generation: one option is to repeatedly spawn the same page which results in the
duplication of XObj ect objects (external graphics objects), and the other is to generate
page contents as XObj ect objects, which only requires that those objects be
repositioned.
The nPageparameter is used to specify the zero-based index of the page number used to
create the page. If the bOverl ay value is set to true, the new page overlays onto the
page number specified in the nPageparameter. If the bOverl ay value is set to fal se,
the new page is inserted as a new page before the specified page. To append a page at the
end of the document, set the bOverl ay value to false and the nPageparameter to the
total number of pages in the document.
Acrobat Templates
Spawning Templates
9
158 Acrobat JavaScript Scripting Guide
Template Syntax and Usage
In this first example, all the templates will be spawned once, the field names will not be
unique in each resultant page (bRenamewill be fal se), and the resultant pages will be
appended to the end of the document (bOverl ay will be fal se). The oXObj ect
parameter will be used to prevent size inflation:
/ / Obt ai n t he col l ect i on of t empl at es:
var t = t hi s. t empl at es;
/ / Spawn each t empl at e once as a page appended at t he end:
f or ( var i = 0; i < t . l engt h; i ++)
t [ i ] . spawn( t hi s. numPages, f al se, f al se) ;
In this next example, the same template will be spawned 10 times, will overlay onto pages 0
through 9 (bOverl ay will be true), and the field names will be unique on each page
(bRenamewill be true):
/ / Obt ai n t he t empl at e:
var t = t hi s. t empl at es;
var T = t [ 0] ;
/ / Pr event f i l e si ze i nf l at i on by usi ng t he XObj ect . Do t hi s by
/ / spawni ng once, savi ng t he r esul t ( an XObj ect ) , and passi ng
/ / t he r esul t ant XObj ect t o t he oXObj ect par amet er i n
/ / t he subsequent cal l s t o t he spawn met hod:
var XO = T. spawn( 0, t r ue, t r ue) ;
f or ( var i = 1; i < 10; i ++)
T. spawn( i , t r ue, t r ue, XO) ;
In this next example, we will retrieve the template named myTempl ate, overlay it onto
pages 5 through 10 (bOverl ay will be true), and use the same field names on each page
(bRenamewill be fal se):
/ / Obt ai n t he t empl at e name "myTempl at e":
var t = t hi s. get Templ at e( "myTempl at e") ;
/ / Pr event f i l e si ze i nf l at i on:
var XO = t . spawn( 5, t r ue, f al se) ;
/ / Spawn t he r emai ni ng pages:
f or ( var i = 6; i <= 10; i ++)
t . spawn( i , t r ue, f al se, XO) ;
Acrobat JavaScript Scripting Guide 159
10
Modifying the User Interface
Introduction
This chapter will provide you with an in-depth understanding of the ways in which you may
present and modify the user interface. You will learn how to use Acrobat JavaScript to
access the Adobe Dialog Manager (ADM), customize navigation in PDF documents,
customize PDF layers, and manage print production.
Chapter Goals
At the end of this chapter, you will be able to:
Create modal dialogs through Acrobat JavaScript access to ADM.
Add and customize navigation in PDF documents.
Customize the properties and behavior or PDF layers.
Understand how to manage print production of PDF documents.
Contents
Topics
Using Adobe Dialog Manager (ADM) in Acrobat JavaScript
Adding Navigation to PDF Documents
Working with PDF Layers
Modifying the User Interface
Using Adobe Dialog Manager (ADM) in Acrobat JavaScript
10
160 Acrobat JavaScript Scripting Guide
Using Adobe Dialog Manager (ADM) in Acrobat JavaScript
Introduction
The Adobe Dialog Manager (ADM) is a cross-platform API for implementing dialog-based
user interfaces in a uniform way for Adobe applications such as Acrobat, Photoshop,
Illustrator, and After Effects. Acrobat JavaScript provides a convenient interface to ADM
through which you may implement modal dialogs containing list objects and other
controls normally included in graphical user interfaces, including buttons, text, text boxes,
check boxes, radio buttons, progress bars, scroll bars, and sliders. These are summarized
below in Table 10.1.
TABLE 10.1 ADM Dialog Elements
Element Type Description
button push button
check_box check box
radi o radio button
l i st_box list box
hi er_l i st_box hierarchical list box
stati c_text static text box
edi t_text editable text box
popup popup control
ok OK button
ok_cancel OK and Cancel button
ok_cancel _other OK, Cancel, and Other button
vi ew container for a set of controls
cl uster frame for a set of controls
gap place holder
Acrobat JavaScript Scripting Guide 161
Modifying the User Interface
Using Adobe Dialog Manager (ADM) in Acrobat JavaScript
10
ADM Object Hierarchy
An ADM user interface consists of dialog objects and the items they contain. All items have
properties and events that determine their default behavior and allow them to be modified
or extended. Thus, when an ADM dialog object is created, it contains a series of methods
and utilities. There are three categories of ADM dialog items:
ADM Hierarchy List
Hierarchy List Box
ADM List
List Box
Popup List
Popup Menu
Scrolling Popup List
Spin Edit Popup
Spin Edit Scrolling Popup
Text Edit Popup
Text Edit Scrolling Popup
non-list items
Frame
Picture Push Button
Picture Radio Button
Picture Static
Picture Check Box
Resize
Scrollbar
Slider
Spin Edit
Text Check Box
Text Edit
Text Edit Read-only
Text Edit MultiLine
Text Edit MultiLine Read-only
Text Push Button
Text Radio Button
Text Static
Text Static MultiLine
Progress Bar
Chasing Arrows
Dial
ItemGroup
Popup Control
Modifying the User Interface
Using Adobe Dialog Manager (ADM) in Acrobat JavaScript
10
162 Acrobat JavaScript Scripting Guide
Popup Control Button
Popup Spin Edit Control
Password Text Edit
Access to ADM through JavaScript
The appobjects execDi al og method is the Acrobat JavaScript method used to execute
ADM dialogs. The method requires a single parameter: an object literal known as a dialog
descriptor, which contains properties and method handlers for all the dialog elements.
An instance of the Di al ogobject is passed to the method handlers. The Di al ogobject
has two important methods: the l oadmethod is used to initialize dialog elements, and the
storemethod retrieves values stored in dialog elements.
The dialog handlers are described below in Table 10.2:
A dialog descriptor is a tree consisting of a root and child nodes. The root is an object literal
containing the properties shown below in Table 10.4, and each child node is a dialog
element containing the properties shown below in Table 10.5. In addition to the standard
properties described in Table 10.5 for dialog elements, there are sets of properties available
for the stati c_text, edi t_text, ok, ok_cancel , and ok_cancel _other
elements. These are listed below in Table 10.3:
TABLE 10.2 Dialog Handlers
Handler Description
i ni ti al i ze Method that runs when the dialog is created
val i date Method called when validating field values
commi t Method called when OK button is selected
destroy Method that runs when the dialog is destroyed
i temI D Method called when an elements i temI Dproperty is
modified
Acrobat JavaScript Scripting Guide 163
Modifying the User Interface
Using Adobe Dialog Manager (ADM) in Acrobat JavaScript
10
TABLE 10.3 Dialog Descriptor Element Properties
Element Properties
stati c_text mul ti l i ne
edi t_text mul ti l i ne, readonl y, password, numeri c,
PopupEdi t, Spi nEdi t
ok ok_name, cancel _name, other_name
ok_cancel ok_name, cancel _name, other_name
ok_cancel _other ok_name, cancel _name, other_name
TABLE 10.4 Root Node of Dialog Descriptor
Property Description
name Title bar
target_i d i temI Dvalue for the active dialog item when the dialog
is created
fi rst_tab i temI Dvalue for the dialog item first in tab order
wi dth Width of the dialog in pixels
hei ght Height of the dialog in pixels
char_wi dth Width of the dialog in characters
char_hei ght Height of the dialog in characters
al i gn_chi l dren Alignment for all descendants
el ements Array of elements contained in the dialog
Modifying the User Interface
Using Adobe Dialog Manager (ADM) in Acrobat JavaScript
10
164 Acrobat JavaScript Scripting Guide
TABLE 10.5 Dialog Element Object Literal
Property Description
name Displayed name of dialog element
i tem_i d i temI Dvalue for the dialog
type Dialog element type
next_tab i temI Dvalue for the next dialog item in the tab order
wi dth Width of the element in pixels
hei ght Height of the element in pixels
char_wi dth Width of the element in characters
char_hei ght Height of the element in characters
font The elements font: default, dialog, or palette
bol d Bold font
i tal i c Italic font
al i gnment Alignment for the element
al i gn_chi l dren Alignment for all descendents
el ements Array of elements contained in this element
Acrobat JavaScript Scripting Guide 165
Modifying the User Interface
Using Adobe Dialog Manager (ADM) in Acrobat JavaScript
10
The following example creates the modal dialog as shown below in Figure 10.1:
FIGURE 10.1 ADM Dialog with Item Cluster
To create a dialog such as the one above in Figure 10.1, first create an object literal
containing a dialog descriptor, and pass it as a parameter to the appobjects execDi al og
method. The object literal may be comprised of one or more of the handlers described in
Table 10.2, a root dialog element, and a hierarchy of dialog items as children of the root
node.
We will begin by creating the handlers for the dialog descriptor. The i ni ti al i zehandler
is called as the dialog is created, and the commi t handler is called when OK is selected. The
i ni ti al i zehandler sets up the list tems, and the commi t handler processes those
items.
Modifying the User Interface
Using Adobe Dialog Manager (ADM) in Acrobat JavaScript
10
166 Acrobat JavaScript Scripting Guide
The following i ni ti al i zehandler initializes the items used in the list_box. Note that it
receives the di al ogobject as a parameter:
/ / Event handl er t o i ni t i al i ze t he l i st _box
i ni t i al i ze: f unct i on( di al og)
{
/ / Cr eat e a l i st _box named sub1 and set up 4 choi ces:
di al og. l oad( {
"sub1":
{
"one": - 1,
"t wo": - 2,
"t hr ee": +3,
"f our ": - 4
}
}) ;
}
The following commi t handler is called when OK is clicked, retrieves the values of the
items used in the l i st_box, and can take action based on those values. Note that it
receives the di al ogobject as a parameter:
commi t : f unct i on( di al og)
{
/ / Ret r i eve t he val ues st or ed i n l i st _box sub1:
var el ement s = di al og. st or e( ) [ "sub1"] ;
/ / I t er at e t hr ough i t ems and t ake act i ons as needed
f or ( var e i n el ement s)
{
/ / per f or mact i on
}
}
It is also possible to write event handlers for specific items selected in the dialog. The
following handler is called when the button labeled butnis clicked:
"but n": f unct i on( di al og)
{
app. al er t ( "but n was cl i cked. ") ;
}
Finally, to create the root node, we must create the descri pti onobject literal, which is
the di al ogdescriptor. This is shown in the complete sample code shown below:
Acrobat JavaScript Scripting Guide 167
Modifying the User Interface
Using Adobe Dialog Manager (ADM) in Acrobat JavaScript
10
var myDi al og =
{
i ni t i al i ze: f unct i on( di al og)
{
/ / Set up and st or e t he val ues i n l i st _box sub1:
di al og. l oad( {
"sub1":
{
/ / Not e: posi t i ve val ue r epr esent s t he sel ect ed i t em
"one": - 1,
"t wo": - 2,
"t hr ee": +3, / / cur r ent l y sel ect ed i t em
"f our ": - 4
}
}) ;
},
commi t : f unct i on( di al og)
{
/ / Ret r i eve t he val ues st or ed i n l i st _box sub1:
var el ement s = di al og. st or e( ) ;
/ / I t er at e t hr ough i t ems and t ake act i ons as needed
f or ( var e i n el ement s[ "sub1"] )
/ / I f t he val ue i s posi t i ve, i t was sel ect ed:
i f ( el ement s[ "sub1"] [ e] > 0)
{
/ / di spl ay t he l i st val ue sel ect ed:
app. al er t ( "You chose: \ n" + e) ;
/ / cal l a r el at ed f unct i on f or t he sel ect i on
r c = el ement s[ "sub1"] [ e] ;
Li st Handl er ( r c) ;
}
},
/ / event handl er f or but n but t on cl i cks
"but n": f unct i on( di al og)
{
app. al er t ( "J avaScr i pt ADMDi al og i n Acr obat 7. ") ;
},
Modifying the User Interface
Using Adobe Dialog Manager (ADM) in Acrobat JavaScript
10
168 Acrobat JavaScript Scripting Guide
/ / Di al og obj ect descr i pt or ( r oot node)
descr i pt i on:
{
name: "Sampl e Di al og",
el ement s:
[
{
t ype: "vi ew",
al i gn_chi l dr en: "al i gn_l ef t ",
el ement s:
[
{
t ype: "cl ust er ",
name: "I t emCl ust er ",
el ement s:
[
{
t ype: "st at i c_t ext ",
name: "Sel ect I t em",
f ont : "def aul t "
},
{
t ype: "l i st _box",
i t em_i d: "sub1",
wi dt h: 200,
hei ght : 100
},
{
t ype: "but t on",
i t em_i d: "but n",
name: "Pr ess Me"
}
]
},
{
t ype: "ok_cancel "
}
]
}
]
}
};
Acrobat JavaScript Scripting Guide 169
Modifying the User Interface
Using Adobe Dialog Manager (ADM) in Acrobat JavaScript
10
/ / Funct i on t o handl e t he user s l i st sel ect i on:
f unct i on Li st Handl er ( r c)
{
swi t ch ( r c) {
case 1:
app. al er t ( "Li st Handl er r esponse f or 1 - one") ;
br eak;
case 2:
app. al er t ( "Li st Handl er r esponse f or 2 - t wo") ;
br eak;
case 3:
app. al er t ( "Li st Handl er r esponse f or 3 - t hr ee") ;
br eak;
case 4:
app. al er t ( "Li st Handl er r esponse f or 4 - f our ") ;
br eak;
def aul t :
app. al er t ( "I nval i d sel ect i on") ;
br eak;
}
}
r c = app. execDi al og( myDi al og) ;
Modifying the User Interface
Adding Navigation to PDF Documents
10
170 Acrobat JavaScript Scripting Guide
Adding Navigation to PDF Documents
Acrobat JavaScript provides a number of constructs that enable you to add and customize
navigation features within PDF documents. These features make it convenient for the user
to see and visit areas of interest within the document, and you may associate a variety of
actions with navigation events. In addition, you may customize the appearance of your
form fields and pages, manipulate multiple documents, add and delete pages, and add
headers, footers, watermarks, backgrounds, and buttons.
Topics
Thumbnails
Bookmarks
Links
Using Actions for Special Effects
Highlighting Form Fields and Navigational Components
Setting Up a Presentation
Numbering Pages
Creating Buttons
Acrobat JavaScript Scripting Guide 171
Modifying the User Interface
Adding Navigation to PDF Documents
10
Thumbnails
Creating Page Thumbnails
The doc object provides methods for adding and removing thumbnails in a document. To
add a set of thumbnails, invoke the di al ogobjects addThumbnai l s method, which
creates thumbnails for a specified set of pages in the document. It accepts two optional
parameters: nStart and nEndrepresent the beginning and end of an inclusive range of
page numbers.
For example, to add thumbnails for pages 2 through 5, use the following command:
t hi s. addThumbnai l s( {nSt ar t : 2, nEnd: 5}) ;
To add a thumbnail for just one page, just provide a value for nStart. The following
example adds a thumbnail for page 7:
t hi s. addThumbnai l s( {nSt ar t : 7}) ;
To add thumbnails from page 0 to a specified page, just provide a value for nEnd. The
following example adds thumbnails for pages 0-7:
t hi s. addThumbnai l s( {nEnd: 7}) ;
To add thumbnails for all the pages in the document, omit both parameters:
t hi s. addThumbnai l s( ) ;
To remove a set of thumbnails, invoke the doc objects removeThumbnai l s method,
which accepts the same parameters as the addThumbnai l s method. For example, to
remove pages 2 to 5, use the following code:
t hi s. r emoveThumbnai l s( {nSt ar t : 2, nEnd: 5}) ;
Adding Page Actions with Page Thumbnails
You may associate a PageOpenevent with a page thumbnail. The most straightforward
way of doing this is to specify a Page Open action in the Page Properties dialog.
To customize a page action with Acrobat JavaScript, invoke the doc objects
setPageActi onmethod for the page to be opened. In the following example, a greeting
is displayed when the user clicks on the thumbnail for page 2:
t hi s. set PageAct i on( 2, "Open", "app. al er t ( Hel l o ) ; ") ;
The advantage of this approach is that you can dynamically build JavaScript strings to be
used in the method call.
Bookmarks
You can use Acrobat JavaScript to customize the appearance and behavior of the
bookmarks that appear in the Bookmarks navigation panel. Every PDF document has an
object known as bookmarkRoot, which is the root of the bookmark tree for the
document. It is possible to recursively add and modify levels of bookmarks underneath the
root. Each node is a bookmarkobject which can have any number of children.
Modifying the User Interface
Adding Navigation to PDF Documents
10
172 Acrobat JavaScript Scripting Guide
Acrobat JavaScript makes the bookmarkRoot object available as a property of the doc
object. This root node contains a property called chi l dren, which is an array of
bookmarkobjects. The bookmarkobject has the properties shown below in Table 10.6,
and the methods shown below in Table 10.7:
Creating Bookmarks
To create a bookmark, it is necessary to navigate through the bookmark tree and identify
the parent of the new node. Begin by accessing the bookmarkRoot, which is a property
of the current document representing the top node in the bookmark tree:
var myRoot = t hi s. bookmar kRoot ;
Assume there are no bookmarks in the document. To create a new bookmark, invoke the
bookmarkRoot objects createChi l dmethod to which you may submit the following
parameters: cName(the name to appear in the navigational panel), cExpr (an optional
JavaScript to be executed when the bookmark is clicked), and nI ndex (an optional zero-
based index into the chi l drenarray).
TABLE 10.6 Bookmark Properties
Property Description
chi l dren Returns the array of child objects for the current node
col or Specifies the color for the bookmark
doc The document object for the bookmark
name The text string appearing in the navigational panel
open Determines if children are shown
parent The parent bookmark
styl e Font style
TABLE 10.7 Bookmark Methods
Method Description
createChi l d Creates a new child bookmark
execute Executes the MouseUpaction for the bookmark
i nsertChi l d Inserts a bookmark as a new child for this bookmark (this
may be used to move existing bookmarks)
remove Removes the bookmark and all its children
setActi on Sets a MouseUpaction for the bookmark
Acrobat JavaScript Scripting Guide 173
Modifying the User Interface
Adding Navigation to PDF Documents
10
The following code creates a bookmark that displays a greeting when clicked. Note that the
omission of the nI ndex value means that it is placed at position 0 in the chi l drenarray:
myRoot . cr eat eChi l d( "myBookmar k", "app. al er t ( Hel l o! ) ; ") ;
The following code adds a bookmark called grandChi l das a child of myBookmark, :
var cur r ent = myRoot . chi l dr en[ 0] ;
cur r ent . cr eat eChi l d( "gr andChi l d") ;
Suppose that you would like to move grandChi l dso that it becomes a child of the root.
Invoke the root bookmarks i nsertChi l dmethod, and provide a reference to
grandChi l das a parameter:
var gr andChi l d = myRoot . chi l dr en[ 0] . chi l dr en[ 0] ;
myRoot . i nser t Chi l d( gr andChi l d, 1) ;
Managing Bookmarks
You can use Acrobat JavaScript to change the name, col or, and styl eproperties of a
bookmark. Note that the styl eproperty is an integer: 0 means normal, 1 means italic, 2
means bold, and 3 means bold-italic. The code below changes the name to NewName, the
color to red, and the font style to bold:
var myRoot = t hi s. bookmar kRoot ;
var myChi l d = myRoot . chi l dr en[ 0] ;
myChi l d. name = "New Name";
myChi l d. col or = col or . r ed;
myChi l d. st yl e = 2;
In addition to adding new or existing bookmarks as you learned in Creating Bookmarks,
you may also delete a bookmark and its children by invoking its removemethod. The
following line of code removes all bookmarks from the document:
t hi s. bookmar kRoot . r emove( ) ;
Creating a Bookmark Hierarchy
Because of the tree structure associated with bookmarks, it is possible to construct a
hierarchy of bookmarks; a child of a bookmark represents a subsection of the section
represented by that bookmark. To create a hierarchy, first add bookmarks to the root, then
to the children of the root, and recursively to their children.
The following code creates bookmarks A, B, C. Each section has 3 children. Child Ahas
children A0, A1, and A2. Child Bhas children B0, B1, and B2. Child Chas children C0, C1,
and C2:
Modifying the User Interface
Adding Navigation to PDF Documents
10
174 Acrobat JavaScript Scripting Guide
var myRoot = t hi s. bookmar kRoot ;
myRoot . cr eat eChi l d( "A") ;
myRoot . cr eat eChi l d( {cName: "B", nI ndex: 1}) ;
myRoot . cr eat eChi l d( {cName: "C", nI ndex: 2}) ;
f or ( var i = 0; i < myRoot . chi l dr en. l engt h; i ++) {
var chi l d = myRoot . chi l dr en[ i ] ;
f or ( var j = 0; j < 3; j ++) {
var name = chi l d. name + j ;
chi l d. cr eat eChi l d( {cName: name, nI ndex: j }) ;
}
}
To print out the hierarchy to the console, you can keep track of levels as shown in the
following code. Note its recursive nature:
f unct i on DumpBookmar k( bm, nLevel ) {
/ / bui l d i ndent s t o i l l ust r at e t he l evel
var s = "";
f or ( var i = 0; i < nLevel ; i ++) s += " ";
/ / pr i nt out t he bookmar k s name:
consol e. pr i nt l n( s + "+- " + bm. name) ;
/ / r ecur si vel y pr i nt out t he bookmar k s chi l dr en:
i f ( bm. chi l dr en ! = nul l )
f or ( var i = 0; i < bm. chi l dr en. l engt h; i ++)
DumpBookmar k( bm. chi l dr en[ i ] , nLevel +1) ;
}
/ / open t he consol e t o begi n:
consol e. cl ear ( ) ; consol e. show( ) ;
/ / r ecur si vel y pr i nt out t he bookmar k t r ee
DumpBookmar k( t hi s. bookmar kRoot , 0) ;
Acrobat JavaScript Scripting Guide 175
Modifying the User Interface
Adding Navigation to PDF Documents
10
Links
Acrobat JavaScript provides support for the addition, customization, or removal of links
within PDF documents. These links may be used to access URLs, file attachments, or
destinations within the document.
The doc object contains methods for adding, retrieving, and removing links. These include
the methods listed below in Table 10.8. This is used in conjunction with the l i nk object,
which contains properties as well as a setActi onmethod for customizing the
appearance and behavior of a given link. Its properties are listed below in Table 10.9.
In addition, the appobject contains a property called openI nPl ace, which can be used
to specify whether cross-document links are opened in the same window or in a new one.
TABLE 10.8 Doc Object Link Methods
Method Description
addLi nk Adds a new link to a page
addWebl i nks Converts text instances to Web links with URL actions
getLi nks Retrieves the links within a specified area on a page
getURL Opens a web page
gotoNamedDest Goes to a named destination within the document
removeLi nks Removes the links within a specifed area on a page
removeWebl i nks Removes Web links created with the Acrobat user
interface
TABLE 10.9 Link Properties
Property Description
borderCol or The border color of the bounding rectangle
borderWi dth The border width of the surrounding rectangle
hi ghl i ghtMode The visual effect when the user clicks the link
rect The rotated user space coordinates of the link
Modifying the User Interface
Adding Navigation to PDF Documents
10
176 Acrobat JavaScript Scripting Guide
Creating Links
If a PDF document contains text beginning with http:// such as http://myURL.com, you
may convert all such instances to links with URL actions by invoking the doc objects
addWebl i nks method. The method returns an integer representing the number of text
instances converted, as shown in the code below:
var number Of Li nks = t hi s. addWebl i nks( ) ;
consol e. pr i nt l n( " Conver t ed " + number Of Li nks + " l i nks. " ) ;
To add a single link to a PDF document, first invoke the doc objects addLi nk method,
and then customize the returned l i nkobjects properties. The addLi nk method requires
two parameters: the page number and the coordinates, in rotated user space, of the
bounding rectangle. In the following example, navigational links are added to the lower left
and right corners of each page in the document. The left link opens the previous page, and
the right link opens the next page:
var l i nkWi dt h = 36, l i nkHei ght = 18;
f or ( var i = 0; i < t hi s. numPages; i ++)
{
/ / Cr eat e t he coor di nat es f or t he l ef t l i nk:
var l Rect = [ 0, l i nkHei ght , l i nkWi dt h, 0] ;
/ / Cr eat e t he coor di nat es f or t he r i ght l i nk:
var cr opBox = t hi s. get PageBox( "Cr op", i ) ;
var of f set = cr opBox[ 2] - cr opBox[ 0] - l i nkWi dt h;
var r Rect = [ of f set , l i nkHei ght , l i nkWi dt h + of f set , 0] ;
/ / Cr eat e t he Li nk obj ect s:
var l ef t Li nk = t hi s. addLi nk( i , l Rect ) ;
var r i ght Li nk = t hi s. addLi nk( i , r Rect ) ;
/ / Cal cul at e t he pr evi ous and next page number s:
var next Page = ( i + 1) %t hi s. numPages;
var pr evPage = i - 1;
i f ( pr evPage < 0) pr evPage = t hi s. numPages - 1;
/ / Set t he l i nk act i ons t o go t o t he pages:
l ef t Li nk. set Act i on( "t hi s. pageNum= " + pr evPage) ;
r i ght Li nk. set Act i on( "t hi s. pageNum= " + next Page) ;
/ / Cust omi ze t he l i nk appear ance:
l ef t Li nk. bor der Col or = col or . r ed;
l ef t Li nk. bor der Wi dt h = 1;
r i ght Li nk. bor der Col or = col or . r ed;
r i ght Li nk. bor der Wi dt h = 1;
}
Acrobat JavaScript Scripting Guide 177
Modifying the User Interface
Adding Navigation to PDF Documents
10
Defining the Appearance of a Link
The previous example contained code that set the appearance of the bounding rectangle
for the links through their borderCol or and borderWi dthproperties. You may also
specify how the link will appear when it is clicked by setting its hi ghl i ghtModeproperty
to one of four values: None, Outl i ne, I nvert (the default), or Push.
For example, the following code sets the border color to blue, the border thickness to 2,
and the highlight mode to Outl i nefor myLi nk:
myLi nk. bor der Col or = col or . bl ue;
myLi nk. bor der Wi dt h = 2;
myLi nk. hi ghl i ght Mode = "Out l i ne";
Editing Links
In addition to adding links and modifying their appearance, you may also remove links
from a document. To remove a known link object from a given page, retrieve its bounding
rectangle coordinates and invoke the doc objects removeLi nks method. In the
following example, myLi nkis removed from page 2 of the document:
var l i nkRect = myLi nk. r ect ;
t hi s. r emoveLi nks( 2, l i nkRect ) ;
To remove all links from the document, simply use the crop box for each page, as shown in
the code below:
f or ( var page = 0; page < t hi s. numPages; page++)
{
var box = t hi s. get PageBox( "Cr op", page) ;
t hi s. r emoveLi nks( page, box) ;
}
Creating Links from URLs
To open a web page for a given link, invoke the l i nkobjects setActi onmethod, and
pass in a script containing a call to the doc objects getURL method.
For example, suppose you have created a l i nk object named myLi nk. The following
code opens http://myWebPage.com:
myLi nk. set Act i on( "t hi s. get URL( ' ht t p: / / myWebPage. com' ) ") ;
Linking to File Attachments
To open a file attachment, embed a JavaScript in the call to the l i nkobjects setActi on
method. The script contains a call to the appobjects openDoc method.
The following example opens myDoc. pdf when myLi nkis clicked:
myLi nk. set Act i on( "app. openDoc( ' / C/ myDoc. pdf ' ) ; ") ;
Modifying the User Interface
Adding Navigation to PDF Documents
10
178 Acrobat JavaScript Scripting Guide
Removing Web Links
To remove Web links that were authored in Acrobat, invoke the doc objects
removeWebl i nks method. It accepts two optional parameters: nStart and nEnd
represent the beginning and end of an inclusive range of page numbers. The following
examples illustrate how to remove Web links from different page ranges in the document:
/ / r emove t he Web l i nks f r ompages 2 t hr ough 5:
t hi s. r emoveWebl i nks( {nSt ar t : 2, nEnd: 5}) ;
/ / r emove t he Web l i nks f r ompage 7
t hi s. r emoveWebl i nks( {nSt ar t : 7}) ;
/ / r emove t he Web l i nks f r ompages 0 t hr ough 7:
t hi s. r emoveWebl i nks( {nEnd: 7}) ;
/ / r emove al l t he Web l i nks i n t he document :
t hi s. r emoveWebl i nks( ) ;
Using Destinations
To go to a named destination within a document, embed a JavaScript in the call to the
l i nkobjects setActi onmethod. The script contains a call to the doc objects
gotoNamedDest method.
The following example goes to the destination named as Chapter5in the current
document when myLi nkis clicked:
myLi nk. set Act i on( "t hi s. got oNamedDest ( ' Chapt er 5' ) ; ") ;
Using Actions for Special Effects
Thumbnails, bookmarks, links, and other objects have actions associated with them, and
you may use Acrobat JavaScript to customize their behavior. For example, you can use
them to display messages, jump to destinations in the same document or any other, open
attachments, open Web pages, execute menu commands, or perform a variety of other
tasks.
Adding Actions
As you learned earlier, you may associate a thumbnail with a PageOpenevent, and
associate bookmarks and links with MouseUpevents.
You may use Acrobat JavaScript to customize the actions associated with a thumbnail by
invoking the doc objects setPageActi onmethod. To customize the actions associated
with bookmarks and links, create a string containing Acrobat JavaScript code and pass it to
the objects setActi onmethod. In the examples shown below, a greeting is displayed
when a thumbnail, bookmark, and link are clicked:
Acrobat JavaScript Scripting Guide 179
Modifying the User Interface
Adding Navigation to PDF Documents
10
/ / Open act i on f or t humbnai l :
t hi s. set PageAct i on( 2, "Open", "app. al er t ( ' Hel l o! ' ) ; ") ;
/ / MouseUp act i ons f or bookmar k and l i nk:
myBookmar k. set Act i on( "app. al er t ( ' Hel l o! ' ) ; ") ;
myLi nk. set Act i on( "app. al er t ( ' Hel l o! ' ) ; ") ;
Action Types
The actions applied to navigational components represent a small portion of the possible
events that may be customized. A complete list of event types and the actions with which
they are associated is shown below in Table 10.10:
TABLE 10.10 Action Types and Associated Events
Action Type Event Names
App I ni t
Batch Exec
Bookmark MouseUp
Consol e Exec
Doc Di dPri nt, Di dSave, Open, Wi l l Cl ose,
Wi l l Pri nt, Wi l l Save
External Exec
Fi el d Bl ur, Cal cul ate, Focus, Format, Keystroke,
MouseDown, MouseEnter, MouseExi t,
MouseUp, Val i date
Li nk MouseUp
Menu Exec
Page Open, Cl ose
Screen I nVi ew, OutVi ew, Open, Cl ose, Focus, Bl ur,
MouseUp, MouseDown, MouseEnter,
MouseExi t
Modifying the User Interface
Adding Navigation to PDF Documents
10
180 Acrobat JavaScript Scripting Guide
Type of Triggers
The event names shown above in Table 10.10 represent the types of triggers that initiate
the actions associated with events. They are described below in Table 10.11.
TABLE 10.11 Trigger Descriptions
Trigger Description
I ni t Acrobat or Adobe Reader starts
Exec Batch sequence starts
Di dPri nt After document has printed
Di dSave After document has saved
Open When the document is opened
Cl ose New page is opened or document is closed
Wi l l Cl ose Just before the document is closed
Wi l l Pri nt Just before the document is printed
Wi l l Save Just before the document is saved
Bl ur Just as the field loses focus
Cal cul ate A calculation is required for a field
Focus After MouseDownand before MouseUp
Format After dependent Cal cul ateevents occurs
Keystroke Keystroke in textbox or combobox, or item is selected in
combobox or listbox
MouseDown Mouse button is down
MouseUp Mouse button has been released
MouseEnter Mouse enters a field or screen rectangle
MouseExi t Mouse exits a field or screen rectangle
Val i date After value has been committed to a field
I nVi ew New page comes into view
OutVi ew Old page leaves view
Acrobat JavaScript Scripting Guide 181
Modifying the User Interface
Adding Navigation to PDF Documents
10
Highlighting Form Fields and Navigational Components
You can use Acrobat JavaScript to customize the actions associated with buttons, links, and
bookmarks so that they change their appearance after the user has clicked on them.
For a button, which is a field, you can invoke its hi ghl i ght property, which allows you to
specify how the button appears once it has been clicked. There are four choices, as shown
below in Table 10.12:
For example, the following code makes the button appear pushed when clicked:
/ / set t he hi ghl i ght mode t o push
var f = t hi s. get Fi el d( "myBut t on") ;
f . hi ghl i ght = hi ghl i ght . p;
As you learned earlier, the l i nkobject also has a hi ghl i ght property.
There are other ways in which you can creatively address the issue of highlighting. For
example, you can change the background color of the button when clicked, by including a
line of code in the script passed into its setActi onmethod. In the following example, the
button displays a greeting and changes its background color to blue when the mouse
enters its area:
var scr i pt = "app. al er t ( ' Hel l o! ' ) ; ";
scr i pt += "var myBut t on = t hi s. get Fi el d( ' myBut t on' ) ; ";
scr i pt += "myBut t on. f i l l Col or = col or . bl ue; ";
f . set Act i on( "MouseEnt er ", scr i pt ) ;
This idea can be applied to the bookMark objects col or property, as well as the l i nk
objects borderCol or property. In both cases, similar code to that shown in the example
above can be used in the scripts passed into their setActi onmethods.
For bookMark objects, you may additionally consider changing the text or font style
through its nameand styl eproperties. For example, the following code adds the word
VI SI TEDto myBookmark and changes the font style to bold:
myBookmar k. name += " - VI SI TED") ;
myBookmar k. st yl e = 2;
TABLE 10.12 Button Appearance
Type Keyword
none hi ghl i ght. n
i nvert hi ghl i ght. i
push hi ghl i ght. p
outl i ne hi ghl i ght. o
Modifying the User Interface
Adding Navigation to PDF Documents
10
182 Acrobat JavaScript Scripting Guide
Setting Up a Presentation
There are two viewing modes for Acrobat and Adobe Reader: full screen mode and regular
viewing mode. Full screen mode is often appropriate for presentations, since PDF pages
can fill the entire screen with the menu bar, toolbar, and window controls hidden.
It is possible to use Acrobat JavaScript to customize the viewing mode when setting up
presentations. The appobjects ful l Screenproperty, as well as the app. medi a
objects wi ndowTypeproperty may be used to set the viewing mode.
Defining the Initial View in Full Screen View
To cause Acrobat and Adobe Reader to display in full screen mode, you may include the
following statement in a document-level script triggered when the document is opened, or
in an application-level script triggered when the application is first started:
app. f ul l scr een = t r ue;
Defining an Initial View
In addition to specifying whether the full screen or regular viewing mode will be used, you
may also use Acrobat JavaScript to set up the document view. You can customize the initial
view in terms of magnification, page layout, application and document viewing
dimensions, the initial page to which the document opens, and whether parts of the user
interface will be visible.
The doc objects l ayout property allows you to specify page layout by assigning one of
the following values:
Si ngl ePage
OneCol umn
TwoCol umnLeft
TwoCol umnRi ght
TwoPageLeft
TwoPageRi ght
To set up the dimensions of the various view windows, assign a rect value to one of the
following doc object properties:
i nnerAppWi ndowRect: the inner application window (excludes title bar, border, etc)
i nnerDocWi ndowRect: the inner document window
outerAppWi ndowRect: the outer application window
outerDocWi ndowRect: the outer document window
pageWi ndowRect: the page view window for the document content
To set up the magnification, assign a value to the doc objects zoomproperty. For example,
the following code sets up a magnification of 125%:
t hi s. zoom= 125;
Acrobat JavaScript Scripting Guide 183
Modifying the User Interface
Adding Navigation to PDF Documents
10
You can also set the zoom type by assigning one of the settings, shown below in
Table 10.13, to the doc objects zoomtypeproperty:
The following example sets the zoom type of the document to fit the width:
t hi s. zoomType = zoomt ype. f i t W;
To specify the page to which the document initially opens, set the doc objects pageNum
property. If the following code is included in the script used in the document Openevent,
the document automatically opens to page 30:
t hi s. pageNum= 30;
Finally, you may choose whether menu items and toolbar buttons will be visible by
invoking the following methods of the appobject:
hi deMenuI tem: removes a specific menu item
hi deTool barButton: removes a specific toolbar button
For example, if the following code is placed in a folder-level script, the "Hand" icon is
removed when Acrobat or Adobe Reader is started:
app. hi deTool bar But t on( "Hand") ;
TABLE 10.13 ZoomType Settings
Zoom Type Property Value
NoVary zoomtype. none
Fi tPage zoomtype. fi tP
Fi tWi dth zoomtype. fi tW
Fi tHei ght zoomtype. fi tH
Fi tVi si bl eWi dth zoomtype. fi tV
Preferred zoomtype. pref
Refl owWi dth zoomtype. refW
Modifying the User Interface
Adding Navigation to PDF Documents
10
184 Acrobat JavaScript Scripting Guide
Adding Page Transitions
You may use Acrobat JavaScript to customize how page transitions occur for any pages
within a document. This is accomplished through the doc objects
setPageTransi ti ons and getPageTransi ti ons methods.
The setPageTransi ti ons method accepts three parameters:
nStart: the zero-based index of the beginning page
nEnd: the zero-based index of the last page
aTrans: a page transition array containing three values:
nDurati on: the time a page is displayed before automatically changing
cTransi ti on: the name of the transition to be applied
nTransDurati on: the duration in seconds of the transition effect
The name of the transition to be applied can be chosen from a comprehensive list made
available through the ful l screenobjects transi ti ons property. To obtain the list,
type the following code into the Console:
consol e. pr i nt l n( "[ " + app. f s. t r ansi t i ons + "] ") ;
In addition, you may set up a default page transition through the ful l screenobjects
defaul tTransi ti onproperty.
In the following example, page transitions are applied to pages 2-5. Each page displays for
10 seconds, and then an automatic transition occurs for one second:
t hi s. set PageTr ansi t i ons( {
nSt ar t : 2,
nEnd: 5,
aTr ans: {
nDur at i on: 10,
cTr ansi t i on: "Wi peLef t ",
nTr ansDur at i on: 1
}
}) ;
/ / Set t he vi ewi ng mode t o f ul l scr een
app. f ul l Scr een = t r ue;
Acrobat JavaScript Scripting Guide 185
Modifying the User Interface
Adding Navigation to PDF Documents
10
Numbering Pages
You may use Acrobat JavaScript to customize the page numbering schemes used
throughout a document. There are three numbering formats:
decimal (often used for normal page ranges)
roman (often used for front matter such as a preface)
alphabetic (often used for back matter such as appendices)
The doc objects getPageLabel and setPageLabel s methods can be used to control
and customize the appearance of numbering schemes within a PDF document.
The getPageLabel method accepts the zero-based page index and returns a string
containing the label for a given page.
The setPageLabel s method accepts two parameters: nPageis the zero-based index for
the page to be labeled, and aLabel is an array of three values representing the numbering
scheme. If aLabel is not supplied, the method removes page numbering for the specified
page and any others up to the next specified label.
The aLabel array contains three required values:
cStyl e: the style of page numbering as shown below in Table 10.14
cPrefox: the string used to prefix the numeric portion of the page label
nStart: the ordinal with which to start numbering the pages
TABLE 10.14 Page Numbering Style Values
cStyle value Description
D Decimal numbering
R Upper case Roman numbering
r Lower case Roman numbering
A Upper case alphabetic numbering
a Lower case alphabetic numbering
Modifying the User Interface
Adding Navigation to PDF Documents
10
186 Acrobat JavaScript Scripting Guide
For example, the code shown below labels 10 pages within a document using the following
scheme: i, ii, ii, 1, 2, 3, 4, 5, Appendix-A, Appendix-B:
/ / Pages 0- 2 wi l l have l ower case r oman numer al s i , i i , i i i :
t hi s. set PageLabel s( 0, [ "r ", "", 1] ) ;
/ / Pages 3- 7 wi l l have deci mal number i ng 1- 5:
t hi s. set PageLabel s( 3, [ "D", "", 1] ) ;
/ / Pages 8- 9 wi l l have al phabet i c number i ng:
t hi s. set PageLabel s( 8, [ "A", "Appendi x- ", 1] ) ;
/ / The page l abel s wi l l be pr i nt ed t o t he consol e:
var l abel s = t hi s. get PageLabel ( 0) ;
f or ( var i =1; i <t hi s. numPages; i ++)
l abel s += ", " + t hi s. get PageLabel ( i ) ;
consol e. pr i nt l n( l abel s) ;
It is also possible to remove a page label by omitting the aLabel parameter, as shown in
the code below (which assumes the existence of the labels in the previous example:
/ / The l abel s f or pages 3- 7 wi l l be r emoved:
t hi s. set PageLabel s( 3) ;
Creating Buttons
Though buttons are normally considered form fields, you can add them to any document. A
button may be used for a variety of purposes, such as opening files, playing sound or movie
clips, or submitting data to a web server. As you learned earlier, you can place text and
images on a button, making it a user-friendly interactive portion of your document. To
show or hide portions of graphic buttons, use the MouseEnter and MouseExi t events
or other types of control mechanisms to manage the usage of the button fields
buttonSetI conmethod.
For example, the following code shows one icon when the mouse enters the button field,
and a different icon when the mouse exits:
var scr i pt = "var f = t hi s. get Fi el d( ' myBut t on' ) ; ";
scr i pt += "f . but t onSet I con( t hi s. get I con( ' oneI con' ) ; ";
myBut t on. set Act i on( "MouseEnt er ", scr i pt ) ;
scr i pt = "var f = t hi s. get Fi el d( ' myBut t on' ) ; ";
scr i pt += "f . but t onSet I con( t hi s. get I con( ' ot her I con' ) ; ";
myBut t on. set Act i on( "MouseExi t ", scr i pt ) ;
Acrobat JavaScript Scripting Guide 187
Modifying the User Interface
Working with PDF Layers
10
Working with PDF Layers
About PDF Layers
PDF layers are components of content that may occupy the same space as other
components. Multiple components may be visible or invisible depending on their settings,
and may be used to support the display, navigation, and printing of layered PDF content by
various applications. It is possible to edit the properties of layers, lock layers, add navigation
to them, merge or flatten layers, and combine PDF layered documents. PDF layers are
supported through the usage of Acrobat JavaScript Optional Content Group (OCG) objects.
To obtain an array of the OCGobjects for a given page in the document, invoke the doc
objects getOCGs method. The following code obtains the array of OCG objects contained
on page 3 of the document:
var ocgAr r ay = t hi s. get OCGs( 3) ;
Navigating with Layers
Since information can be stored in different layers of a PDF document, navigational controls
can be customized within different layers, whose visibility settings may be dynamically
customized so that they are tied to context and user interaction. For example, if the user
selects a given option, a set of navigational links belonging to a corresponding optional
content group may be shown.
In addition, it is possible to determine the order in which layers are displayed in the user
interface by invoking the doc objects getOCGOrder and setOCGOrder methods. In
the following example, the display order of all the layers is reversed:
var ocgOr der = t hi s. get OCGOr der ( ) ;
var newOr der = new Ar r ay( ) ;
f or ( var i =0; i <ocgOr der . l engt h; i ++)
newOr der [ i ] = ocgOr der [ ocgOr der . l engt h - i - 1] ;
t hi s. set OCGOr der ( newOr der ) ;
Modifying the User Interface
Working with PDF Layers
10
188 Acrobat JavaScript Scripting Guide
Editing the Properties of PDF Layers
The OCGobject provides properties that can be used to determine whether the objects
default state should be on or off, whether its intent should be for viewing or design
purposes, whether it should be locked, the text string seen in the user interface, and the
current state. The properties are shown below in Table 10.15:
The i ni tStateproperty can be used to set the default state for an optional content
group. In the following example, myLayer is set to onby default:
myLayer . i ni t St at e = t r ue;
The i ntent property, which is an array of values, can be used to define the intent of a
particular optional content group. There are two possible values used in the array: Vi ew
and Desi gn. A Desi gnlayer is created for informational purposes only, and does not
affect the visibility of content. Its purpose is to represent a document designers structural
organization of artwork. The Vi ewlayer is intended for interactive use by document
consumers. If Vi ewis used, the visibility of the layer is affected. In the following example,
the intent of all the OCGobjects in the document is set to both values:
var ocgs = t hi s. get OCGs( ) ;
f or ( var i =0; i <ocgs. l engt h; i ++)
ocgs[ i ] . i nt ent = [ "Vi ew", "Desi gn"] ;
The l ockedproperty is used to determine whether a given layer can be toggled through
the user interface. In the following example, myLayer is locked, meaning that it cannot be
toggled through the user interface:
myLayer . l ocked = t r ue;
The stateproperty represents the current on/off state for a given OCG. In the following
example, all the OCGs are turned on:
var ocgs = t hi s. get OCGs( ) ;
f or ( var i =0; i <ocgs. l engt h; i ++)
ocgs[ i ] . st at e = t r ue;
TABLE 10.15 OCG Properties
Property Description
i ni tState Determines whether the OCGobject is on or off by
default
i ntent The intent of the OCGobject (View or Design)
l ocked Whether the on/off state can be toggled through the user
interface
name The text string seen in the user interface for the OCG
object
state The current on/off state of the OCGobject
Acrobat JavaScript Scripting Guide 189
Modifying the User Interface
Working with PDF Layers
10
The nameproperty represents the text string seen in the user interface that is used to
identify layers. In the following example, the WatermarkOCG is toggled:
var ocgs = t hi s. get OCGs( ) ;
f or ( var i =0; i <ocgs. l engt h; i ++)
i f ( ocgs[ i ] . name == "Wat er mar k")
ocgs[ i ] . st at e = ! ocgs[ i ] . st at e;
Merging Layers
You can use Acrobat JavaScript to merge layers in a PDF document. A merged layer (the
source layer) will acquire the properties of the layer into which they are merged (the target
layer). In the following example, sourceLayer is merged into targetLayer:
sour ceLayer . i ni t St at e = t ar get Layer . i ni t St at e;
sour ceLayer . i nt ent = t ar get Layer . i nt ent ;
sour ceLayer . l ocked = t ar get Layer . l ocked;
sour ceLayer . name = t ar get Layer . name;
sour ceLayer . st at e = t ar get Layer . st at e;
Flattening PDF Layers
Flattening layers means that they will be consolidated. This operation is done through the
Layers tab in the user interface.
Combining PDF Layered Documents
Multiple PDF documents containing layers can be combined while preserving the layered
information. When doing this, it may be necessary to rearrange the order of the merged
OCG arrays. To accomplish this, obtain the OCG order arrays for each document, and merge
them into a new array in the merged document. In the example shown below,
sour ce1. pdf and sour ce2. pdf are combined into t ar get . pdf . It is assumed that there are
no common layers between the two documents:
Modifying the User Interface
Working with PDF Layers
10
190 Acrobat JavaScript Scripting Guide
/ / Open t he sour ce document s:
var sour ce1 = app. openDoc( "/ C/ sour ce1. pdf ") ;
var sour ce2 = app. openDoc( "/ C/ sour ce2. pdf ") ;
/ / Obt ai n t he OCG or der ar r ay f or each sour ce document :
var mer gedOCGAr r ay = new Ar r ay( ) ;
var sour ce1OCGAr r ay = sour ce1. get OCGOr der ( ) ;
var sour ce2OCGAr r ay = sour ce2. get OCGOr der ( ) ;
/ / Mer ge t he OCG or der ar r ays i nt o t he t ar get ar r ay:
f or ( var i =0; i <sour ce1OCGAr r ay. l engt h; i ++)
mer gedOCGAr r ay[ i ] = sour ce1OCGAr r ay[ i ] ;
var of f set = sour ce1OCGAr r ay. l engt h;
f or ( var j =0; j <sour ce2OCGAr r ay. l engt h; j ++)
mer gedOCGAr r ay[ of f set + j ] = sour ce2OCGAr r ay[ j ] ;
/ / Cr eat e t he t ar get document :
var t ar get = app. newDoc( "/ C/ t ar get . pdf ") ;
/ / I nser t sour ce1. pdf :
t ar get . i nser t Pages( {
nPage : - 1,
cPat h : "/ c/ sour ce1. pdf ",
}) ;
/ / I nser t sour ce2. pdf :
t ar get . i nser t Pages( {
nPage : t ar get . numPages,
cPat h : "/ c/ sour ce2. pdf ",
}) ;
/ / Set t he OCG or der ar r ay i n t he t ar get document
t ar get . set OCGOr der ( mer gedOCGAr r ay) ;
/ / Save t he t ar get document :
t ar get . saveAs( {
"/ c/ t ar get . pdf ") ;
}) ;
/ / Cl ose t he t ar get document wi t hout not i f yi ng t he user :
t ar get . cl oseDoc( t r ue) ;
Acrobat JavaScript Scripting Guide 191
11
Search and Index Essentials
Introduction
This chapter will enable you to customize and extend searching operations for PDF
document content and metadata, as well as indexing operations. The principal Acrobat
JavaScript objects used in searching and indexing are the search, catal og, and i ndex
objects. You will learn how to use these objects to accomplish the goals listed below.
Chapter Goals
At the end of this chapter, you will be able to:
Use Acrobat JavaScript to search for text in one or more PDF documents.
Customize searching to perform advanced queries.
Customize indexing of PDF documents.
Use JavaScript to read and search XMP metadata.
Contents
Topics
Searching for Text in PDF Documents
Indexing Multiple PDF Documents
Searching Metadata
Search and Index Essentials
Searching for Text in PDF Documents
11
192 Acrobat JavaScript Scripting Guide
Searching for Text in PDF Documents
Introduction
Acrobat JavaScript provides a static searchobject, which provides powerful searching
capabilities that may be applied to PDF documents and indexes. Its properties and
methods are described below in Table 11.1 and Table 11.2.
TABLE 11.1 Search Properties
Property Description
attachments Searches PDF attachments along with base
document
avai l abl e Determines if searching is possible
docI nfo Searches document metadata information
docText Searches document text
docXMP Searches document XMP metadata
bookmarks Searches document bookmarks
i gnoreAccents Ignores accents and diactrics in search
i gnoreAsi anCharacterWi dth Matches Kana characters in query
i ndexes Obtains all accessible i ndex objects
j pegExi f Searches EXIF data in associated JPEG images
markup Searches annotations
matchCase Determines whether query is case-sensitive
matchWhol eWord Finds only occurrences of complete words
maxDocs Maximum number of documents returned
proxi mi ty Uses proximity in results ranking for AND
clauses
proxi mi tyRange Range of proximity search in number of
words
refi ne Uses previous results in query
stem Uses word stemming in searches
Acrobat JavaScript Scripting Guide 193
Search and Index Essentials
Searching for Text in PDF Documents
11
Finding Words in an PDF Document
The searchobjects query method is used to search for text within a PDF document. It
accepts three parameters:
cQuery: the text for which to search
cWhere: where to search for the text:
Acti veDoc: search within the active document
Fol der: search within a specified folder
I ndex: search within a specified index
Acti veI ndexes: search within the active set of available indexes (the default)
cDI Path: path to folder or index used in search
Performing a Simple Search of a Document
The simplest type of search is applied to the text within the PDF document. For example,
the following code performs a case-insensitive search for the word Acrobat within the
current document:
sear ch. quer y( " Acr obat " ) ;
Using Advanced Search Options
You can set the searchobjects properties to use advanced searching options, which can
be used to determine how to match search strings, and whether to use proximity or
stemming.
To determine how the words in the search string will be matched, set the searchobjects
wordMatchi ngproperty to one of the following values:
wordMatchi ng Determines how words will be matched
(phrase, all words, any words, boolean query)
TABLE 11.2 Search Methods
Method Description
addI ndex Adds an index to the list of searchable indexes
getI ndexForPath Searches the index list according to a specified path
query Searches the document or index for specified text
removeI ndex Removes an index from the list of searchable indexes
TABLE 11.1 Search Properties
Property Description
Search and Index Essentials
Searching for Text in PDF Documents
11
194 Acrobat JavaScript Scripting Guide
MatchPhrase: match the exact phrase
MatchAl l Words: match all the words without regard to the order in which they
appear
MatchAnyWord: match any of the words in the search string
Bool eanQuery: perform a boolean query for multiple-document searches (the
default)
For example, the following code matches the phrases "My Search" or "SearchMy":
sear ch. wor dMat chi ng = "Mat chAl l Wor ds";
sear ch. quer y( "My Sear ch") ;
To determine whether proximity is used in searches involving multiple documents or index
definition files, set the searchobjects wordMatchi ngproperty to MatchAl l Words
and set its proxi mi ty property to true. In the example below, all instances of the words
My and Searchthat are not separated by more than 900 words will be listed in the search:
sear ch. wor dMat chi ng = "Mat chAl l Wor ds";
sear ch. pr oxi mi t y = t r ue;
sear ch. quer y( "My Sear ch") ;
To use stemming in the search, set the searchobjects stemproperty to true. For
example, the following search lists words that begin with "run", such as "running" or "runs":
sear ch. st em= t r ue;
sear ch. quer y( "r un") ;
Acrobat JavaScript Scripting Guide 195
Search and Index Essentials
Searching for Text in PDF Documents
11
Searching Across Multiple PDF Documents
Searching all PDF Files in a Specific Location
To search all the PDF files within a folder, set the cWhereparameter in the search
objects query method to Fol der. In the following example, all documents in
/ C/ MyFol der will be searched for the word "Acrobat":
sear ch. quer y( "Acr obat ", "Fol der ", "/ C/ MyFol der ") ;
Using Advanced Search Options for Multiple Document Searches
In addition to the advanced options for matching phrases, using stemming, and using
proximity, it is also possible to specify whether the search should be case-sensitive,
whether to match whole words, set the maximum number of documents to be returned as
part of a query, and whether to refine the results of the previous query.
To specify that a search should be case sensitive, set the searchobjects matchCase
property to true. For example, the following code matches "Acrobat" but not "acrobat":
sear ch. mat chCase = t r ue;
sear ch. quer y( "Acr obat ", "Fol der ", "/ C/ MyFol der ") ;
To specify that the search should only identify occurrences of complete words, set the
searchobjects matchWhol eWordproperty to true. For example, the following code
matches "stick", but not "tick" or "sticky":
sear ch. mat chWhol eWor d = t r ue;
sear ch. quer y( "st i ck", "Fol der ", "/ C/ MyFol der ") ;
To set the maximum number of documents to be returned as part of a query, set the
searchobjects maxDocs property to the desired number (the default is 100). For
example, the following code limits the number of documents to be searched to 5:
sear ch. maxDocs = 5;
To refine the results of the previous query, set the searchobjects refi neproperty to
true, as shown in the following code:
sear ch. r ef i ne = t r ue;
Search and Index Essentials
Searching for Text in PDF Documents
11
196 Acrobat JavaScript Scripting Guide
Searching PDF Index Files
A PDF index file often covers multiple PDF files, and the time required to search an index is
much less than that required to search each of the corresponding individual PDF files.
To search a PDF index, set the cWhereparameter in the searchobjects query method
to I ndex. In the following example, myI ndex is searched for the word "Acrobat":
sear ch. quer y( "Acr obat ", "I ndex", "/ C/ MyI ndex. pdx") ;
Using Boolean Queries in Multiple Document Searches
Boolean queries may be applied to multiple PDF documents using the following
operations:
AND
OR
^(exclusive or)
NOT
For example, the phrase "Pari s ANDFrance" used in a search would return all
documents containing both the words Pari s and France.
The phrase "Pari s ORFrance" used in a search would return all documents containing
one or both of the words Pari s and France.
The phrase "Pari s ^France" used in a search would return all documents containing
exactly one (not both) of the words Pari s and France.
The phrase "Pari s NOTFrance" used in a search would return all documents
containing Pari s that do not contain the word France.
In addition, parentheses may be used. For example, the phrase "oneAND(twoOR
three)" would be equivalent to performing two searches: one using the statement "one
ANDtwo", followed by another using the statement "oneANDthree".
To specify that a boolean query will be used, be sure that the search objects
wordMatchi ng property is set to Bool eanQuery (which is the default).
Acrobat JavaScript Scripting Guide 197
Search and Index Essentials
Indexing Multiple PDF Documents
11
Indexing Multiple PDF Documents
It is possible to extend and customize indexes for multiple PDF documents using the
Acrobat JavaScript catal og, catal ogJ ob, and i ndex objects. These objects may be
used to build, retrieve, or remove indexes. The i ndex object represents a catal og-
generated index, contains a bui l dmethod that is used to create an index (and returns a
catal ogJ obobject containing information about the index), and has the properties
shown below in Table 11.3:
The catal ogobject may be used to manage indexing jobs and retrieve indexes. It
contains a getI ndex method for retrieving an index, a removemethod for removing a
pending indexing job, and properties containing information about indexing jobs.
Creating, Updating, or Rebuilding Indexes
To determine which indexes are available, use the searchobjects i ndexes property,
which contains an array of i ndex objects. For each object in the array, you can determine
its name by using its nameproperty. In the code below, the names and paths of all available
selected indexes are printed to the console:
var ar r = sear ch. i ndexes;
f or ( var i =0; i <ar r . l engt h; i ++)
{
i f ( ar r [ i ] . sel ect ed)
{
var st r = "I ndex[ " + i + "] = " + ar r [ i ] . name;
st r += "\ nPat h = " + ar r [ i ] . pat h;
consol e. pr i nt l n( st r ) ;
}
}
TABLE 11.3 Index Properties
Property Description
avai l abl e Indicates whether an index is available
name The name of the index
path The device-independent path of the index
sel ected Indicates whether the index will participate in the search
Search and Index Essentials
Indexing Multiple PDF Documents
11
198 Acrobat JavaScript Scripting Guide
To build an index, first invoke the catal ogobjects getI ndex method to retrieve the
i ndex object. This method accepts a parameter containing the path of the i ndex object.
Then invoke the i ndex objects bui l dmethod, which returns a catal ogJ obobject. The
method accepts two parameters:
cExpr: an Acrobat JavaScript expression executed once the build operation is
complete
bRebui l dAl l : indicates whether to perform a clean build in which the existing index
is first deleted and then completely built
Finally, the returned catal ogJ obobject contains three properties providing useful
information about the indexing job:
path: the device-independent path of the index
type: the type of indexing operation (Bui l d, Rebui l d, or Del ete)
status: the status of the indexing operation (Pendi ng, Processi ng, Compl eted,
or Compl etedWi thErrors)
In the code shown below, the index myI ndex is completely rebuilt, after which its status is
reported:
/ / Ret r i eve t he I ndex obj ect
var i dx = cat al og. get I ndex( "/ C/ myI ndex. pdx") ;
/ / Bui l d t he I ndex
var j ob = i dx. bui l d( "app. al er t ( I ndex bui l d ) ; ", t r ue) ;
/ / Conf i r mt he pat h of t he r ebui l t i ndex:
consol e. pr i nt l n( "Pat h of r ebui l t i ndex: " + j ob. pat h) ;
/ / Conf i r mt hat t he i ndex was r ebui l t :
consol e. pr i nt l n( "Type of oper at i on: " + j ob. t ype) ;
/ / Repor t t he j ob st at us
consol e. pr i nt l n( "St at us: " + j ob. st at us) ;
Acrobat JavaScript Scripting Guide 199
Search and Index Essentials
Searching Metadata
11
Searching Metadata
Using Acrobat JavaScript to Read and Search XMP Metadata
PDF documents contain document metadata in XML format, which includes information
such as the document title, subject, authors name, keywords, copyright information, date
modified, file size, and file name and location path.
To use Acrobat JavaScript to search a documents XMP metadata, set the searchobjects
docXMPproperty to true, as shown in the following code:
sear ch. docXMP = t r ue;
Search and Index Essentials
Searching Metadata
11
200 Acrobat JavaScript Scripting Guide
Acrobat JavaScript Scripting Guide 201
12
Security
Introduction
This chapter will introduce you to the various security options available through Acrobat
JavaScript. You will understand how to customize security in PDF documents by applying
passwords and digital signatures, certifying documents, encrypting files, adding security to
attachments, managing digital IDs and certificates, and customizing security policies.
Chapter Goals
At the end of this chapter, you will be able to:
Understand the Acrobat JavaScript security model supporting PDF documents.
Use Acrobat JavaScript to add, remove, and validate digital signatures in a PDF
document.
Use Acrobat JavaScript to apply passwords, security options, usage rights, and
encryption to PDF documents and attachments.
Use Acrobat JavaScript to create, use, and manage digital IDs and certificates.
Contents
Topics
Security Essentials
Digitally Signing PDF Documents
Adding Security to PDF Documents
Digital IDs and Certification Methods
Security
Security Essentials
12
202 Acrobat JavaScript Scripting Guide
Security Essentials
Acrobat JavaScript provides a number of objects that support security. These are managed
by the securi ty, securi tyPol i cy, and securi tyHandl er objects for managing
certificates, security policies, and signatures. The certi fi cate, di rectory,
si gnatureI nfo, and di rConnecti onobjects are used to manage digital signatures
and access the user certificates.
Methods for Adding Security to PDF Documents
The general procedures for applying various types of security to a PDF document are
described below. Details and examples are provided in the later sections of this chapter.
Passwords and Restrictions
The basic way to protect a document from unauthorized access is to encrypt it for a list of
authorized recipients using the doc objects encryptForReci pi ents method. This
essentially requires that the authorized recipients use a private key or credential to gain
access to it. Restrictions may be applied so that the recipients access to the document may
be controlled.
Certifying Documents
The author signature for a document is what makes modification detection and prevention
(mdp) possible. When this type of signature is applied, it is possible to certify the document,
which means that you will specify information about its contents and the types of changes
that are allowed in order for the document to remain certified.
To apply an author signature to a document, create an author signature field using the doc
objects addFi el dmethod. Then sign the field using the fi el dobjects
si gnatureSi gnmethod, in which you will provide parameters containing the security
handler, a si gnatureI nfoobject containing an mdpproperty value other than
al l owAl l , and a legal attest explaining why certain legal warnings are embedded in the
document. The si gnatureI nfoobject has properties common to all security handlers.
These properties are described below in Table 12.1:
TABLE 12.1 SignatureInfo Properties
Property Description
bui l dI nfo Software build and version for the signature
date Date and time of the signature
handl erName Security handler name specified in the Filter attribute
in the signature dictionary
handl erUserName Security handler name specified by handl erName
handl erUI Name Security handler name specified by handl erName
Acrobat JavaScript Scripting Guide 203
Security
Security Essentials
12
Encrypting Files Using Certificates
When you invoke the doc objects encryptForReci pi ents method, it encrypts the
document using the public key certificates of each recipient. The groups of recipients are
specified in the oGroups parameter, which is an array of Groupobjects, each of which
contains two properties: permi ssi ons and userEnti ti es. The userEnti ti es
property is an array of UserEnti ty objects (described below in Table 12.2), each of which
describes a user and their associated certificates, and is returned by a call to the
di rConnecti onobjects searchmethod. The associated certificates are represented in
a property containing an array of Certi fi cateobjects (described below in Table 12.3),
each of which contains read-only access to the properties of an X.509 public key certificate.
To obtain a group of recipients (the oGroups parameter mentioned above), you may
invoke the securi ty objects chooseReci pi entsDi al ogmethod, which opens a
dialog box prompting the user to choose a list of recipients.
l ocati on Physical location or hostname
mdp Modification detection and prevention setting
(al l owNone, al l owAl l , defaul t,
defaul tAndComments)
name Name of the user
numFi el dsAl tered Number of fields altered since the previous signature
numFi el dsFi l l edI n Number of fields filled in since the previous signature
numPagesAl tered Number of pages altered since the previous signature
numRevi si ons The number of revisions in the document
reason Reason for signing
revi si on Signature revision
status Validity status (4represents a completely valid
signature)
statusText String representation of signature status
subFi l ter Formats used for public key signatures
veri fyHandl erName Security handler used to validate signature
veri fyHandl erUI Name Handler specified by veri fyHandl erName
TABLE 12.1 SignatureInfo Properties
Property Description
Security
Security Essentials
12
204 Acrobat JavaScript Scripting Guide
TABLE 12.2 UserEntity Object Properties
Property Description
fi rstName the first name of the user
l astName the last name of the user
ful l Name the full name of the user
certi fi cates array of Certi fi cateobjects for the user
defaul tEncryptCert the preferred Certi fi cate
TABLE 12.3 Certificate Object Properties
Property Description
bi nary the raw bytes of the certificate
i ssuerDN the distinguished name of the user
keyUsage the value of the certificate key usage extension
MD5Hash the MD5 digest of the certificate
SHA1Hash the SHA1 digest of the certificate
seri al Number a unique identifier for the certificate
subj ectCN the common name of the signer
subj ectDN the distinguished name of the signer
usage purposes: end-user signing or encryption
ubri ghts an application Ri ghts object
Acrobat JavaScript Scripting Guide 205
Security
Digitally Signing PDF Documents
12
Security Policies
Security policies are common specifications that include the type of encryption, the
permission settings, and the password or public key to be used. You may create folder-level
scripts containing objects that reflect these policies. Security policies may be customized
through the use of securi tyPol i cy objects, which may be accessed and managed by
the securi ty objects getSecuri tyPol i ci es and chooseSecuri tyPol i cy
methods, as well as the doc objects encryptUsi ngPol i cy and encryptforAPS
methods.
Secure Forms
You can lock form fields by creating a script containing a call to the si gnaturefields
setLock method, and passing that script as the second parameter to the si gnature
fields setActi onmethod.
In addition, you may sign an embedded FDF data object by invoking its si gnatureSi gn
method, and subsequently validate the signature by invoking its si gnatureVal i date
method.
Digitally Signing PDF Documents
A digital signature contains identifying information about the person signing the
document. When applying an author signature (the first time a signature is applied to a
document), it is also possible to certify the document. This involves providing a legal attest
with regard to the documents contents and specifying the types of changes allowed for
the document in order for it to remain certified.
Signing a PDF Document
To sign a document, create a signature field, choose a security handler, and invoke the
fields si gnatureSi gnmethod, which accepts the following parameters:
oSi g: the security handler object
oI nfo: a si gnatureI nfoobject
cDI Path: the device-independent path to which the file will subsequently be saved
bUI : whether the security handler will display a user interface when signing
cLegal Attest: a string explaining legal warnings (for author signatures only)
The creation and usage of these parameters are explained below in the following sections:
The Security Handler Object, The SignatureInfo Object, and Applying the Signature.
Security
Digitally Signing PDF Documents
12
206 Acrobat JavaScript Scripting Guide
The Security Handler Object
To obtain a security handler (the oSi gparameter), invoke the securi ty objects
getHandl er method, which creates a new security handler engine, and accepts the
following parameters:
cName: the name of the security handler (contained in the securi ty objects
handl ers property)
bUI Engi ne: the existing engine associated with the Acrobat user interface
The following code illustrates how to set up signature validation whenever the document is
opened, lists all available security handlers, and selects the Adobe. PPKLi teengine
associated with the Acrobat user interface:
/ / Val i dat e si gnat ur es when t he document i s opened:
secur i t y. val i dat eSi gnat ur esOnOpen = t r ue;
/ / Li st al l t he avai l abl e si gnat ur e handl er s
f or ( var i =0; i <secur i t y. handl er s. l engt h; i ++)
consol e. pr i nt l n( secur i t y. handl er s[ i ] ) ;
/ / Sel ect t he Adobe. PPKLi t e engi ne wi t h Acr obat user i nt er f ace:
var ppkl i t e = secur i t y. get Handl er ( "Adobe. PPKLi t e", t r ue) ;
After obtaining the security handler, invoke the securi tyHandl er objects l ogi n
method, which makes it possible to access and select your digital ID, as shown in the
following code:
var oPar ams = {
passwor d: "myPasswor d",
cDI Pat h: "/ C/ si gnat ur es/ myName. pf x" / / di gi t al si gnat ur e pr of i l e
};
ppkl i t e. l ogi n( oPar ams) ;
The SignatureInfo Object
To create the oI nfoparameter for the signature fields si gnatureSi gnmethod, create
a generic object containing the properties as described above in Table 12.1. An example of
its usage when creating an author signature is given below:
var myI nf o = {
passwor d: "myPasswor d",
l ocat i on: "San J ose, CA",
r eason: "I amappr ovi ng t hi s document ",
cont act I nf o: "user Name@adobe. com",
appear ance: "Fancy",
mdp: "al l owNone" / / an mdp val ue i s needed f or aut hor si gnat ur es
};
Acrobat JavaScript Scripting Guide 207
Security
Digitally Signing PDF Documents
12
Applying the Signature
Now that the security handler and signature information have been created, you may
invoke the signature fields si gnatureSi gnmethod, as shown in the code below:
/ / Obt ai n t he si gnat ur e f i el d obj ect :
var f = t hi s. get Fi el d( "myAut hor Si gnat ur eFi el d") ;
/ / Si gn t he f i el d:
f . si gnat ur eSi gn(
oSi g: ppkl i t e,
oI nf o: myI nf o,
cDI Pat h: "/ C/ mySi gnedFi l e. pdf ",
bUI : t r ue,
cLegal At t est : "Font s ar e not embedded t o r educe f i l e si ze"
) ; / / end of si gnat ur e
Creating a New Signature Appearance
You may create a new signature appearance through the Acrobat user interface, access
signature appearances through the appearances property of the securi tyHandl er
object, and use the signature fields si gnatureSetSeedVal uemethod, which accepts
a SeedVal ueobject used to control signature properties.
One of the SeedVal ueproperties is called subFi l ter, which is an array of acceptable
formats to use for the signature. In the following example, the signing handler is set to
PPKMSand the format is set to adbe. pksc7. sha1:
var f = t hi s. get Fi el d( "mySi gnat ur eFi el d") ;
f . si gnat ur eSet SeedVal ue( {
f i l t er : "Adobe. PPKMS",
subFi l t er : [ "adbe. pksc7. sha1"] ,
f l ags: 0x03
}) ;
Clearing a Digital Signature from a Signature Field
To clear a signature, invoke the doc objects resetFormmethod. In the example below,
mySi gnatureFi el dis cleared:
var f = t hi s. get Fi el d( "mySi gnat ur eFi el d") ;
t hi s. r eset For m( f ) ;
Security
Digitally Signing PDF Documents
12
208 Acrobat JavaScript Scripting Guide
Getting Signature Information from Another User
You may maintain a list of trusted user identities by adding the certificates contained within
FDF files sent to you by other users. You may also obtain signature information from an FDF
file by invoking the FDFobjects si gnatureVal i datemethod, which returns a
si gnatureI nfoobject, as shown in the example below:
/ / Open t he FDF f i l e sent t o you by t he ot her user :
var f df = app. openFDF( "/ C/ myDoc. f df ") ;
/ / Obt ai n t he secur i t y handl er :
var engi ne = secur i t y. get Handl er ( "Adobe. PPKLi t e") ;
/ / Check t o see i f t he FDF has been si gned:
i f ( f df . i sSi gned)
{
/ / Obt ai n t he ot her user s si gnat ur e i nf o:
si gI nf o = f df . si gnat ur eVal i dat e( {
oSi g: engi ne,
bUI : t r ue
}) ;
/ / Di spl ay t he si gnat ur e st at us and descr i pt i on:
consol e. pr i nt l n( "Si gnat ur e St at us: " + si gI nf o. st at us) ;
consol e. pr i nt l n( "Descr i pt i on: " + si gI nf o. st at usText ) ;
}
el se
consol e. pr i nt l n( "Thi s FDF was not si gned. ") ;
Removing Signatures
To remove a signature field, invoke the doc objects removeFi el dmethod. In the
example below, mySi gnatureFi el dis removed:
var f = t hi s. get Fi el d( "mySi gnat ur eFi el d") ;
t hi s. r emoveFi el d( f ) ;
Certifying a Document
When applying an author signature to certify a document, check trustFl ags, which is a
read-only property of the si gnatureI nfoobject. If its value is 2, the signer is trusted for
certifying documents.
Acrobat JavaScript Scripting Guide 209
Security
Digitally Signing PDF Documents
12
Validating Signatures
To validate a signature, invoke the signature fields si gnatureVal i datemethod, which
returns one of the following integer validity status values:
- 1: not a signature field
0: signature is blank
1: unknown status
2: signature is invalid
3: signature is valid, identity of signer could not be verified
4: signature and identity of signer are both valid
The method accepts two parameters:
oSi g: the security handler used to validate the signature (a securi tyHandl er or
Si gnatureParameters object)
bUI : determines whether the user interface is shown when validating the data file
A Si gnatureParameters object contains two properties:
oSecHdl r: the security handler object
bAl tSecHdl r: determines whether an alternate security handler may be used
In the following example, mySi gnatureFi el dis analyzed for validity:
/ / Obt ai n t he si gnat ur e f i el d:
var f = t hi s. get Fi el d( "mySi gnat ur eFi el d") ;
/ / Val i dat e t he si gnat ur e f i el d:
var st at us = f . si gnat ur eVal i dat e( ) ;
/ / Obt ai n t he si gnat ur e i nf or mat i on
var si gI nf o = f . si gnat ur eI nf o( ) ;
/ / Check t he st at us r et ur ned f r omt he val i dat i on:
i f ( st at us < 3)
var msg = "Si gnat ur e i s not val i d: " + si gI nf o. st at usText ;
el se
var msg = "Si gnat ur e i s val i d: " + si gI nf o. st at usText ;
/ / Di spl ay t he st at us message:
app. al er t ( msg) ; ;
Using Approval Stamps
You may apply a stamp annotation to a document that indicates whether approval is
indicated. To do this, set the annotations APproperty to either Approvedor
NotApproved, as shown in the example below:
Security
Adding Security to PDF Documents
12
210 Acrobat JavaScript Scripting Guide
var annot = t hi s. addAnnot ( {
page: 0,
t ype: "St amp",
aut hor : "A. C. Robat ",
r ect : [ 400, 400, 550, 500] ,
cont ent s: "Thi s i s good. "
AP: "Appr oved"
}) ;
Setting Digital Signature Preferences
When applying digital signatures, you may specify the appearance and the default signing
method. In addition, you may set the securi ty objects
val i dateSi gnaturesOnOpenproperty to verify signatures whenever the document is
opened, and set up policies that examine the signature information. Signature information
may be obtained by invoking the signature fields si gnatureI nfomethod. At this point
you can customize the behavior based on the information found within the
si gnatureI nfoobject.
The following example illustrates how to access the signature information:
/ / Obt ai n t he si gnat ur e f i el d:
var f = t hi s. get Fi el d( "mySi gnat ur eFi el d") ;
/ / Val i dat e t he si gnat ur e f i el d:
var st at us = f . si gnat ur eVal i dat e( ) ;
/ / Obt ai n t he si gnat ur e i nf or mat i on
var si gI nf o = f . si gnat ur eI nf o( ) ;
consol e. pr i nt l n( "Name: " + si gI nf o. name) ;
consol e. pr i nt l n( "Reason: " + si gI nf o. r eason) ;
consol e. pr i nt l n( "Dat e: " + si gI nf o. dat e) ;
consol e. pr i nt l n( "Cont act I nf o: " + si gI nf o. cont act I nf o) ;
Adding Security to PDF Documents
Adding Passwords and Setting Security Options
Since the Standard security handler, used for password encryption of documents, is not
JavaScript-enabled, the most direct way to add passwords is through the creation of user or
master passwords in the Acrobat user interface.
As you learned earlier in Encrypting Files Using Certificates, you may encrypt a document
for a number of recipients using certificates, and can set security policies through the
Acrobat JavaScript Scripting Guide 211
Security
Adding Security to PDF Documents
12
application of an author signature accompanied by the desired modification, detection,
and prevention settings shown above in Table 12.1.
Adding Usage Rights to a Document
You may decide which usage rights will be permitted for a set of users. You may specify
either full, unrestricted access to the document, or rights that address accessibility, content
extraction, allowing changes, and printing. You may use Acrobat JavaScript to customize
these rights when encrypting a document for a list of recipients. For more information, see
Rights-Enabled PDF Files.
Encrypting PDF Files for a List of Recipients
As you have seen throughout this chapter, the doc objects encryptForReci pi ents
method is the primary means of encrypting PDF files for a list of recipients using Acrobat
JavaScript. In the previous example, the certificates used were gathered by connecting to a
di rectory, which is a repository of user information. The di rectory object contains
an i nfoproperty with which it is possible to create and activate a new directory, and is
accessible either through the di rectori es property or the newDi rectory method of
the securi tyHandl er object.
The i nfoobject is a Di rectoryI nformati onobject, which may contain standard
properties related to the name of the directory, as well as additional properties specific to a
particular directory handler (these may include server and port information).
To create a new directory, create a Di rectoryI nformati onobject, obtain a
securi tyHandl er object and invoke its newDi rectory method, and assign the
Di rectoryI nformati onobject to the new directorys i nfoproperty. An example of
this is given below:
/ / Cr eat e and act i vat e a new di r ect or y:
var newDi r I nf o = {
di r St dEnt r yI D: "di r 0",
di r St dEnt r yName: "Empl oyee LDAP Di r ect or y",
di r St dEnt r yPr ef Di r Handl er I D: "Adobe. PPKMS. ADSI ",
di r St dEnt r yDi r Type: "LDAP",
ser ver : "l dap0. acme. com",
por t : 389
};
/ / Obt ai n t he secur i t y handl er :
var sh = secur i t y. get Handl er ( "Adobe. PPKMS") ;
/ / Cr eat e t he new di r ect or y obj ect :
var newDi r = sh. newDi r ect or y( ) ;
/ / St or e t he di r ect or y i nf or mat i on i n t he new di r ect or y:
newDi r . i nf o = newDi r I nf o;
Security
Adding Security to PDF Documents
12
212 Acrobat JavaScript Scripting Guide
In order to obtain certificates from a directory, you must first connect to it using the
di rectory objects connect method, which returns a Di rConnecti onobject. An
example is given below:
/ / Obt ai n t he secur i t y handl er :
var sh = secur i t y. get Handl er ( "Adobe. PPKMS") ;
var dc = sh. di r ect or i es[ 0] . connect ( ) ;
It is then possible to use the Di rConnecti onobject to search for certificates. You can
specify the list of attributes to be used for the search by invoking the Di rConnecti on
objects setOutputFi el ds method, which accepts two parameters:
oFi el ds: an array of attributes to be used in the search
bCustom: whether the attributes are standard output attribute names
For example, the following code specifies standard output attributes (certi fi cates and
emai l ):
dc. set Out put At t r i but es( {oFi el ds: [ "cer t i f i cat es", "emai l "] }) ;
To perform the search, invoke the Di rConnecti onobjects searchmethod, which
accepts the following parameters:
oParams: an array of key-value pairs consisting of search attribute names and their
corresponding strings
cGroupName: the name of the group to which to restrict the search
bCustom: whether oParams contains standard attribute names
bUI : whether a user interface is used to collect the search parameters
In the following example, the directory is searched for certificates for the user whose last
name is "Smith", and displays the users email address:
var r et val = dc. sear ch( {oPar ams: {l ast Name: "Smi t h"}}) ;
i f ( r et val . l engt h > 0)
consol e. pr i nt l n( r et val [ 0] . emai l ) ;
Acrobat JavaScript Scripting Guide 213
Security
Adding Security to PDF Documents
12
Encrypting PDF Files Using Security Policies
It is possible to define a security policy for a PDF document. The policy can contain a list of
people who can open the document, restrictions limiting their ability to modify, print, or
copy the document, and an expiration date for the document after which it cannot be
opened.
There are two kinds of security policies: a custom policy is one created by a user and is
stored on a local computer, and a corporate policy is developed by an organization and
stored on a policy server such as LiveCycle

Policy Server

).
There are three types of custom policies. You may create policies for password security,
certificate security, and policies used on LiveCycle Policy Server.
Acrobat JavaScript defines a securi tyPol i cy object that contains the following
properties:
i d: a machine-readable policy id string
name: the policy name
descri pti on: the policy description
l astModi fi ed: the date when the policy was last modified
handl er: the handler that implements the policy (Adobe. APS, Adobe. PubSec, and
Adobe. Standard)
target: the target data covered by the policy (document or attachments)
To obtain a list of the security policies currently available, invoke the securi ty objects
getSecuri tyPol i ci es method, which accepts two parameters:
oOpti ons: a securi tyPol i cyOpti ons object containing parameters used to filter
the list
bUI : determines whether the user interface will be displayed (affects bCheckOnl i ne
in the oOpti ons parameter)
The securi tyPol i cyOpti ons object is a generic object used to filter the list of security
policies that will be returned by the method, and contains the following properties:
bCheckOnl i ne: determines whether to check online for updated security policies
bFavori tes: determines whether to return policies which are favorites
cFi l ter: returns policies using the specified PDCrypt filter (Adobe. APS,
Adobe. PubSec, and Adobe. Standard)
cTarget: returns policies using the specified target (document or attachments)
Security
Adding Security to PDF Documents
12
214 Acrobat JavaScript Scripting Guide
The following example illustrates how to request and display a list of favorite security
policies:
/ / Set up t he f i l t er i ng opt i ons ( Secur i t yOpt i onsPol i cy obj ect ) :
var opt i ons = {
bFavor i t es: t r ue,
cFi l t er : "Adobe. PubSec"
};
/ / Obt ai n t he f i l t er ed l i st of secur i t y pol i ci es:
var pol i cyAr r ay = secur i t y. get Secur i t yPol i ci es( opt i ons) ;
/ / Di spl ay t he l i st of secur i t y pol i ci es by name:
f or ( var i =0; i <pol i cyAr r ay. l engt h; i ++)
consol e. pr i nt l n( pol i cyAr r ay[ i ] . name) ;
To encrypt a PDF file using a security policy, you must first choose a security policy by
invoking the securi ty objects chooseSecuri tyPol i cy method, and then encrypt
the file by invoking either the doc objects encryptUsi ngPol i cy or encryptForAPS
method.
The securi ty objects chooseSecuri tyPol i cy method opens a dialog that permits
the user to choose from a list of security policies, filtered according to a
securi tyPol i cyOpti ons object.
The doc objects encryptUsi ngPol i cy method accepts three parameters:
cPol i cyI D: the policy id to use when encrypting the document
oReci pi ents: a Groupobject containing a list of recipients
bI gnoreUnknowns: determines whether unknown or incomplete recipients will
cause an exception to be thrown
Acrobat JavaScript Scripting Guide 215
Security
Adding Security to PDF Documents
12
In the following example, a newly created document is encrypted for a list of recipients,
using the encryptUsi ngPol i cy method, by choosing and applying a security policy:
/ / Cr eat e t he new document
var myDoc = app. newDoc( ) ;
/ / Set up t he f i l t er i ng opt i ons ( Secur i t yOpt i onsPol i cy obj ect ) :
var opt i ons = {
bCheckOnl i ne: t r ue,
cFi l t er : "Adobe. APS"
};
/ / Choose t he secur i t y pol i cy:
var pol i cy = secur i t y. chooseSecur i t yPol i cy( opt i ons) ;
/ / Choose t he l i st of r eci pi ent s
var r eci pi ent s = {
user Ent i t i es: [
{emai l : "user 1@adobe. com"},
{emai l : "user 2@adobe. com"},
{emai l : "user 3@adobe. com"}
]
};
/ / Encr ypt t he document usi ng t he secur i t y pol i cy:
var pol i cyI D = myDoc. encr ypt Usi ngPol i cy( {
cPol i cyI d: "adobe_secur e_f or _r eci pi ent s",
oReci pi ent s: [ r eci pi ent s]
}) ;
/ / Di spl ay t he pol i cy I D:
consol e. pr i nt l n( "Pol i cy I D = " + pol i cyI D) ;
Security
Adding Security to PDF Documents
12
216 Acrobat JavaScript Scripting Guide
The doc objects encryptForAPSmethod accepts four parameters:
cPol i cyI D: the policy ID to use when encrypting the document
bUI : determines whether the user interface is shown when authenticating
oHandl er: the handler to use when applying the policy
aReci pi ents: an array of email addresses for the intended recipients (used only if the
template policy ID is adobe_secure_for_reci pi ents
In the following example, a newly created document is encrypted using the template
policy:
/ / Obt ai n t he APS secur i t y handl er :
var aps = secur i t y. get Handl er ( "Adobe. APS") ;
/ / Access t he di gi t al I D:
aps. l ogi n( {
oPar ams: {
cURI : "ht t p: / / adobe. com/ guar di an",
cUser I d: "t est ",
cPasswor d: "t est "
}
}) ;
/ / Speci f y t he r eci pi ent s:
var r eci pi ent s = [
"user 1@adobe. com",
"user 2@adobe. com",
"user 3@adobe. com"
] ;
/ / Cr eat e t he new document
var myDoc = app. newDoc( ) ;
/ / Encr ypt t he document :
myDoc. encr ypt For APS( {
cPol i cyI d: "adobe_secur e_f or _r eci pi ent s",
aReci pi ent s: r eci pi ent s,
oHandl er : aps,
bUI : f al se
}) ;
Acrobat JavaScript Scripting Guide 217
Security
Adding Security to PDF Documents
12
Adding Security to Document Attachments
You may add security to a document by encrypting its attachments and enclosing them in
an eEnvelope. To do this with Acrobat JavaScript, invoke the doc objects
addReci pi entLi stCryptFi l ter method, which is used to encrypt data objects and
accepts two parameters:
oCryptFi l ter: the name of the encryption filter
oGroup: an array of Groupobjects representing the intended recipients
Thus, an eEnvelope is a PDF file that contains encrypted attachments. The name of the
crypt filter, which represents the recipient list, is defined and used when importing the
attachment. An example is given below:
/ / Cr eat e i nst r uct i ons t o be used i n t he r eci pi ent di al og:
var not e = "Sel ect t he r eci pi ent s. Each must have ";
not e += "an emai l addr ess and a cer t i f i cat e. ";
/ / Speci f y t he r emai ni ng opt i ons used i n t he r eci pi ent di al og:
var opt i ons = {
bAl l owPer mGr oups: f al se,
cNot e: not e,
bRequi r eEmai l : t r ue
};
/ / Obt ai n t he i nt ended r eci pi ent Gr oup obj ect s:
var gr oupAr r ay = secur i t y. chooseReci pi ent sDi al og( opt i ons) ;
/ / Open t he eEnvel ope document :
var env = app. openDoc( "/ C/ myeEnvel ope. pdf ") ;
/ / Set up t he cr ypt f i l t er :
env. addReci pi ent Li st Cr ypt Fi l t er ( "myFi l t er ", gr oupAr r ay) ;
/ / At t ach t he cur r ent document t o t he eEnvel ope:
env. i mpor t Dat aObj ect ( "secur eMai l 0", t hi s. pat h, "myFi l t er ") ;
/ / Save t he eEnvel ope:
env. saveAs( "/ C/ out mai l . pdf ") ;
Security
Digital IDs and Certification Methods
12
218 Acrobat JavaScript Scripting Guide
Digital IDs and Certification Methods
It is possible to customize and extend the management and usage of digital IDs using
Acrobat JavaScript. In addition, it is possible to share digital ID certificates, build a list of
trusted identities, and analyze the information contained within certificates.
Digital IDs
As you learned earlier, a digital ID is represented with a si gnatureI nfoobject, which
contains properties of the digital signature common to all handlers, in addition to other
properties defined by public key security handlers. These additional properties are
described below in Table 12.4:
TABLE 12.4 SignatureInfo Public Key Security Handler Properties
Property Description
appearance User-configured appearance name
certi fi cates Chain of certificates from signer to certificate authority
contactI nfo User-specified contact information for determining trust
byteRange Bytes covered by this signature
docVal i di ty Validity status of the document byte range digest
i dPri vVal i di ty Validity of the identity of the signer
i dVal i di ty Numerical validity of the identity of the signeN
obj Val i di ty Validity status of the object digest
trustFl ags What the signer is trusted for
password Password used to access private key for signing
Acrobat JavaScript Scripting Guide 219
Security
Digital IDs and Certification Methods
12
About Digital ID Providers
A digital ID provider is a trusted 3rd party, often called a certificate authority or signature
handler, that verifies the identity, issues the private key, and protects the public key. The
certi fi cates property of the si gnatureI nfoobject contains an array of certificates
that reflects the hierarchy leading from the signers certificate to that issued by the
certificate authority. Thus, you may inspect the details of the certificate issued by the digital
ID provider, such as its usageproperty.
For example, the following code encrypts the current document for everyone in the
address book. It does this by creating a collection of certificates suitable for encrypting
documents, which are filtered from the overall collection. This is accomplished by
examining all the certificates in the address book and excluding those entries containing
sign-only certificates, CA certificates, no certificates, or certificates otherwise unsuitable for
encryption:
/ / Obt ai n t he secur i t y handl er :
var eng = secur i t y. get Handl er ( "Adobe. AAB") ;
/ / Connect t o t he di r ect or y cont ai ni ng t he cer t i f i cat es:
var dc = eng. di r ect or i es[ 0] . connect ( ) ;
/ / Obt ai n t he l i st of al l r eci pi ent s i n t he di r ect or y:
var r cp = dc. sear ch( ) ;
/ / Cr eat e t he f i l t er ed r eci pi ent l i st :
var f Rcp = new Ar r ay( ) ;
/ / Popul at e t he f i l t er ed r eci pi ent l i st :
f or ( var i =0; i <r cp. l engt h; i ++) {
i f ( r cp[ i ] . def aul t Encr ypt Cer t &&
r cp[ i ] . def aul t Encr ypt Cer t . usage. endUser Encr ypt i on)
f Rcp[ f Rcp. l engt h] = r cp[ i ] ;
i f ( r cp[ i ] . cer t i f i cat es) {
f or ( var j =0; j <r cpp[ i ] . cer t i f i cat es. l engt h; j ++)
i f ( r cp[ i ] . cer t i f i cat es[ j ] . usage. endUser Encr ypt i on)
f Rcp[ f Rcp. l engt h] = r cp[ i ] ;
}
}
/ / Now encr ypt f or t he f i l t er ed r eci pi ent l i st :
t hi s. encr ypt For Reci pi ent s( {[ user Ent i t i es: f Rcp] }) ;
Security
Digital IDs and Certification Methods
12
220 Acrobat JavaScript Scripting Guide
Creating a Digital ID (Default Certificate Security)
If you would like to create a certificate for a new user, invoke the securi tyHandl er
objects newUser method, which supports enrollment with the Adobe. PPKLi teand
Adobe. PPKMSsecurity handlers by creating a new self-sign credential, and prevents the
user from overwriting the file. It accepts the following parameters:
cPassword: the password needed to access the digital ID file
cDI Path: the location of the digital ID file
oRDN: the relative distinguished name (represented as an RDNobject) containing the
issuer or subject name for the certificate
oCPS: the certificate policy information, which is a generic object containing the
following properties:
oi d: the certificate policy object identifier
url : URL pointing to detailed policy information
noti ce: shortened version of detailed policy information
bUI : determines whether to use the user interface to enroll the new user
The relative distinguished name is a generic object containing the properties shown below
in Table 12.5:
TABLE 12.5 RDN Object
Property Description
c Country or region
cn Common name
o Organization name
ou Organization unit
e Email address
Acrobat JavaScript Scripting Guide 221
Security
Digital IDs and Certification Methods
12
An example is given below:
/ / Obt ai n t he secur i t y handl er :
var ppkl i t e = secur i t y. get Handl er ( "Adobe. PPKLi t e") ;
/ / Cr eat e t he r el at i ve di st i ngui shed name:
var newRDN = {
cn: "newUser ",
c: "US"
};
/ / Cr eat e t he cer t i f i cat e pol i cy i nf or mat i on:
var newCPS = {
oi d: "1. 2. 3. 4. 5",
ur l : "ht t p: / / newca. com/ newCPS. ht ml ",
not i ce: "Thi s i s a sel f - gener at ed cer t i f i cat e"
};
/ / Cr eat e t he new user s cer t i f i cat e:
secur i t y. newUser ( {
cPasswor d: "newUser Passwor d",
cDI Pat h: "/ C/ newUser . pf x",
oRDN: newRDN,
oCPS: newCPS,
bUI : f al se
}) ;
The securi tyHandl er object has a Di gi tal I Ds property that contains the
certificates associated with the currently selected digital IDs for the security handler. The
Di gi tal I Ds property is a generic object containing the following properties:
oEndUserSi gnCert: the certificate used when signing
oEndUserCryptCert: the certificate used when encrypting
certs: an array of certificates corresponding to all the digital IDs
stores: an array of strings (one for every certi fi cateobject) indicating where the
digital IDs are stored
You may use the securi ty objects exportToFi l emethod to save a certificate file to
disk. In the following example, the signing certificate is written to disk:
/ / Obt ai n t he secur i t y handl er :
var sh = secur i t y. get Handl er ( "Adobe. PPKMS") ;
/ / Obt ai n t he cer t i f i cat es:
var i ds = sh. Di gi t al I Ds;
/ / Wr i t e t he si gni ng cer t i f i cat e t o di sk:
secur i t y. expor t ToFi l e( i ds. oEndUser Si gnCer t , "/ C/ mySi gnCer t . cer ") ;
Security
Digital IDs and Certification Methods
12
222 Acrobat JavaScript Scripting Guide
Using Digital IDs (Default Certificate Security)
As you learned earlier, you may obtain signature information from a signature field by
invoking its si gnatureI nfomethod. In addition to this, you may also use an existing
certificate to create a digital ID. To do this, obtain the certificate from an existing, signed
field and create the relative distinguished name using the information it contains, as shown
in the following example:
/ / Obt ai n t he secur i t y handl er :
var ppkl i t e = secur i t y. get Handl er ( "Adobe. PPKLi t e") ;
/ / Obt ai n t he si gnat ur e f i el d:
var f = t hi s. get Fi el d( "exi st i ngSi gnat ur e") ;
/ / Val i dat e t he si gnat ur e:
f . si gnat ur eVal i dat e( ) ;
/ / Obt ai n t he si gnat ur e i nf or mat i on:
var si gI nf o = f . si gnat ur eI nf o( ) ;
/ / Obt ai n t he cer t i f i cat es and di st i ngui shed name i nf or mat i on
var cer t s = si gI nf o. cer t i f i cat es;
var r dn = cer t s[ 0] . subj ect DN;
/ / Now cr eat e t he di gi t al si gnat ur e:
ppkl i t e. newUser ( {
cPasswor d: "newUser Passwor d",
cDI Pat h: "/ C/ newUser . pf x",
oRDN: r dn,
}) ;
Acrobat JavaScript Scripting Guide 223
Security
Digital IDs and Certification Methods
12
Managing Digital IDs (Windows Certificate Security)
A di rectory object is a repository of user information, including public key certificates.
On Windows, the Adobe. PPKMSsecurity handler provides access, through the Microsoft
Active Directory Script Interface (ADSI), to the directories created by the user. These are
created sequentially with the names Adobe. PPKMS. ADSI . di r0,
Adobe. PPKMS. ADSI . di r1, etc. In this case, the Adobe. PPKMS. ADSI directory
handler includes the directory information object properties shown below in Table 12.6:
For example, the following code displays information for an existing directory:
/ / Obt ai n t he secur i t y handl er :
var ppkms = secur i t y. get Handl er ( "Adobe. PPKMS") ;
/ / Obt ai n t he di r ect or y i nf or mat i on obj ect :
var i nf o = ppkms. di r ect or i es[ 0] . i nf o;
/ / Di spl ay some of t he di r ect or y i nf or mat i on:
consol e. pr i nt l n( "Di r ect or y: " + i nf o. di r St dEnt r yName) ;
consol e. pr i nt l n( "Addr ess: " + i nf o. ser ver + ": " + i nf o. por t ) ;
TABLE 12.6 Adobe.PPKMS.ADSI Directory Handler Object Properties
Property Description
server The server hosting the data
port The port number (standard LDAP port is 389)
searchBase Used to narrow the search to a section of the directory
maxNumEntri es Maximum number of entries retrieved from search
ti meout Maximum time allowed for search
Security
Digital IDs and Certification Methods
12
224 Acrobat JavaScript Scripting Guide
Managing Digital ID Certificates
Sharing Digital ID Certificates
You may share a self-signed digital ID certificate by exporting it as an FDF file. To do this,
sign the FDF file by invoking the FDFobjects si gnatureSi gnmethod, which works
similarly to that of the doc object. Its usage is illustrated in the example below:
/ / Obt ai n t he secur i t y handl er :
var eng = secur i t y. get Handl er ( "Adobe. PPKLi t e") ;
/ / Access t he di gi t al I D:
eng. l ogi n( "myPasswor d", "/ C/ myI D. pf x") ;
/ / Open t he FDF:
var myFDF = app. openFDF( "/ C/ myFDF. f df ") ;
/ / Si gn t he FDF:
i f ( ! myFDF. i sSi gned) {
/ / Si gn t he FDF
myFDF. si gnat ur eSi gn( {
oSi g: eng,
nUI : 1,
cUI Si gnTi t l e: "Si gn Embedded Fi l e FDF",
cUI Sel ect Msg: "Pl ease sel ect a di gi t al I D"
}) ;
/ / Save t he FDF
myFDF. save( "/ C/ myFDF. f df ") ;
}
Building a List of Trusted Identities
The trust level associated with a digital ID is stored in the trustFl ags property defined in
the si gnatureI nfoobjects public key security handler properties. The bits in this
number indicate the level of trust associated with the signer, and are valid only when the
status property has a value of 4. These trust settings are derived from those in the
recipients trust database, such as the Acrobat Address Book (Adobe. AAB). The following
bit assignments are described below:
1: trusted for signatures
2: trusted for certifying documents
3: trusted for dynamic content such as multimedia
4: Adobe internal use
5: the JavaScript in the PDF file is trusted to operate outside the normal PDF restrictions
Acrobat JavaScript Scripting Guide 225
Security
Digital IDs and Certification Methods
12
Checking Information on Certificates
As you learned earlier, you may obtain a certificates through the certi fi cates property
of a si gnatureI nfoobject, which is returned by a call to the signature fields
si gnatureI nfo method. The certificate properties are described above in Table 12.3,
and the relative distinguished name properties are defined in Table 12.5.
In the following example, the signers common name, the certificates serial number, and
the distinguished name information are displayed:
/ / Obt ai n t he si gnat ur e f i el d:
var f = t hi s. get Fi el d( "mySi gnat ur eFi el d") ;
/ / Val i dat e t he si gnat ur e f i el d:
var st at us = f . si gnat ur eVal i dat e( ) ;
/ / Obt ai n t he si gnat ur e i nf or mat i on
var si gI nf o = f . si gnat ur eI nf o( ) ;
/ / Obt ai n t he cer t i f i cat e:
var cer t = si gI nf o. cer t i f i cat es[ 0] ;
consol e. pr i nt l n( "si gner s common name: " + cer t . subj ect CN) ;
consol e. pr i nt l n( "ser i al number : " + cer t . ser i al Number ) ;
/ / Di st i ngui shed name i nf or mat i on:
consol e. pr i nt l n( "di st i ngui shed common name: " + cer t . subj ect DN. cn) ;
consol e. pr i nt l n( "di st i ngui shed or gani zat i on: " + cer t . subj ect DN. o) ;
Security
Digital IDs and Certification Methods
12
226 Acrobat JavaScript Scripting Guide
Tokenized Acrobat JavaScript Security Model
In order to maintain security for cases in which Acrobat JavaScript connects to data sources
external to the current document without user interaction (excluding console and batch
sequences), a token-based security scheme is used to match and validate JavaScript
resources and operations (a resource is defined as the combination of a protocol and a host).
Each JavaScript is provisionally granted a token, which is matched against the resource.
The methods and properties shown below in Table 12.7 use this token-based security
model:
TABLE 12.7 Methods and Properties Using Tokenized Security Model
Method/Property Description
doc. submi tForm Get/send
doc. getURL Send
doc. mai l Doc Send when bUI is fal se
doc. mai l Form Send when bUI is fal se
doc. save May mark doc with data sources
doc. saveAs May mark doc with data sources
soap. connect Get/send
soap. request Get/send
soap. response Get/send
ADBC. newConnecti on Get/send
app. acti veDocs Get
app. openDoc Get
app. gl obal Get
Acrobat JavaScript Scripting Guide 227
13
Rights-Enabled PDF Files
Introduction
When creating a PDF document, it is possible to create certified documents by assigning
special rights to it that enable users of Adobe Reader to fill in forms, participate in online
reviews, and attach files. LiveCycle Reader Extensions

may be used to activate additional


functionality within Adobe Reader for a particular document, thereby enabling the user to
save, fill in, annotate, sign, certify, authenticate, and submit the document, thus
streamlining collaboration for document reviews and automating data capture with
electronic forms. In addition, users of Acrobat Professional can Reader-enable
collaboration.
Chapter Goals
At the end of this chapter, you will be able to:
List the additional usage rights that can be enabled in a PDF document.
Understand the roles of Adobe Document Server and LiveCycle Reader Extensions.
Understand how Reader-enabled PDF documents affect the usage of Acrobat
JavaScript.
Understand how to enable collaboration
Understand how the security model is related to additional usage rights.
Contents
Topics
Additional Usage Rights
LiveCycle Reader Extensions
Writing Acrobat JavaScript for Reader
Enabling Collaboration
Rights-Enabled PDF Files
Additional Usage Rights
13
228 Acrobat JavaScript Scripting Guide
Additional Usage Rights
Livecycle Reader Extensions sets permissions within a PDF document that would otherwise
be disabled through the usage of a certificate issued by the Adobe Reader-Extension Root
Certificate Authority. Permissions for Reader-enabled PDF files (also known as certified PDF
documents) are determined by the combination of the user rights settings in the PDF file
and and a special Object Identifier (OID), embedded within the certificate, specifying the
additional permissions to be made available. The permissions are listed below:
Form: fill-in and document full-save
Form: import and export
Form: add and delete
Form: submit standalone
Form: spawn template
Signature: modify
Annotation: create, delete, modify, and copy
Annotation: import and export
Form: barcode plain text
Annotation: online
Form: online
Embedded File: create, delete, modify, copy, and import
LiveCycle Reader Extensions
During the design process, a PDF document may be created through the usage of LiveCycle
Designer

, LiveCycle Forms

, or Adobe Document Server

. Then the document creator


may assign appropriate usage rights using the LiveCycle Reader Extensions. The PDF
document is made available on the Web, and users may complete the form on the web site,
or save it locally and subsequently complete and annotate it, digitally sign it, add
attachments, and return it.
In effect, LiveCycle Reader Extensions will enable functionality within Adobe Reader for a
given document that is not normally available. After the user has finished working with the
document, those functions will be disabled until the user receives another rights-enabled
PDF file.
One major advantage of LiveCycle Reader Extensions is that it supports data automation
through XML-based representation and transfer via SOAP, thus ensuring seamless
integration with business logic and advanced data transport capabilities available within
enterprise applications.
Acrobat JavaScript Scripting Guide 229
Rights-Enabled PDF Files
Writing Acrobat JavaScript for Reader
13
Writing Acrobat JavaScript for Reader
It is possible to access or assign additional usage rights within a PDF file by using the
LiveCycle Reader Extensions API or its Web user interface.
NOTE: For rights-enabled documents, certain editing features normally available within
the Acrobat Standard and Professional products will be disabled. This will ensure
that the user does not inadvertantly invalidate the additional usage rights in a
document under managed review before passing the document on to an Adobe
Reader user for further commenting.
The methods shown below in Table 13.1 will be disabled by LiveCycle Reader Extensions:
TABLE 13.1 Features Disabled by Livecycle Reader Extensions
Features Methods
delete, add, replace, and move pages doc. del etePages,
doc. newPage,
doc. repl acePages,
doc. movePage,
doc. i nsertPage
modify page content doc. addWatermarkFromText,
doc. addWatermarkFromFi l e,
doc. fl attenPages,
doc. del eteSound
add or modify JavaScripts doc. setActi on,
doc. setPageActi on,
fi el d. setActi on,
l i nk. setActi on,
ocg. setActi on,
bookmark. setActi on,
thi s. i mportAnFDF
Rights-Enabled PDF Files
Writing Acrobat JavaScript for Reader
13
230 Acrobat JavaScript Scripting Guide
In Acrobat Standard and Professional, the following controls will be disabled for rights-
enabled documents:
Menu items under Advanced > JavaScript that allow the addition or modification of
JavaScripts (except for the Debugger).
Menu items under Advanced > Forms that allow the creation, modification, or deletion
of form fields (except the Import and Export menu items).
Certain operations within Document Properties > Security Panel will be marked as
Not Allowed.
In addition, since the following menu operations will be affected in Acrobat Standard and
Professional, so will their corresponding JavaScript methods, indicated below in Table 13.2:
TABLE 13.2 Controls Affected by Livecycle Reader Extensions in Acrobat Standard and
Professional
Menu Operation Equivalent JavaScript Method
File > Reduce File Size app. execMenuI tem
Document > Pages > Insert doc. i nsertPage
Document > Pages > Replace doc. repl acePages
Document > Pages > Delete doc. del etePages
Document > Pages > Crop doc. setPageBoxes
Document > Pages > Rotate doc. setPageRotati ons
Document > Pages > Set Page
Transitions
app. defaul tTransi ti ons
(read-only),
doc. setPageTransi ti ons
Document > Pages > Number
Pages
doc. setPageLabel s
Document > Add Watermark &
Background
doc. addWatermarkFromText,
doc. addWatermarkFromFi l e
Edit > Add Bookmark bookmark. createChi l d
Acrobat JavaScript Scripting Guide 231
Rights-Enabled PDF Files
Writing Acrobat JavaScript for Reader
13
When you invoke the objects encryptForReci pi ents method, the oGroups
parameter is an array of Groupobjects, each of which contains a permi ssi ons property.
The permi ssi ons property is an object containing the properties described below in
Table 13.3:
The following code allows full and unrestricted access to the entire document for one set of
users (i mportantUsers), and allows high quality printing for another set of users
(otherUsers):
/ / Obt ai n t he secur i t y handl er :
var sh = secur i t y. get Handl er ( "Adobe. PPKMS") ;
/ / Connect t o t he di r ect or y cont ai ni ng t he user cer t i f i cat es:
var di r = sh. di r ect or i es[ 0] ;
var dc = di r . connect ( ) ;
/ / Sear ch t he di r ect or y f or cer t i f i cat es:
dc. set Out put Fi el ds( {oFi el ds: [ "cer t i f i cat es"] }) ;
var i mpor t ant User s = dc. sear ch( {oPar ams: {l ast Name: "Smi t h"}}) ;
var ot her User s = dc. sear ch( {oPar ams: {l ast Name: "J ones"}}) ;
/ / Al l ow i mpor t ant user s f ul l , unr est r i ct ed access:
var i mpor t ant Gr oup = {
oCer t s: i mpor t ant User s,
oPer mi ssi ons: {al l owAl l : t r ue}
};
/ / Al l ow ot her user s hi gh qual i t y pr i nt i ng:
var ot her Gr oup = {
oCer t s: ot her User s,
oPer mi ssi ons: {al l owPr i nt i ng: "hi ghQual i t y"}
};
TABLE 13.3 Permissions Object
Property Description
al l owAl l Full, unrestricted access
al l owAccessi bi l i ty Content access for the visually impaired
al l owContentExtracti on content copying and extraction
al l owChanges Allowed changes (none,
documentAssembl y, fi l l AndSi gn,
edi tNotesFi l l AndSi gn, al l )
al l owPri nti ng Printing security level (none, l owQual i ty,
hi ghQual i ty)
Rights-Enabled PDF Files
Writing Acrobat JavaScript for Reader
13
232 Acrobat JavaScript Scripting Guide
/ / Encr ypt t he document f or t he i nt ended r eci pi ent s:
t hi s. encr ypt For Reci pi ent s( {
oGr oups: [ i mpor t ant Gr oup, ot her Gr oup] ,
bMet aDat a: t r ue
}) ;
If a document is rights-enabled but commenting is not allowed, then the JavaScript
methods shown below in Table 13.4 will be disabled:
If a document is rights-enabled but file attachments are not allowed, then the following
JavaScript methods will be disabled:
doc. createDataObj ect
doc. i mportDataObj ect
doc. setDataObj ectContents
doc. removeDataObj ect
If a document is rights-enabled but digital signatures are not allowed, then the following
JavaScript methods will be disabled:
doc. getFi el d(for signature fields)
doc. addFi el d(when cFi el dType="si gnature")
fi el d. removeFi el d(when cFi el dType="si gnature")
fi el d. si gnatureSi gn
TABLE 13.4 When Commenting is Not Allowed in Reader-Enabled Documents
Feature Method
Add a comment
doc. addAnnot
Import comments
doc. i mportAnFDF
Export comments doc. exportAsFDF(when
bAnnotati ons is set to true)
Acrobat JavaScript Scripting Guide 233
Rights-Enabled PDF Files
Enabling Collaboration
13
Enabling Collaboration
By using Really Simple Syndication (RSS), collaboration servers can provide customized
XML-based user interfaces directly inside of Acrobat itself, thus providing a more dynamic
and personalized tool, and providing JavaScript developers a means to extend
collaboration, including full user interfaces.
In addition, it is now straightforward to migrate comments from one document to another,
carry comments across multiple versions of a document, and anchor comments to content
so that the annotations remain in the right place even if the content changes.
The advantages of this are that it is possible to automate discovery of collaboration servers,
initiation workflows, and RSS feeds which may be used to populate content inside Adobe
Reader.
It is significant to note that users of Acrobat Professional can enable collaboration, thus
enabling them to invite users of Adobe Reader to participate in the review process.
The following JavaScript methods will be enabled in Adobe Reader when collaboration is
enabled:
doc. addAnnot
doc. i mportAnFDF
doc. exportAnFDF
Rights-Enabled PDF Files
Enabling Collaboration
13
234 Acrobat JavaScript Scripting Guide
Acrobat JavaScript Scripting Guide 235
Rights-Enabled PDF Files
Enabling Collaboration
13
Rights-Enabled PDF Files
Enabling Collaboration
13
236 Acrobat JavaScript Scripting Guide
Acrobat JavaScript Scripting Guide 237
14
Interacting with Databases
Introduction
It is possible to use Acrobat JavaScript to interact with databases through an Open
Database Connectivity (ODBC) connection. This means that you may use Acrobat
JavaScript objects to connect to a database, retrieve tables, and execute queries. The object
model associated with database interaction is centered on the ADBCobject, which
provides an interface to the ODBC connection. The ADBCobject interacts with other
objects to facilitate database connectivity and interaction: DataSourceI nfo,
connecti on, statement, Col umn, Col umnI nfo, row, and Tabl eI nfo. These
objects may be used in document-level scripts to execute database queries.
Chapter Goals
At the end of this chapter, you will be able to:
Obtain a list of accessible databases.
Connect to a database.
Execute an SQL query.
Access table, row, and column properties and data.
Contents
Topics
Introduction to ADBC
Establishing an ADBC Connection
Executing SQL Statements
Interacting with Databases
Introduction to ADBC
14
238 Acrobat JavaScript Scripting Guide
Introduction to ADBC
Acrobat JavaScript provides an ODBC-compliant object model called Acrobat Database
Connectivity (ADBC), which can be used in document-level scripts to connect to a database
for the purposes of inserting new information, updating existing information, and deleting
database entries. ADBC provides a simplified interface to ODBC, which it uses to establish a
connection to a database and access its data, and supports the usage of SQL statements for
data access, update, deletion, and retrieval.
Thus, a necessary requirement to the usage of ADBC is that ODBC must be installed on a
client machine running a Microsoft Windows operating system. In addition, ADBC does not
provide security measures with respect to database access; it is assumed that the database
administrator will establish and maintain the security of all data.
The Acrobat JavaScript ADBCobject thus provides methods through which you can obtain
a list of accessible databases and form a connection with one of them. These methods are
called getDataSourceLi st and newConnecti on. In addition, the ADBCobject
provides a number of properties corresponding to all supported SQL and Acrobat
JavaScript data types, which include representations of numeric, character, time, and date
formats.
Establishing an ADBC Connection
There are normally two steps required to establish an ADBC connection. First, obtain a list
of accessible databases by invoking the ADBCobjects getDataSourceLi st method.
Then establish the connection by passing the Data Source Name (DSN) of one of the
databases in the list to the ADBCobjects newConnecti onmethod.
The getDataSourceLi st method returns an array of DataSourceI nfogeneric
objects, each of which contains the following properties:
name: a string identifying the database
descri pti on: a description containing specific information about the database
In the following example, a list of all available databases is retrieved, and the DSN of the
DataSourceI nfoobject representing Q32000Datais identified and stored in variable
DB:
Acrobat JavaScript Scripting Guide 239
Interacting with Databases
Establishing an ADBC Connection
14
/ / Obt ai n a l i st of accessi bl e dat abases:
var dat abaseLi st = ADBC. get Dat aSour ceLi st ( ) ;
/ / Sear ch t he Dat aSour ceI nf o obj ect s f or t he Q32000Dat a dat abase:
i f ( dat abaseLi st ! = nul l ) {
var DB = "";
f or ( var i =0; i <dat abaseLi st . l engt h; i ++)
i f ( dat abaseLi st [ i ] . name == "Q32000Dat a") {
DB = dat abaseLi st [ i ] . name;
br eak;
}
}
To establish the database connection, invoke the ADBCobjects newConnecti on
method, which accepts the following parameters:
cDSN: the Data Source Name (DSN) of the database
cUI D: the user ID
cPWD: the password
The newConnecti onmethod returns a connecti onobject, which encapsulates the
connection by providing methods which allow you to create a statement object, obtain
information about the list of tables in the database or columns within a table, and close the
connection.
In the following example, a connection is established with the Q32000Datadatabase:
i f ( DB ! = "") {
/ / Connect t o t he dat abase and obt ai n a Connect i on obj ect :
var myConnect i on = ADBC. newConnect i on( DB. name) ;
}
The connecti onobject provides the methods shown below in Table 14.1:
TABLE 14.1 Connection Object
Method Description
cl ose Closes the database connection
newStatement Creates a statement object used to execute SQL
statements
getTabl eLi st Retrieves information about the tables within the
database
getCol umnLi st Retrieves information about the various columns within a
table
Interacting with Databases
Establishing an ADBC Connection
14
240 Acrobat JavaScript Scripting Guide
The connecti onobjects getTabl eLi st method returns an array of Tabl eI nfo
generic objects, each of which corresponds to a table within the database and contains the
following properties:
name: the table name
descri pti on: a description of database-dependent information about the table
In the following example, the name and description of every table in the database is
printed to the console:
/ / Obt ai n t he ar r ay of Tabl eI nf o obj ect s r epr esent i ng t he dat abase t abl es:
var t abl eAr r ay = myConnect i on. get Tabl eLi st ( ) ;
/ / Pr i nt t he name and descr i pt i on of each t abl e t o t he consol e:
f or ( var i =0; i <t abl eAr r ay. l engt h; i ++) {
consol e. pr i nt l n( "Tabl e Name: " + t abl eAr r ay[ i ] . name) ;
consol e. pr i nt l n( "Tabl e Descr i pt i on: " + t abl eAr r ay[ i ] . descr i pt i on) ;
}
The connecti onobjects getCol umnLi st method accepts a parameter containing the
name of one of the database tables, and returns an array of Col umnI nfogeneric objects,
each of which corresponds to a column within the table and contains the following
properties:
name: the name of the column
descri pti on: a description of database-dependent information about the column
type: a numeric identifier representing an ADBCSQL type
typeName: a database-dependent string representing the data type
In the following example, a complete description of every column in the Q32000Data
database table called Sal es is printed to the console:
/ / Obt ai n t he ar r ay of Col umnI nf o obj ect s r epr esent i ng t he Sal es t abl e:
var col umnAr r ay = myConnect i on. get Col umnLi st ( "Sal es") ;
/ / Pr i nt a compl et e descr i pt i on of each col umn t o t he consol e:
f or ( var i =0; i <col umnAr r ay. l engt h; i ++) {
consol e. pr i nt l n( "Col umn Name: " + col umnAr r ay[ i ] . name) ;
consol e. pr i nt l n( "Col umn Descr i pt i on: " + col umnAr r ay[ i ] . descr i pt i on) ;
consol e. pr i nt l n( "Col umn SQL Type: " + col umnAr r ay[ i ] . t ype) ;
consol e. pr i nt l n( "Col umn Type Name: " + col umnAr r ay[ i ] . t ypeName) ;
}
Acrobat JavaScript Scripting Guide 241
Interacting with Databases
Executing SQL Statements
14
Executing SQL Statements
To execute SQL statements, first create a statement object by invoking the
connecti onobjects newStatement method. The newly created statement object
can be used to access any row or column within the database table and execute SQL
commands.
In the following example, a statement object is created for the Q32000Datadatabase
created in the previous sections:
mySt at ement = myConnect i on. newSt at ement ( ) ;
The statement object provides the methods shown below in Table 14.2:
In addition to the methods shown above in Table 14.2, the statement object provides
two useful properties:
col umnCount: the number of columns in each row of results returned by a query
rowCount: the number of rows affected by an update
To execute an SQL statement, invoke the statement objects executemethod, which
accepts a string parameter containing the SQL statement. Note that any names containing
spaces must be surrounded by escaped quotation marks, as shown in the following
example:
/ / Cr eat e t he SQL st at ement :
var SQLSt at ement = Sel ect * f r om\ "Cl i ent Dat a\ " ;
/ / Execut e t he SQL st at ement :
mySt at ement . execut e( SQLSt at ement ) ;
TABLE 14.2 Statement Object
Method Description
execute Executes an SQL statement
getCol umn Obtains a column within the table
getCol umnArray Obtains an array of columns within the table
getRow Obtains the current row in the table
nextRow Iterates to the next row in the table
Interacting with Databases
Executing SQL Statements
14
242 Acrobat JavaScript Scripting Guide
There are two steps required to obtain a row of data. First, invoke the statement objects
nextRowmethod; this makes it possible to retrieve the rows information. Then, invoke the
statement objects getRowmethod, which returns a Rowgeneric object representing
the current row.
In the example shown below, the first row of information will be displayed in the console.
Note that the syntax is simplified in this case because there are no spaces in the column
names:
/ / Cr eat e t he SQL st at ement :
var st = Sel ect f i r st Name, l ast Name, ssn f r om\ "Empl oyee I nf o\ " ;
/ / Execut e t he SQL st at ement :
mySt at ement . execut e( st ) ;
/ / Make t he next r ow ( t he f i r st r ow i n t hi s case) avai l abl e:
mySt at ement . next Row( ) ;
/ / Obt ai n t he i nf or mat i on cont ai ned i n t he f i r st r ow ( a Row obj ect ) :
var f i r st Row = mySt at ement . get Row( ) ;
/ / Di spl ay t he i nf or mat i on r et r i eved:
consol e. pr i nt l n( "Fi r st name: " + f i r st Row. f i r st Name. val ue) ;
consol e. pr i nt l n( "Last name: " + f i r st Row. l ast Name. val ue) ;
consol e. pr i nt l n( "Soci al Secur i t y Number : " + f i r st Row. ssn. val ue) ;
If the column names contain spaces, the syntax can be modified as shown below:
/ / Cr eat e t he SQL st at ement :
var st = Sel ect \ "Fi r st Name\ ", \ "Last Name\ " f r om\ "Empl oyee I nf o\ " ;
/ / Execut e t he SQL st at ement :
mySt at ement . execut e( st ) ;
/ / Make t he next r ow ( t he f i r st r ow i n t hi s case) avai l abl e:
mySt at ement . next Row( ) ;
/ / Obt ai n t he i nf or mat i on cont ai ned i n t he f i r st r ow ( a Row obj ect ) :
var f i r st Row = mySt at ement . get Row( ) ;
/ / Di spl ay t he i nf or mat i on r et r i eved:
consol e. pr i nt l n( "Fi r st name: " + f i r st Row[ "Fi r st Name"] . val ue) ;
consol e. pr i nt l n( "Last name: " + f i r st Row[ "Last Name"] . val ue) ;
Acrobat JavaScript Scripting Guide 243
15
SOAP and Web Services
Introduction
The basis for most current models of web services is the Extensible Markup Language
(XML), which facilitates interoperability by permitting the exchange of information
between applications and platforms in a text-based manner. The Simple Object Access
Protocol (SOAP) is an XML-based messaging protocol used as a medium for information
and instruction exchange between web services. Information sent using the SOAP standard
is placed in a file called a SOAP envelope. The Web Services Description Language (WSDL) is
an XML-based standard for describing web services and their capabilities. Acrobats
support for these standards makes it possible for PDF documents to locate services,
understand their capabilities, and interact with them.
In order to guarantee interoperability between various platforms and applications, it is
necessary to exchange information that adheres to a standardized format for data types. To
address this need, the XML Schema Definition Language (XSD) provides a standard set of
definitions for the various data types that can be exchanged in SOAP envelopes.
Acrobat 7.0 provides support for the SOAP 1.1 and 1.2 standards in order to enable PDF
forms to communicate with web services. This support has made it possible to include both
SOAP header and body information, send binary data more efficiently, use document/literal
encoding, and facilitate authenticated or encrypted communications. In addition, it also
provides the ability to locate network services using DNS Service Discovery. All of this
makes it possible to integrate PDF files into existing workflows by binding XML forms to
schemas, databases, and web services. These workflows include the ability to share
comments remotely or invoke web services through form field actions.
Chapter Goals
At the end of this chapter, you will be able to:
Understand the support available for the SOAP standards.
Connect to a web service.
Exchange information with a web service.
Search and manage XML-based information.
Use DNS Service Discovery to locate network services.
Understand how to apply Acrobats SOAP support to various workflows.
SOAP and Web Services
Using SOAP and Web Services
15
244 Acrobat JavaScript Scripting Guide
Contents
Using SOAP and Web Services
Acrobat JavaScript provides a SOAPobject that encapsulates the support for web services
and service discovery. Through the usage of this object, you can extend and customize
your workflows by engaging in XML-based communication with remote servers.
The SOAPobject has a wi reDumpproperty that sends all XML requests and responses to
the JavaScript Console for debugging purposes. In addition, the SOAPobject provides the
methods described below in Table 15.1:
Topics
Using SOAP and Web Services
DNS Service Discovery
Managing XML-based Information
Workflow Applications
TABLE 15.1 SOAP Object
Method Description
connect Obtains a WSDL proxy object used to invoke a web
service
queryServi ces Locates network services using DNS Service Discovery
resol veServi ce Binds a service name to a network address and port
request The principal method used to invoke a web service
response A callback method used in asynchronous web method
calls
streamDecode Decodes a Base64 or Hex stream object
streamEncode Applies Base64 or Hex encoding to a stream object
streamFromStri ng Converts a string to a stream object
stri ngFromStream Converts a stream object to a string
Acrobat JavaScript Scripting Guide 245
SOAP and Web Services
Using SOAP and Web Services
15
Using a WSDL Proxy to Invoke a Web Service
When connecting to a web service, your Acrobat JavaScript code may use a WSDL proxy
object to generate a SOAP envelope. The envelope contains a request for the server to run a
web method on behalf of the client. To obtain the WSDL proxy object, invoke the SOAP
objects connect method, which accepts a single parameter containing the HTTP or
HTTPS URL of the WSDL document.
The returned proxy object contains the web methods available in the web service
described by the WSDL document. If the web service uses SOAP/RPC encoding, the
parameters in the proxy objects methods will match the order specified in the WSDL
document. If the web service uses document/literal encoding, the methods will accept a
single parameter describing the request message.
In the example shown below, a connection to a web service will be established, and its RPC-
encoded web methods will be invoked. Assume that myURL contains the address of the
WSDL document:
/ / Obt ai n t he WSDL pr oxy obj ect :
var myPr oxy = SOAP. connect ( myURL) ;
/ / I nvoke t he echoSt r i ng web ser vi ce, whi ch r equi r es a st r i ng par amet er :
var t est St r i ng = "Thi s i s a t est st r i ng. ";
var r esul t = myPr oxy. echoSt r i ng( t est St r i ng) ;
/ / Di spl ay t he r esponse i n t he consol e:
consol e. pr i nt l n( "Resul t i s " + r esul t ) ;
/ / I nvoke t he echoI nt eger web ser vi ce, whi ch r equi r es an i nt eger par amet er :
/ / Si nce J avaScr i pt does not suppor t XSD- compl i ant i nt eger val ues,
SOAP and Web Services Topics
Using a WSDL Proxy to Invoke a Web Service
Synchronous and Asynchronous Information Exchange
Using Document/Literal Encoding
Exchanging File Attachments and Binary Data
Converting Between String and ReadStream Information
Accessing SOAP Version Information
Accessing SOAP Header Information
Authentication
Error Handling
SOAP and Web Services
Using SOAP and Web Services
15
246 Acrobat JavaScript Scripting Guide
/ / We wi l l cr eat e an i nt eger obj ect compl i ant wi t h t he XSD st andar d:
var myI nt eger Obj ect = {
soapType: "xsd: i nt ",
soapVal ue: "10"
};
var r esul t = myPr oxy. echoI nt eger ( myI nt eger Obj ect ) ;
/ / Di spl ay t he r esponse i n t he consol e:
consol e. pr i nt l n( "Resul t i s " + r esul t ) ;
Note that each call to a web method generates a SOAP envelope that is delivered to the
web service, and that the return value is extracted from the corresponding envelope
returned by the web service. Also, since XML relies on text, there is no problem sending a
string to the web service. In the case of integers, however, it is necessary to create an XSD-
compliant object to represent the integer value. Acrobat JavaScript does support some of
the standard data types specified in the XSD. These are shown below in Table 15.2:
TABLE 15.2 XSD-Compliant Data Types Supported in JavaScript
JavaScript Type Equivalent XSD-Compliant Type
Stri ng xsd: stri ng
Number xsd: fl oat
Date xsd: dateTi me
Bool ean xsd: bool ean
ReadStream SOAP- ENC: base64
Array SOAP- ENC: Array
Acrobat JavaScript Scripting Guide 247
SOAP and Web Services
Using SOAP and Web Services
15
Synchronous and Asynchronous Information Exchange
The SOAPobjects request method may be used to establish either synchronous or
asynchronous communication with a web service, and provides extensive support for
SOAP header information, firewall support, the type of encoding used, namespace
qualified names, compressed or uncompressed attachments, the SOAP protocol version to
be used, authentication schemes, response style, and exception handling.
The request method accepts the parameters shown below in Table 15.3:
TABLE 15.3 Request Method
Parameter Description
cURL URL for SOAP HTTP endpoint
oRequest Object containing RPC information
oAsync Object used for asynchronous method invocation
cActi on SOAPAction header used by firewalls and servers to filter
requests
bEncoded Indicates whether SOAP encoding is used
cNamespace Message schema namespace when SOAP encoding is not used
oReqHeader SOAP header to be included with request
oRespHeader SOAP header to be included with response
cVersi on SOAP protocol version to be used (1.1 or 1.2)
oAuthenti cate Authentication scheme
cResponseStyl e The type and structure of the response information (JS, XML,
Message)
SOAP and Web Services
Using SOAP and Web Services
15
248 Acrobat JavaScript Scripting Guide
Establishing a Synchronous Connection
The SOAPobjects request method may be used to establish a synchronous connection
with a web service. To establish the connection and invoke the web methods, it is necessary
to provide the cURL, oRequest, and cActi onparameters. The example below
demonstrates how to invoke the same web services used in the previous example.
Similar to the parameter used in the connect method, the cURL parameter contains the
URL for the WSDL document. For the purposes of our example, assume that myURL
represents the WSDL document location.
The oRequest parameter is a fully qualified object literal specifying both the web method
name and its parameters, in which the namespace is separated from the method name by a
colon. It may also contain the following properties:
soapType: the SOAP type used for the value
soapVal ue: the SOAP value used when generating the message
soapName: the element name used when generating the SOAP message
soapAttri butes: an object containing the XML attributes in the request node
soapQName: the namespace-qualified name of the request node
soapAttachment: determines whether soapVal ueis encoded as an attachment
according to the SwA/MTOM

specification. In this case, soapVal uewill be a stream.


Assume that the namespace is http://mydomain/methods, the method name is
echoStri ng, and it accepts a string parameter called i nputStri ng. The following code
represents the oRequest parameter:
var echoSt r i ngRequest = {
"ht t p: / / mydomai n/ met hods: echoSt r i ng {
i nput St r i ng: "Thi s i s a t est . "
}
};
The cActi onparameter contains header information described by the WSDL document
that is used by firewalls to filter SOAP requests. In our example, we will supply the location
of the WSDL document:
var mySOAPAct i on = "ht t p: / / mydomai n/ met hods";
We may now invoke the echoStri ngweb method:
var r esponse = SOAP. r equest ( {
cURL: myURL,
oRequest : echoSt r i ngRequest ,
cAct i on: mySOAPAct i on
}) ;
Acrobat JavaScript Scripting Guide 249
SOAP and Web Services
Using SOAP and Web Services
15
In the case of synchronous requests such as this one, the value returned by the request
method (responsein this example) is an object containing the result of the web method,
which will be one of the Acrobat JavaScript types corresponding to XSD types. The default
format for the response value is an object describing the SOAP body (or header) of the
returned message.
NOTE: In the case of base64 or hex encoding of binary information, the type returned will
be a readStreamobject.
We may now obtain the returned value by using syntax that corresponds to the SOAP body
sent back by the web method:
var r esponseSt r i ng = "ht t p: / / mydomai n/ met hods: echoSt r i ngResponse";
var r esul t = r esponse[ r esponseSt r i ng] [ "r et ur n"] ;
/ / Di spl ay t he r esponse i n t he consol e:
consol e. pr i nt l n( "Resul t i s " + r esul t ) ;
Similarly, we can invoke the echoI nteger method. To do this, we will use the same value
for the cURL and cActi onparameters, and develop an oRequest parameter like the
one we used for the echoStri ngmethod. In this case, however, we must supply an XSD-
compliant object to represent the integer value:
var myI nt eger Obj ect = {
soapType: "xsd: i nt ",
soapVal ue: "10"
};
var echoI nt eger Request = {
"ht t p: / / mydomai n/ met hods: echoI nt eger {
i nput I nt eger : myI nt eger Obj ect
}
};
Now we may invoke the echoI nteger web method and display its results:
var r esponse = SOAP. r equest ( {
cURL: myURL,
oRequest : echoI nt eger Request ,
cAct i on: mySOAPAct i on
}) ;
var r esponseSt r i ng = "ht t p: / / mydomai n/ met hods: echoI nt eger Response";
var r esul t = r esponse[ r esponseSt r i ng] [ "r et ur n"] ;
/ / Di spl ay t he r esponse i n t he consol e:
consol e. pr i nt l n( "Resul t i s " + r esul t ) ;
SOAP and Web Services
Using SOAP and Web Services
15
250 Acrobat JavaScript Scripting Guide
Asynchronous Web Service Calls
The SOAPobjects request method may be used in conjunction with the response
method to establish asynchronous communication with a web service. In this case, the
request method calls a method on the notification object, and does not return a value.
Asynchronous communication is made possible by assigning a value to the request
methods aSync parameter, which is an object literal that must contain a function called
responsethat accepts two parameters: oResul t (the result object) and cURI (the URI
of the requested HTTP endpoint).
In the example below, the aSync parameter named mySync contains an attribute called
i sDone, which is used to monitor the status of the web service call, and an attribute called
val which will contain the result of the web service call. When the responsefunction is
called by the web service, it sets i sDoneto trueindicating that the asynchronous call has
been completed:
/ / Cr eat e t he aSync par amet er :
var mySync = {
i sDone: f al se,
val : nul l ,
/ / Gener at es t he r esul t of t he web met hod:
r esul t : f unct i on( cMet hod)
{
t hi s. i sDone = f al se;
var name = "ht t p: / / mydomai n/ met hods/ : " + cMet hod + "Response";
i f ( t ypeof t hi s. val [ name] == "undef i ned")
r et ur n nul l ;
el se
r et ur n t hi s. val [ name] [ "r et ur n"] ;
},
/ / The met hod cal l ed by t he web ser vi ce af t er compl et i on:
r esponse: f unct i on( oResul t , cURI )
{
t hi s. val = oResul t ;
t hi s. i sDone = t r ue;
},
/ / Whi l e t he web ser vi ce i s not done, do somet hi ng el se:
wai t : f unct i on( )
{
whi l e ( ! t hi s. i sDone) doSomet hi ngEl se( ) ;
}
};
Acrobat JavaScript Scripting Guide 251
SOAP and Web Services
Using SOAP and Web Services
15
/ / I nvoke t he web ser vi ce:
SOAP. r equest ( {
cURL: myURL,
oRequest : echoI nt eger Request ,
oAsync: mySync,
cAct i on: mySOAPAct i on
}) ;
/ / The r esponse cal l back f unct i on coul d cont ai n t he f ol l owi ng code:
/ / Handl e t he asynchr onous r esponse:
var r esul t = mySync. r esul t ( "echoI nt eger ") ;
/ / Di spl ay t he r esponse i n t he consol e:
consol e. pr i nt l n( "Resul t i s " + r esul t ) ;
Using Document/Literal Encoding
You may use document/literal encoding in your SOAP messages by assigning values to the
following parameters of the request method:
bEncoded: Assign a value of fal seto this parameter.
cNamespace: Specify a namespace for the message schema.
cResponseStyl e: Assign SOAPMessageStyl e. J S, SOAPMessageStyl e. XML,
or SOAPMessageStyl e. Messagevalue to this parameter.
Once this is done, fill the oRequest parameter with an object literal containing the data.
An example is given below:
/ / Set up t wo i nt eger val ues t o be added i n a web met hod cal l :
var aI nt = {soapType: "xsd: i nt ", soapVal ue: "10"};
var bI nt = {soapType: "xsd: i nt ", soapVal ue: "4"};
/ / Set up t he document l i t er al :
var r eq = {};
r eq[ "Add"] = {a: aI nt , b: bI nt };
/ / I nvoke t he web ser vi ce:
var r esponse = SOAP. r equest ( {
cURL: myURL,
oRequest : r eq,
cAct i on: mySOAPAct i on,
bEncoded: f al se,
cNamespace: myNamespace,
cResponseSt yl e: SOAPMessageSt yl e. Message
}) ;
/ / Di spl ay t he r esponse t o t he consol e:
var val ue = r esponse[ 0] . soapVal ue[ 0] . soapVal ue;
consol e. pr i nt l n( "ADD( 10 + 4) = " + val ue) ;
SOAP and Web Services
Using SOAP and Web Services
15
252 Acrobat JavaScript Scripting Guide
Exchanging File Attachments and Binary Data
As you learned earlier, the oRequest parameter provides alternative options for sending
binary-encoded data. This may be useful for sending information such as serialized object
data or embedded images. You may embed binary information in text-based format in the
SOAP envelope by using base64 encoding, or take advantage of the Soap With
Attachments

(SwA) standard or the Message Transmission Optimization Mechanism


(MTOM) to send the binary data in a more efficient format. Both SwA and MTOM can
significantly reduce network transmission time, file size, and XML parsing time.
SwA can be used by setting the oRequest parameters soapAttachment value to
true, as shown in the example below. Assume myStreamis a readStreamobject
containing binary data:
/ / Use t he SwA st andar d:
var SwARequest = {
"ht t p: / / mydomai n/ met hods: echoAt t achment ": {
dh:
{
soapAt t achment : t r ue,
soapVal ue: mySt r eam
}
}
};
var r esponse = SOAP. r equest ( {
cURL: myURL,
oRequest : SwARequest
}) ;
var r esponseSt r i ng = "ht t p: / / mydomai n/ met hods: echoAt t achment Response";
var r esul t = r esponse[ r esponseSt r i ng] [ "r et ur n"] ;
Acrobat JavaScript Scripting Guide 253
SOAP and Web Services
Using SOAP and Web Services
15
MTOM is used by additionally setting the request methods bEncodedparameter to
fal seand the cNamespaceparameter to an appropriate value. This is illustrated in the
following code, which creates an oRequest object:
/ / Use t he MTOMst andar d:
var MTOMRequest = {
"echoAt t achment DL": {
dh:
{
i ncl usi on:
{
soapAt t achment : t r ue,
soapVal ue: mySt r eam
}
}
}
};
var r esponse = SOAP. r equest ( {
cURL: myURL,
oRequest : MTOMRequest ,
bEncoded: f al se,
cNamespace: myNamespace
}) ;
Converting Between String and ReadStream Information
The SOAPobjects streamFromStri ngand stri ngFromStreammethods are useful
for converting between formats. The streamFromStri ngmethod is useful for
submitting data in a web service call, and the stri ngFromStreammethod is useful for
examining the contents of a response returned by a web service call. An example is shown
below:
/ / Cr eat e a ReadSt r eamobj ect f r oman XML st r i ng:
var mySt r eam= st r eamFr omSt r i ng( "<momname = ' Mar y' ></ mom>") ;
/ / Pl ace t he i nf or mat i on i n an at t achment :
t hi s. set Dat aObj ect Cont ent s( "or g. xml ", mySt r eam) ;
/ / Conver t t he ReadSt r eamobj ect back t o a st r i ng and di spl ay i n consol e:
consol e. pr i nt l n( st r i ngFr omSt r eam( mySt r eam) ) ;
SOAP and Web Services
Using SOAP and Web Services
15
254 Acrobat JavaScript Scripting Guide
Accessing SOAP Version Information
Acrobat 7.0 provides improved support for SOAP Version 1.1 and support for Version 1.2. To
encode the message using a specific version, assign one of the following values to the
request methods cVersi onparameter: SOAPVersi on. versi on_1_1(SOAP
Version 1.1) or SOAPVersi on. versi on_1_2(SOAP Version 1.2). Its usage is shown in
the following example:
var r esponse = SOAP. r equest ( {
cURL: myURL,
oRequest : myRequest ,
cVer si on: SOAPVer si on. ver si on_1_2
}) ;
Accessing SOAP Header Information
You may send SOAP header information to the web service using the request methods
oReqHeader parameter, and access the returned header information using the
oRespHeader parameter. The oReqHeader is identical to the oRequest object, with
the addition of two attributes:
soapActor: the SOAP actor that should interpret the header
soapMustUnderstand: determines whether the SOAP actor must understand the
header contents
Their usage is shown in the following example:
/ / Set up t he namespace t o be used:
var myNamespace = "ht t p: / / mydomai n/ met hods/ : ";
/ / Cr eat e t he oReqHeader par amet er :
var sendHeader = {};
sendHeader [ myNamespace + "t est Sessi on"] = {
soapType: "xsd: st r i ng",
soapVal ue: "Header Test St r i ng"
};
/ / Cr eat e t he i nt i al l y empt y oRespHeader par amet er :
var r esponseHeader = {};
r esponseHeader [ myNamespace + "echoHeader "] = {};
/ / Exchange header i nf or mat i on wi t h t he web ser vi ce:
var r esponse = SOAP. r equest ( {
cURL: myURL,
oRequest : {},
cAct i on: "ht t p: / / mydomai n/ met hods",
oReqHeader : sendHeader ,
oRespHeader : r esponseHeader
}) ;
Acrobat JavaScript Scripting Guide 255
SOAP and Web Services
Using SOAP and Web Services
15
Authentication
You may use the request methods oAuthenti cateparameter to specify how to
handle HTTP authentication or provide credentials used in Web Service Security (WS-
Security). Normally, if authentication is required, an interface will handle HTTP
authentication challenges for BASIC and DIGEST authentication using the SOAP header,
thus making it possible to engage in encrypted or authenticated communication with the
web service. This parameter helps to automate the authentication process.
The oAuthenti cateparameter contains two properties:
Username: A string containing the username
Password: A string containing the authentication credential
Its usage is shown in the following example:
/ / Cr eat e t he oAut hent i cat e obj ect :
var myAut hent i cat i on = {
User name: "myUser name",
Passwor d: "myPasswor d"
};
/ / I nvoke t he web ser vi ce usi ng t he user name and passwor d:
var r esponse = SOAP. r equest ( {
cURL: myURL,
oRequest : echoSt r i ngRequest ,
cAct i on: mySOAPAct i on
oAut hent i cat e: myAut hent i cat i on
}) ;
Error Handling
The SOAPobject provides extensive error handling capabilities within its methods. In
addition to the standard Acrobat JavaScript exceptions, the SOAPobject also provides
SOAPError and NetworkError exceptions.
A SOAPError exception is thrown when the SOAP endpoint returns a SOAPFault. The
SOAPError exception object will include information about the SOAP Fault code, the
SOAP Actor, and the details associated with the fault. The SOAPobjects connect and
request methods support this exception type.
A NetworkError exception is thrown when there is a problem with the underlying HTTP
transport layer or in obtaining a network connection. The NetworkError exception
object will contain a status code indicating the nature of the problem. The SOAPobjects
connect, request, and responsemethods support this exception type.
SOAP and Web Services
DNS Service Discovery
15
256 Acrobat JavaScript Scripting Guide
DNS Service Discovery
Suppose the exact URL for a given service is not known, but that it is available locally
because it has been published using DNS Service Discovery (DNS-SD). You may use the
SOAPobjects queryServi ces and resol veServi cemethods to locate the service
on the network and bind to it for communications.
The queryServi ces method can locate services that have been registered using
Multicast DNS (mDNS) for location on a local network link, or through unicast DNS for
location within an enterprise. The method performs an asynchronous search, and the
resultant service names can be subsequently bound to a network location or URL through
the SOAPobjects resol veServi cemethod.
The queryServi ces method accepts the following parameters:
cType: The DNS SRV service name (such as "http" or "ftp")
oAsync: A notification object used when services are located or removed (implements
addServi ces and removeServi ces methods). The notification methods accept a
parameter containing the following properties:
name: the unicode display name of the service
domai n: the DNS domain for the service
type: the DNS SRV service name (identical to cType)
aDomai ns: An array of domains for the query. The valid domains are
Servi ceDi scovery. l ocal (searches the local networking link using mDNS) and
Servi ceDi scovery. defaul t (searches the default DNS domain using unicast
DNS).
Acrobat JavaScript Scripting Guide 257
SOAP and Web Services
DNS Service Discovery
15
An example of its usage is shown below:
/ / Cr eat e t he oAsync not i f i cat i on obj ect :
var myNot i f i cat i ons = {
/ / Thi s met hod i s cal l ed whenever a ser vi ce i s added:
addSer vi ces: f unct i on( ser vi ces)
{
f or ( var i =0; i <ser vi ces. l engt h; i ++) {
var st r = "ADD: ";
st r += ser vi ces[ i ] . name;
st r += " i n domai n ";
st r += ser vi ces[ i ] . domai n;
consol e. pr i nt l n( st r ) ;
}
}
/ / Thi s met hod i s cal l ed whenever a ser vi ce i s r emoved:
r emoveSer vi ces: f unct i on( ser vces)
{
var st r = "DEL: ";
st r += ser vi ces[ i ] . name;
st r += " i n domai n ";
st r += ser vi ces[ i ] . domai n;
consol e. pr i nt l n( st r ) ;
}
};
/ / Per f or mt he ser vi ce di scover y:
SOAP. r equest Ser vi ces( {
cType: "ht t p",
oAsync: myNot i f i cat i ons,
aDomai ns: [ Ser vi ceDi scover y. l ocal , Ser vi ceDi scover . def aul t ]
}) ;
Once a service has been discovered, it can be bound through the SOAPobjects
resol veServi cemethod to a network address and port so that a connection can be
established. The resol veServi cemethod accepts the following parameters:
cType: the DNS SRV service name (such as "http" or "ftp").
cDomai n: the domain in which the service is located.
cServi ce: the service name to be resolved.
oAsync: a notification object used when the service is resolved. It implements a
resol vemethod that accepts parameters nStatus (0if successful) and oI nfo(used
if successful, contains a servi ceI nfoobject). The servi ceI nfoobject contains the
following properties:
target: the IP address or DNS name of the machine providing the service.
port: the port on the machine.
i nfo: an object with name/value pairs supplied by the service.
SOAP and Web Services
Managing XML-based Information
15
258 Acrobat JavaScript Scripting Guide
Its usage is illustrated in the following example:
/ / Cr eat e t he oAsync not i f i cat i on obj ect :
var myNot i f i cat i on = {
/ / Thi s met hod i s cal l ed when t he ser vi ce i s bound:
r esol ve: f unct i on( nSt at us, oI nf o)
{
/ / Pr i nt t he l ocat i on i f t he ser vi ce was bound:
i f ( nSt at us == 0) {
var st r = "RESOLVE: ht t p: / / ";
st r += oI nf o. t ar get ;
st r += ": ";
st r += oI nf o. por t ;
st r += "/ ";
st r += oI nf o. i nf o. pat h;
consol e. pr i nt l n( st r ) ;
}
/ / Di spl ay t he er r or code i f t he ser vi ce was not bound:
el se
consol e. pr i nt l n( "ERROR: " + nSt at us) ;
}
};
/ / At t empt t o bi nd t o t he ser vi ce:
SOAP. r esol veSer vi ce( {
cType: "ht t p",
cDomai n: "l ocal . ",
cSer vi ce: "My Web Ser ver ",
oAsync: myNot i f i cat i on
}) ;
Managing XML-based Information
Acrobat JavaScript provides support for XML-based information generated within your
workflows by providing an XMLDataobject, which represents an XML document tree that
may be manipulated via the XFA Data DOM. (For example, it is possible to apply an XSL
transformation (XSLT) to a node and its children using the XFAobject). The XMLData
object provides two methods for manipulating XML documents:
parse: Creates an object representing an XML document tree.
appl yXPath: Permits the manipulation and query of an XML document via XPath
expressions.
You may convert a string containing XML information into a document tree using the XML
objects parsemethod, and then manipulate and query the tree using its appl yXPath
method.
Acrobat JavaScript Scripting Guide 259
SOAP and Web Services
Managing XML-based Information
15
The XML objects parsemethod accepts two parameters:
param1: A string containing the text in the XML document.
param2: A boolean that determines whether the root node should be ignored.
Its usage is illustrated below:
/ / XML st r i ng t o be conver t ed i nt o a document t r ee:
myXML = "<f ami l y name = ' Robat ' >\
<momi d = ' m1' name = ' Mar y' gender = ' F' >\
<chi l d> m2 </ chi l d>\
<per sonal >\
<i ncome>75000</ i ncome>\
</ per sonal >\
</ mom>\
<son i d = ' m2' name = ' Bob' gender = ' M' >\
<par ent > m1 </ par ent >\
<per sonal >\
<i ncome>35000</ i ncome>\
</ per sonal >\
</ son>\
</ f ami l y>";
/ / Gener at e t he document t r ee:
var myTr ee = XML. par se( myXML, f al se) ;
/ / Pr i nt mom s name:
consol e. pr i nt l n( "Mom: " + myXML. f ami l y. mom. val ue) ;
/ / Change son s i ncome:
myXML, f ami l y. son. per sonal . i ncome. val ue = 40000;
The XML objects appl yXPathmethod accepts two parameters:
oXML: An object representing the XML document tree.
cXPath: A string containing an XPath query to be performed on the document tree.
In the following example, assume that myXML is the document tree obtained in the
previous example:
/ / Obt ai n mom s i nf or mat i on:
var momI nf o = XML. appl yXPat h( myXML, "/ / f ami l y/ mom") ;
/ / Save t he i nf or mat i on t o a st r i ng:
momI nf o. saveXML( ' pr et t y' ) ;
/ / Gi ve moma r ai se:
momI nf o. per sonal . i ncome. val ue = "80000";
SOAP and Web Services
Workflow Applications
15
260 Acrobat JavaScript Scripting Guide
Workflow Applications
One major impact that Acrobat JavaScript support for SOAP has is on collaboration
workflows. A SOAP-based collaboration server can be used to share comments remotely via
a Web-based comment repository. Through the DNS Service Discovery support, it is
possible to enable dynamic discovery of collaboration servers, initiation workflows, and RSS
feeds that can provide customized user interfaces, via XML, directly inside of Acrobat 7.0.
In addition, it is possible to deploy Web-based JavaScripts that always maintain the most
updated information and processes, and to connect to those scripts via form field actions
that invoke web services.
In the following example, a form is submitted to a server using a SOAP-based invocation:
/ / Popul at e t he cont ent obj ect wi t h f or mand SOAP i nf or mat i on:
var l ocat i on = "ht t p: / / adobe. com/ Acr obat / For m/ submi t / "
var f or mt ype = l ocat i on + "encodedTypes: For mDat a";
var cont ent = new Ar r ay( ) ;
f or ( var i = 0; i < document . numFi el ds; i ++) {
var name = document . get Nt hFi el dName( i ) ;
var f i el d = document . get Fi el d( name) ;
cont ent [ i ] = new Obj ect ( ) ;
cont ent [ i ] . soapType = f or mt ype;
cont ent [ i ] . name = f i el d. name;
cont ent [ i ] . val = f i el d. val ue;
}
/ / Send t he f or mt o t he ser ver :
SOAP. r equest ( {
cURL: cURL,
oRequest : {
l ocat i on + ": submi t For m":
{
cont ent : cont ent
}
},
cAct i on: l ocat i on + "submi t For m"
}
Acrobat JavaScript Scripting Guide 261
A
A Short Acrobat JavaScript FAQ
1
Where can JavaScripts be found and how are they used?
JavaScripts work with Acrobat on a variety of levels: the folder level, document level, and
field level, and batch level. These restrict the type of processing that can occur and are
loaded at different times.
How should I name my Acrobat form fields?
Acrobat form fields typically have names like Fi rstName, LastName, etc. This naming
convention is referred to as flat names. For many form applications, this flat hierarchy of
names is sufficient and works well. The problem with using flat names is that there is no
association between the fields.
Acrobat form field names can be more useful by creating a hierarchal structure. For
example, if we change Fi rstNameto Name. Fi rst and LastNameto Name. Last we
form a tree of fields. The period (.) separator is used in Acrobat Forms and denotes a
hierarchy shift. The Nameportion of these fields is the parent, and Fi rst and Last
become the children. While there is no limit to the depth to which a hierarchical name can
be constructed, it is important that the hierarchy remain manageable.
This hierarchy can be useful in a number of ways. It can speed up authoring and ease
manipulation of groups of fields in JavaScript. In addition, a form field hierarchy can
improve the performance of form applications when there are many fields in the
document.
Using our original flat names Fi rstName, Mi ddl eNameand LastName, you can change
the background color of these fields to yellow (e.g. to indicate missing data or emphasize
an important point). In this case, two lines of JavaScript code would be needed for each
field:
var name = t hi s. get Fi el d( "Fi r st Name") ;
name. f i l l Col or = col or . yel l ow;
name = t hi s. get Fi el d( "Mi ddl eName") ;
name. f i l l Col or = col or . yel l ow;
name = t hi s. get Fi el d( "Last Name") ;
name. f i l l Col or = col or . yel l ow;
1. Frequently Asked Questions
A Short Acrobat JavaScript FAQ
How should I name my Acrobat form fields?
A
262 Acrobat JavaScript Scripting Guide
With the hierarchy of Name. Fi rst, Name. Mi ddl eand Name. Last suggested above,
you can change the background color of these fields with just two lines of code instead of
six:
var name = t hi s. get f i el d( "Name") ;
name. f i l l Col or = col or . yel l ow
When using this hierarchy within a JavaScript, you can only change appearance-related
properties of the parent field, and those changes will propagate to all its children. However,
you cannot change the fields value. For example if you try the following script:
var name = t hi s. get Fi el d( "Name") ;
name. val ue = "Li ncol n";
the script will fail. Nameis considered a parent field. You can only change the value of
terminal fields (i.e. a field that does not have children like Last or Fi rst). The following
script executes correctly:
var f i r st = t hi s. get Fi el d( "Name. Fi r st ") ;
var l ast = t hi s. get Fi el d( "Name. Last ") ;
f i r st . val ue = "Abr aham";
l ast . val ue = "Li ncol n";
Acrobat JavaScript Scripting Guide 263
A Short Acrobat JavaScript FAQ
How do I use date objects?
A
How do I use date objects?
This section discusses the use of Dateobjects within Acrobat. The reader should be
familiar with the JavaScript Dateobject and the Uti l methods that process dates.
JavaScript Dateobjects actually contain both a date and a time. All references to Datein
this section refer to the date-time combination.
NOTE: All date manipulations in JavaScript, including those methods that have been
documented in this specification are Year 2000 (Y2K) compliant.
NOTE: When using the Dateobject, do not use the getYear() method, which returns
the current year minus 1900. Instead use the getFul l Year() method which
always returns a four digit year. For example,
var d = new Dat e( )
d. get Ful l Year ( ) ;
Converting from a Date to a String
Acrobat provides several date-related methods in addition to the ones provided by the
JavaScript Dateobject. These are the preferred methods of converting between Date
objects and strings. Because of Acrobats ability to handle dates in many formats, the Date
object does not always handle these conversions correctly.
To convert a Dateobject into a string, the pri ntdmethod of the Uti l object is used.
Unlike the built-in conversion of the Dateobject to a string, pri ntdallows an exact
specification of how the date should be formatted.
/ * Exampl e of ut i l . pr i nt d */
var d = new Dat e( ) ; / / Cr eat e a Dat e obj ect cont ai ni ng t he cur r ent dat e
/ * Cr eat e some st r i ngs f r omt he Dat e obj ect wi t h var i ous f or mat s wi t h
** ut i l . pr i nt d */
var s = [ "mm/ dd/ yy", "yy/ m/ d", "mmmmdd, yyyy", "dd- mmm- yyyy" ] ;
f or ( var i = 0; i < s. l engt h; i ++) {
/ * pr i nt t hese st r i ngs t o t he consol e */
consol e. pr i nt l n( "For mat " + s[ i ] + " l ooks l i ke: "
+ ut i l . pr i nt d( s[ i ] , d) ) ;
}
The output of this script would look like:
For mat mm/ dd/ yy l ooks l i ke: 01/ 15/ 05
For mat yy/ mm/ dd l ooks l i ke: 05/ 1/ 15
For mat mmmmdd, yyyy l ooks l i ke: J anuar y 15, 2005
For mat dd- mmm- yyyy l ooks l i ke: 15- J an- 2005
NOTE: It is advised that you output dates with a four digit year to avoid ambiguity.
A Short Acrobat JavaScript FAQ
How do I use date objects?
A
264 Acrobat JavaScript Scripting Guide
Converting from a string to a date
To convert a string into a Dateobject, use the Uti l objects scandmethod. It accepts a
format string that it uses as a hint as to the order of the year, month, and day in the input
string.
/ * Exampl e of ut i l . scand */
/ * Cr eat e some st r i ngs cont ai ni ng t he same dat e i n di f f er i ng f or mat s. */
var s1 = "03/ 12/ 97";
var s2 = "80/ 06/ 01";
var s3 = "December 6, 1948";
var s4 = "Sat ur day 04/ 11/ 76";
var s5 = "Tue. 02/ 01/ 30";
var s6 = "Fr i day, J an. t he 15t h, 1999";
/ * Conver t t he st r i ngs i nt o Dat e obj ect s usi ng ut i l . scand */
var d1 = ut i l . scand( "mm/ dd/ yy", s1) ;
var d2 = ut i l . scand( "yy/ mm/ dd", s2) ;
var d3 = ut i l . scand( "mmmmdd, yyyy", s3) ;
var d4 = ut i l . scand( "mm/ dd/ yy", s4) ;
var d5 = ut i l . scand( "yy/ mm/ dd", s5) ;
var d6 = ut i l . scand( "mmmmdd, yyyy", s6) ;
/ * Pr i nt t he dat es t o t he consol e usi ng ut i l . pr i nt d */
consol e. pr i nt l n( ut i l . pr i nt d( "mm/ dd/ yyyy", d1) ) ;
consol e. pr i nt l n( ut i l . pr i nt d( "mm/ dd/ yyyy", d2) ) ;
consol e. pr i nt l n( ut i l . pr i nt d( "mm/ dd/ yyyy", d3) ) ;
consol e. pr i nt l n( ut i l . pr i nt d( "mm/ dd/ yyyy", d4) ) ;
consol e. pr i nt l n( ut i l . pr i nt d( "mm/ dd/ yyyy", d5) ) ;
consol e. pr i nt l n( ut i l . pr i nt d( "mm/ dd/ yyyy", d6) ) ;
The output of this script would look like:
03/ 12/ 1997
06/ 01/ 1980
12/ 06/ 1948
04/ 11/ 1976
01/ 30/ 2002
01/ 15/ 1999
Unlike the date constructor (new Dat e( . . . ) ), scandis rather forgiving in terms of the
string passed to it.
NOTE: Given a two digit year for input, scandresolves the ambiguity as follows: if the year
is less than 50 then it is assumed to be in the 21st century (i.e. add 2000), if it is
greater than or equal to 50 then it is in the 20th century (add 1900). This heuristic is
often known as the Date Horizon.
Acrobat JavaScript Scripting Guide 265
A Short Acrobat JavaScript FAQ
How do I use date objects?
A
Date arithmetic
It is often useful to do arithmetic on dates to determine things like the time interval
between two dates or what the date will be several days or weeks in the future. The
JavaScript Dateobject provides several ways to do this. The simplest and possibly most
easily understood method is by manipulating dates in terms of their numeric
representation. Internally, JavaScript dates are stored as the number of milliseconds (one
thousand milliseconds is one whole second) since a fixed date and time. This number can
be retrieved through the valueOf method of the Dateobject. The Dateconstructor allows
the construction of a new date from this number.
/ * Exampl e of dat e ar i t hmet i c. */
/ * Cr eat e a Dat e obj ect wi t h a def i ni t e dat e. */
var d1 = ut i l . scand( "mm/ dd/ yy", "4/ 11/ 76") ;
/ * Cr eat e a dat e obj ect cont ai ni ng t he cur r ent dat e. */
var d2 = new Dat e( ) ;
/ * Number of seconds di f f er ence. */
var di f f = ( d2. val ueOf ( ) - d1. val ueOf ( ) ) / 1000;
/ * Pr i nt some i nt er est i ng st uf f t o t he consol e. */
consol e. pr i nt l n( "I t has been "
+ di f f + " seconds si nce 4/ 11/ 1976") ;
consol e. pr i nt l n( "I t has been "
+ di f f / 60 + " mi nut es si nce 4/ 11/ 1976") ;
consol e. pr i nt l n( "I t has been "
+ ( di f f / 60) / 60 + " hour s si nce 4/ 11/ 1976") ;
consol e. pr i nt l n( "I t has been "
+ ( ( di f f / 60) / 60) / 24 + " days si nce 4/ 11/ 1976") ;
consol e. pr i nt l n( "I t has been "
+ ( ( ( di f f / 60) / 60) / 24) / 365 + " year s si nce 4/ 11/ 1976") ;
The output of this script would look something like:
I t has been 718329600 seconds si nce 4/ 11/ 1976
I t has been 11972160 mi nut es si nce 4/ 11/ 1976
I t has been 199536 hour s si nce 4/ 11/ 1976
I t has been 8314 days si nce 4/ 11/ 1976
I t has been 22. 7780821917808 year s si nce 4/ 11/ 1976
A Short Acrobat JavaScript FAQ
How can I make restricted Acrobat JavaScript methods available to users?
A
266 Acrobat JavaScript Scripting Guide
The following example shows the addition of dates.
/ * Exampl e of dat e ar i t hmet i c. */
/ * Cr eat e a dat e obj ect cont ai ni ng t he cur r ent dat e. */
var d1 = new Dat e( ) ;
/ * numcont ai ns t he numer i c r epr esent at i on of t he cur r ent dat e. */
var num= d1. val ueOf ( ) ;
/ * Add t hi r t een days t o t oday s dat e, i n mi l l i seconds. */
/ * 1000 ms/ sec, 60 sec/ mi n, 60 mi n/ hour , 24 hour s/ day, 13 days */
num+= 1000 * 60 * 60 * 24 * 13;
/ * Cr eat e our new dat e, 13 days ahead of t he cur r ent dat e. */
var d2 = new Dat e( num) ;
/ * Pr i nt out t he cur r ent dat e and our new dat e usi ng ut i l . pr i nt d */
consol e. pr i nt l n( "I t i s cur r ent l y: "
+ ut i l . pr i nt d( "mm/ dd/ yyyy", d1) ) ;
consol e. pr i nt l n( "I n 13 days, i t wi l l be: "
+ ut i l . pr i nt d( "mm/ dd/ yyyy", d2) ) ;
The output of this script would look something like:
I t i s cur r ent l y: 01/ 15/ 1999
I n 13 days, i t wi l l be: 01/ 28/ 1999
How can I make restricted Acrobat JavaScript methods available to
users?
Many of the methods in Acrobat JavaScript are restricted for security reasons, and their
execution is only allowed during batch, console or menu events. The Acrobat JavaScript
Scripting Reference identifies these methods by a padlock symbol in the quick bar. 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 Acrobat 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
Digital IDs > Trusted Identities in Acrobats main menu.
Acrobat JavaScript Scripting Guide 267
A Short Acrobat JavaScript FAQ
How can I make my documents accessible?
A
How can I make my documents accessible?
Accessibility of electronic information is an ever-increasingly important issue. Creating
forms that adhere to the accessibility tips below will make your forms more easily usable by
all users. The following is a set of guidelines to follow in order to make a form minimally
accessible.
Document Metadata
The metadata for a document can be specified using File > Document Properties >
Description or Advanced > Document Metadata.
When a document is opened, saved, printed, or closed, the document title is spoken to the
user. If the title has not been specified in the Document Metadata, then the file name is
used. Often, file names are abbreviated or changed, so it is advised that the document
author specify a title for the document. For example, if a document has a file name of
"I RS1040. pdf " a good document title would be "Form 1040: U.S. Individual Income Tax
Return for 2004".
In addition, third-party screen readers usually read the title in the window title bar. You can
specify what appears in the window title bar by using File > Document Properties >
Initial View and in the Window Options, choose to Show either the File Name or
Document Title.
Filling all of the additional metadata associated with a document (Author, Subject,
Keywords) also makes it more easily searchable using Acrobat Search and Internet search
engines.
Short Description
Every field that is not hidden must contain a user-friendly name (tooltip). This name is
spoken when a user acquires the focus to that field and should give an indication of the
fields purpose. For example, if a field is named "name. fi rst", a good short description
would be "Fi rst Name". The name should not depend on the surrounding context. For
instance, if both the main section and spouse section of a document contain a "Fi rst
Name" field, the field in the spouse section might be named "Spouse' s Fi rst Name".
This description is also displayed as a tooltip when the user positions the mouse over the
field.
Setting Tab Order
In order to traverse the document in a reasonable manner, the tab order for the fields must
be set in a logical way. This is important as most users use the tab key to move through the
document. For visually impaired users, this is a necessity as they cannot rely on mouse
movements or visual cues.
A Short Acrobat JavaScript FAQ
How can I define global variables in JavaScript?
A
268 Acrobat JavaScript Scripting Guide
Pressing the tab (shift-tab) key when there is no form field that has the keyboard focus will
cause the first (last) field in the tab order on the current page to become active. If there are
no form fields on the page then Acrobat will inform the user of this via a speech cue.
Using tab (shift-tab) while a field has the focus tabs forward (backward) in the tab order to
the next (previous) field. If the field is the last (first) field on the page and the tab (shift-tab)
key is pressed, the focus is set to the first (last) field on the next (previous) page if one exists.
If such a field does not exist, then the focus "loops" to the first (last) field on the current
page.
Reading Order
The reading order of a document is determined by the Tags tree. In order for a form to be
used effectively by a visually impaired user, the content and fields of a page must be
included in the Tags tree. The Tags tree can also indicate the tab order for the fields on a
page.
How can I define global variables in JavaScript?
The Acrobat extensions to JavaScript define a Gl obal object to which you can attach
global variables as properties. To define a new global variable called 'myVari abl e' and
set it equal to the null string, you would type:
gl obal . myVar i abl e = "";
All of your scripts, no matter where they are in a document, will now be able to reference
this variable.
Making Global Variables Persistent
Global data does not persist across user sessions unless you specifically make your global
varaibles persistent. The predefined Gl obal object has a method designed to do this. To
make a variable named 'myVari abl e' persist across sessions, use the following syntax:
gl obal . set Per si st ent ( "myVar i abl e", t r ue) ;
In future sessions, the variable will still exist with its previous value intact.
Acrobat JavaScript Scripting Guide 269
A Short Acrobat JavaScript FAQ
How can I hide an Acrobat form field based on the value of another?
A
How can I hide an Acrobat form field based on the value of another?
Use the di spl ay method of the Gl obal object:
var t i t l e = t hi s. get Fi el d( "t i t l e") ;
i f ( t hi s. get Fi el d( "showTi t l e") . val ue == "Of f ")
t i t l e. di spl ay = di spl ay. hi dden;
el se
t i t l e. di spl ay = di spl ay. vi si bl e;
How can I query an Acrobat form field value in another open form?
One way would be to use the Gl obal object's subscri bemethod to make the field(s) of
interest available to others at runtime. For example, a form may contain a document-level
script (invoked when that document is first opened) that defines a global field value of
interest:
f unct i on Publ i shVal ue( xyzFor m_f i el dVal ue_of _i nt er est ) {
gl obal . xyz_val ue = xyzFor m_f i el dVal ue_of _i nt er est ;
}
Then, when your document (Document A) wants to access the value of interest from the
other form (Document B), it can subscribe to the variable in question:
gl obal . subscr i be( "xyz_val ue", Val ueUpdat e) ;
In this case, ValueUpdate refers to a user-defined function that is called automatically
whenever xyz_val uechanges. If you were using xyz_val uein Document A as part of a
field called MyFi el d, you might define the callback function this way:
f unct i on Val ueUpdat e( newVal ue ) {
t hi s. get Fi el d( "MyFi el d") . val ue = newVal ue; }
How can I intercept keystrokes one by one as they occur in Acrobat
forms?
Create a Custom Keystroke Filter script (see the Format tab in the Properties dialog for any
text field or combo box ) in which you examine the value of event. change. By altering
this value, you can alter the user's input as it takes place.
A Short Acrobat JavaScript FAQ
How can I construct my own colors?
A
270 Acrobat JavaScript Scripting Guide
How can I construct my own colors?
Colors are Array objects in which the first item in the array is a string describing the color
space ('G' for grayscale, 'RGB' for RGB, 'CMYK' for CMYK) and the following items are numeric
values for the respective components of the color space. Hence:
col or . bl ue = new Ar r ay( "RGB", 0, 0, 1) ;
col or . cyan = new Ar r ay( "CMYK", 1, 0, 0, 0) ;
To make a custom color, just declare an array containing the color-space type and channel
values you want to use.
How can I prompt the user for a response in a dialog?
Use the responsedefined in the Appobject. This method displays a dialog box
containing a question and an entry field for the user to reply to the question. (Optionally,
the dialog can have a title or a default value for the answer to the question.) The return
value is a string containing the users response. If the user clicks Cancel, the response is the
null object.
var di al ogTi t l e = "Pl ease Conf i r m";
var def aul t Answer = "No. ";
var r epl y = app. r esponse( "Di d you r eal l y mean t o t ype t hat ?",
di al ogTi t l e, def aul t Answer ) ;
How can I fetch an URL from JavaScript?
Use the getURL method of the doc object. This method retrieves the specified URL over
the internet using a GET. If the current document is being viewed inside the browser or
Acrobat Web Capture is not available, it uses the Weblink plug-in to retrieve the requested
URL.
How can I determine if the mouse has entered/left a certain area on
an Acrobat form?
Create an invisible, read-only text field at the place where you want to detect mouse entry
or exit. Then attach JavaScripts to the mouse-enter and/or mouse-exit actions of the field.
Acrobat JavaScript Scripting Guide 271
A Short Acrobat JavaScript FAQ
How can I disallow changes in scripts contained in my document?
A
How can I disallow changes in scripts contained in my document?
Go to File > Document Properties and select the Security tab. Set up either password or
certificate security for the document by clicking Security Method and choosing either
Password Security or Certificate Security. In the Permissions area of the dialog box that
pops up, click Changes Allowed and select any of the options except Any except
extracting pages. You can verify that changes to scripts have been disabled by returning
to the Security tab. In the Document Restrictions Summary portion, Changing the
Document should be set to Not Allowed.
How can I hide scripts contained in my document?
Go to File > Document Properties and select the Security tab. Set up either password or
certificate security for the document by clicking Security Method and choosing either
Password Security or Certificate Security. In the Permissions area of the dialog box that
pops up, ensure that Enable copying of text, images, and other content is unchecked.
You can verify that changes to scripts have been disabled by returning to the Security tab.
In the Document Restrictions Summary portion, Changing the Document should be set
to Not Allowed.
A Short Acrobat JavaScript FAQ
How can I hide scripts contained in my document?
A
272 Acrobat JavaScript Scripting Guide
Acrobat JavaScript Scripting Guide 273
Index
A
Acrobat
plug-in 14
Acrobat Database Connectivity 24, 238
Acrobat forms 87
Acrobat form field 89
action types 179
ADBC 24, 237, 238
getDataSourceList 238
newConnection 238, 239
adding security to attachments 217
additional usage rights 124, 227
ADM 26, 159, 160
ADO 27, 114
Adobe Dialog Manager 26, 159
Adobe Document Server 228
Adobe LiveCycle Designer 87, 108, 109
Adobe LiveCycle Policy Server 213
Adobe Reader-Extension Root Certificate
Authority 228
Adobe.PPKLite 220
Adobe.PPKMS 220, 223
Adobe.PPKMS.ADSI 223
ADSI 223
Advanced Editing Toolbar 53
advanced search options 193
annot
AP 129, 134, 137
attachIcon 130
destroy 136
hidden 138
setProps 133, 136, 137
soundIcon 130
transitionToState 137
annotations 20
app 22
execDialog 162
fullscreen 182
hideMenuItem 183
hideToolbarButton 183
newDoc 72
openDoc 69, 72, 139
openInPlace 175
printColorProfiles 79, 82
printerNames 79
app.media 145, 151, 182
getPlayers 145, 151
windowType 182
Approval 135, 140
approval stamp 209
Array 97
sort 97
asynchronous communication 250
B
base64 encoding 252
BASIC 255
batch 139
binary data 252
bookmark
color 181
hierarchy 173
boolean queries 196
breakpoints 58
conditional 59
define 60
button 186
buttonAlignX 95
buttonAlignY 95
buttonScaleHow 95
buttonScaleWhen 95
buttonSetIcon 186
highlight 94, 181
setIcon 95
C
calculation 101, 106
274 Acrobat JavaScript Scripting Guide
Index
call stack 55
catalog 191, 197
getIndex 198
catalogJob 197
certificate 119, 202, 203
default security 220, 222
public key 223
certificate authority 219
certifying a document 208
check box 96
defaultIsChecked 96
code
formatting 32
Collab 126, 127
addAnnotStore 127
addStateModel 126
getStateInModel 126
removeStateModel 126
setStoreSettings 127
transitionToState 126
Column 237
ColumnInfo 237, 240
combining PDF documents 69
combo box 97
commitOnSelChange 97
doNotSpellCheck 97
editable 97
setItems 97
comment
aggregate for use in Excel 139
change appearance 137
change status 137
compare 139
find 138
import and export 139
list 136, 137
place checkmarks 137
preferences 133
repository 20
show or hide 138
sort 138
connection 24, 237, 239
getColumnList 240
getTableList 240
newStatement 241
console 23, 29, 31, 46
core JavaScript 13
creating a digital ID 220
cropping pages 70
D
database 20, 24, 86, 237
DataSourceInfo 237, 238
dbg 23
debugger 23, 29, 45, 48
buttons 50
debug from start 59
dialog 23, 162
load 162
store 162
dictionary 132
add words 133
DIGEST 255
digital ID 218
provider 219
digital signature preferences 210
dirConnection 119, 202, 203, 212
search 203, 212
setOutputFields 212
directory 119, 202, 211, 223
connect 212
DirectoryInformation 211
DNS 24
DNS Service Discovery 256
DNS-SD 256
mDNS 256
Multicast DNS 256
Service Discovery 243
unicast DNS 256
doc 22
addField 89
addLink 132, 176
addRecipientListCryptFilter 217
addThumbnails 171
addWatermarkFromFile 74, 134
addWatermarkFromText 74, 75, 134, 135
addWeblinks 176
Acrobat JavaScript Scripting Guide 275
Index
bookmarkRoot 171
bookmark 171
children 172
createChild 172
createDataObject 139
createTemplate 156
deletePages 72
dynamicXFAForm 114
encryptForAPS 205, 214, 216
encryptForRecipients 120, 124, 202, 203, 211
encryptUsingPolicy 205, 214
exportAsFDF 139
exportAsXFDF 139
exportDataObject 131, 139
getAnnot 138
getAnnots 136, 138, 139
getDataObjectContents 131, 132
getOCGOrder 187
getOCGs 187
getPageBox 70
getPageLabel 185
getPageRotation 71
getPageTransitions 184
getPrintParams 80
gotoNamedDest 178
icons 141
importAnFDF 139
importAnXFDF 139
importDataObject 69
importIcon 95
importSound 130
insertPages 69, 70, 72
layout 182
mailDoc 125
mailForm 115
openDataObject 115
pageNum 183
print 79
removeDataObject 132
removeField 208
removeLinks 177
removeThumbnails 171
replacePages 70, 72
resetForm 96
saveAs 75, 115
setDataObjectContents 132
setOCGOrder 187
setPageAction 171, 178
setPageBoxes 70
setPageLabels 185
setPageRotations 71
setPageTransitions 184
spellDictionaryOrder 132
spellLanguageOrder 133
syncAnnotScan 136
templates 156
zoom 182
zoomType 183
doc object 22
doc.media 145
canPlay 153
getOpenPlayers 145
document/literal encoding 251
documents
manipulating 22
dynamic XML forms architecture 108
E
ECMAScript 13
Editing Toolbar, Advanced 53
Editor 29, 38, 42
eEnvelope 217
enabling JavaScript 33
encryption 202
documents 203
encrypt for a list of recipients 211
event 25
Excel 139
Executing 31
EXIF 24
export value 90
Extensible Markup Language 243
external editor 42
F
FDF 115, 208
276 Acrobat JavaScript Scripting Guide
Index
signatureValidate 208
field 92
border style 94
button 94
character limit 114
display 94
hierarchy 103
name 92
print 79
rotation 95
setAction 95
setExportValues 90
signatureSign 202
strokeColor 94
file attachment 130
file creation 68
flattening layers 189
font options 83
footers 75
form 26, 85, 88
accessible 117
creation 88
email 115
export 115
save 115
securing 205
spell-check 114
web-ready 107
format options 92
formatting
code 32
fullScreen 184
defaultTransition 184
transitions 184
G
global 23
global submit 115
Group 203
permissions 203, 231
userEntities 203
H
Hanko 140, 141
headers 75
highlight annotation 102
HTML JavaScript 14
HTTP 24, 245
authentication 255
HTTPS 245
I
index 191, 197
build 198
file 196
initial view 182
Inkan 141
inspect details window 55, 56, 57
Interrupt 60
J
JavaScript
core 13
creating simple scripts 67, 77, 85, 123, 143, 155,
159, 191, 201
enabling 33
external editors 41
formatting 32
objects 21
JavaScript objects
doc 22
L
language 133
link 175
add 176
annotation 132
borderColor 181
remove 177
setAction 177
list box 99
multipleSelection 99
Acrobat JavaScript Scripting Guide 277
Index
setAction 99
LiveCycle
Designer 228
Forms 228
Reader Extensions 227, 228
Lock 99
action 99
fields 99
M
magnification 182
mdp 202
media 143
media player 144
MediaPlayer 146
MediaSettings 146, 153
bgColor 153
merging layers 189
Message Transmission Optimization Mechanism 252
metadata 199
Microsoft Active Directory Script Interface 223
MIME 69, 145
modification detection and prevention 202
Monitor 149, 150
Monitors 149
movie 143, 151
MTOM 252, 253
multimedia preferences 153
Multipurpose Internet Mail Extensions 69
N
named destination 178
navigation 170
with layers 187
NetworkError 255
O
Object Identifier 228
OCG 74, 187, 188
ODBC 24, 237, 238
OID 228
online collaborative review 123
online team review 20
Open Database Connectivity 237
optional content group 74
P
page 72
action 171
delete 72
insert 72
layout 182
numbering 185
replace 72
transitions 184
password 202, 210
PDF documents. <Emphasis>See documents
playback settings 146
PlayerInfo 145
PlayerInfoList 145
select 145
plug 20
PostScript options 82
Preface 13
print
documents 79
options 82
production 78
printParams 78, 80, 82
private key 219
public key 219
R
radio buttons 90, 99
readStream 249
Really Simple Syndication 233
relative distinguished name 220
Rendition 146
getPlaySettings 146, 153
select 152
rendition 152
review, markup, and approval 26, 123
RMA 123
278 Acrobat JavaScript Scripting Guide
Index
email-based 124
rotated user space 89, 103
rotating pages 71
row 237, 242
RSS 233
S
screen annot 151
script
batch-level 65
document-level 65
field-level 65
folder-level 54, 64
search 24, 191, 192
query 193
wordMatching 193
security 20, 24, 119, 121, 202, 203
chooseRecipientsDialog 203
chooseSecurityPolicy 205, 214
getHandler 206
getSecurityPolicies 205, 213
handler 206
policies 205, 213
corporate policy 213
custom policy 213
token-based security 226
tokenized Acrobat JavaScript security model 226
validateSignaturesOnOpen 210
securityHander 119
securityHandler 202, 206, 211, 220, 221
DigitalIDs 221
login 206
newUser 220
securityPolicy 202, 205, 213
securityPolicyOptions 213
SeedValue 207
self-sign credential 220
sharing digital ID certificates 224
signature 99, 205
remove 208
setAction 99
setLock 99, 205
signatureSign 99
signature handler 219
signatureInfo 119, 202, 218, 219
certificates 219, 225
trustFlags 224
SignatureParameters 209
Simple Object Access Protocol 243
SOAP 24, 126, 127, 243, 244
collaboration server 260
connect 127, 245
envelope 243, 245
header 247, 254
queryServices 256
request 127, 247
resolveService 256
response 127
Soap With Attachments 252
SOAPError 255
streamFromString 253
stringFromStream 253
version 254
wireDump 244
sound 143, 152
sound attachment 130
spell 132
addWord 133
checkWord 132
dictionaryNames 132
languages 133
SQL 24, 237, 238, 241
stamp 134
statement 24, 237, 239, 241
execute 241
getRow 242
nextRow 242
synchronous connection 248
T
tab order 105
TableInfo 237, 240
tagged annot 117, 119
template 155, 156
spawn 156, 157
Text 117
Acrobat JavaScript Scripting Guide 279
Index
this 22
thumbnails 171
tile marks 82
Toolbar
Advanced Editing 53
triggers 180
trust level 224
trusted user identities 208
TTS 117
U
usage rights 27, 211
UserEntity 203
Util 23
V
validation 101
viewing modes 182
full screen 182
regular 182
W
watches list 57
watermark 134
web method 246
web services 20, 24, 75, 86, 87, 243, 244
Web Service Security 255
Web Services Description Language 243
What Can You Do with Acrobat JavaScript? 19
Windows certificate security 223
workflows 26
WSDL 24, 243
proxy 245
X
XDP 115
XFA 109
appModel 109
DOM 112
Tree 112
treeList 112
XFDF 115
XML 24, 67, 75, 112, 243
applyXPath 258
DOM 112
forms 85, 87
Node 112
parse 258
Schema Definition Language 243
XMLData 258
XMP metadata 199
XPath 24, 112
XSL transform 112
Z
zoom type 183
280 Acrobat JavaScript Scripting Guide
Index

You might also like