Adobe Acrobat 7.0 Acrobat JavaScript Scripting 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, me chanical, photocopying, recording 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 refere PostScript language as defined by Adobe Systems Incorporated unle ss otherwise stated. The name PostScript also is used as a pro duct trademark for Adobe Systems implementation Except as otherwise stated, any reference to a PostScript printing devi ce, PostScript display device, or similar item refer s 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 ei ther 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 countri es. PowerPC is a registered trademark of IBM Corporation in the United States . ActiveX, Microsoft, Windows, and Windows NT are either regis 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 construe d as a commitment by Adobe Systems Incorporated. Adobe Systems Incorporated assumes no responsibility or liability for any errors or i naccuracies, makes no warranty of any kind (express, implied, or statutory) with respect to this publicatio n, and expressly disclaims any an d all warranties of merchantability, fitness for particular purp oses, and noninfringement of third party rights. Acrobat JavaScript Scripting Guide 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 1Acrobat JavaScript Overvi ew . . . . . . . . . . . . . . . .19 Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 Chapter Goals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 Acrobat JavaScript Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 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 2Acrobat JavaScript Tools . . . . . .29 Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 Chapter Goals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 Acrobat JavaScript Scripting Guide Using the Acrobat JavaScript Console. . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 Opening the JavaScript Console. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 Executing JavaScript. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 Formatting Code. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 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 Acrobat JavaScript Scripting Guide Calculator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60 Summary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62 Chapter 3Acrobat 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 4Creating and Modifyi ng 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 5Print 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 Acrobat JavaScript Scripting Guide Chapter 6Using 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 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 Making Forms Accessible . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .11 Text-To-Speech . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .11 Tagging Annotations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .119 Using JavaScript to Secure Forms. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .119 Chapter 7Review, Markup, and Approval . . . . . . . . 123 Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .123 Chapter Goals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 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 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .12 Acrobat JavaScript Scripting Guide Highlighting, Crossing Out, and Underlining Text . . . . . . . . . . . . . . . . . . . .129 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 10Modifying the User Inte rface . . . . . . . . . 159 Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .159 Chapter Goals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 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. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .18 Working with PDF Layers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .18 About PDF Layers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .187 Navigating with Layers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .187 Editing the Properties of PDF Layers . . . . . . . . . . . . . . . . . . . . . . . . . .188 Merging Layers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .18 Flattening PDF Layers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .189 Combining PDF Layered Documents . . . . . . . . . . . . . . . . . . . . . . . . . .189 Chapter 11Search and Index Essentia ls . . . . . . . . . . . . . . . 191 Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .191 Chapter Goals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .191 Searching for Text in PDF Documents. . . . . . . . . . . . . . . . . . . . . . . . . . . .192 Acrobat JavaScript Scripting Guide 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 12Security . . . . . . . . . . . . 201 Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .201 Chapter Goals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2 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 13Rights-Enabled PD F Files . . . . . . . . . . . 227 Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .227 Chapter Goals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2 Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .227 Additional Usage Rights . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228 Acrobat JavaScript Scripting Guide LiveCycle Reader Extensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .228 Writing Acrobat JavaScript for Reader. . . . . . . . . . . . . . . . . . . . . . . . . . . .229 Enabling Collaboration. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .233 Chapter 14Interacting with Databases . . . . . . . . . . 237 Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .237 Chapter Goals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2 Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .237 Introduction to ADBC. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .238 Establishing an ADBC Connection. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .238 Executing SQL Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .241 Chapter 15SOAP and Web Services. . . . . . . . . . 243 Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .243 Chapter Goals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2 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 Appendix AA Short Acrobat JavaSc ript 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? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .26 Converting from a Date to a String . . . . . . . . . . . . . . . . . . . . . . . . . . .263 Converting from a string to a date. . . . . . . . . . . . . . . . . . . . . . . . . . . .264 Date arithmetic. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265 Acrobat JavaScript Scripting Guide 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 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .26 Setting Tab Order . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .26 Reading Order. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .26 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 Acrobat JavaScript Scripting Guide Acrobat JavaScript Scripting Guide Preface Preface 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 What is Acrobat JavaScript? Acrobat JavaScript is a language based on th e core of JavaScript version 1.5 of ISO-16262, formerly known as ECMAScript, an object-oriented scripting language developed by , and Preface 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 Acrobat JavaScript does not have access to objects within an HTML page. Similarly, HTML JavaScript cann ot access objects within a PDF file. HTML JavaScript is able to manipulate such objects as . Acrobat JavaScript cannot access this particular object bu t it can manipulate PDF-specific objects. If you have used previous versions of Acro bat 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 Acrobat JavaScript Scripting Guide Preface How To Use This Guide Purpose and Scope The purpose of this guide is to: Describe how you can use the Acrobat JavaScri pt language as the primary vehicle with which to develop and deploy Acrobat workflow solutions. Provide you with references to other resources where you can learn more about Acrobat JavaScript and related technologies. After reading this guide and co 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: Be sure that you have Acrobat Prof essional installed on your Windows or Macintosh workstation. The exercises are designed to work on Windows and Macintosh versions of Acrobat, unless otherwise noted. 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. Preface Font Conventions Used in This Book Acrobat JavaScript Scripting Guide The Acrobat documentation uses text styles according to the following conventions. Font Used for monospaced Paths and filenames C:\templates\mytmpl.fm Code examples set off from plain text These are variable declarations: AVMenu commandMenu,helpMenu; monospaced bold Code items within plain text The method ... The enumeration terminates if returns Pseudocode ACCB1 void ACCB2 ExeProc(void) Placeholders in code AFSimple_Calculate( cFunction cFields blue Live links to Web pages http://partners.adobe.com/asn/ Live links to sections within this document Using the SDK Live links to code items within this document exists. PostScript language and PDF operators, keywords, dictionary The setpagedevice operator User interface names The File menu Document titles that are not live links Acrobat Core API Overview New terms User space specifies coordinates for... PostScript variables filename Acrobat JavaScript Scripting Guide Preface Related Documents This guide refers to the following source s 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. 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 Acrobat JavaScript Scripting Guide Acrobat JavaScript Scripting Guide Acrobat JavaScript Overview This chapter introduces the Acrobat JavaScript objects and containment hierarchies, as well as the primary Acrobat and PD F 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 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 enviro nment 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 ac tions. This type of PDF document can replace existing paper forms, allowing employees with in 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 ) 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 do cument, implement security policies, interact with databases and web services, and dynamica lly 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 an d 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 Ja vaScript to perform a ta sk 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 pr ocessing of multiple documents, processing within a single document, processing for a gi ven 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 Acrobat JavaScript Overview Acrobat JavaScript Object Summary 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 co ntrol the application and document, the development environment itself, and gene ral-purpose JavaScript functionality. The most significant objects available contro l Acrobat, the Acrobat JavaScript debugger, the Acrobat JavaScript console, the PDF document, the Adobe Dialog Manager , Web services, databases, security, searches, and JavaScript events. ABLE Primary Acrobat JavaScript Objects Object Purpose app Acrobat PDF document dbg JavaScript debugger console JavaScript console global Persistent and cross-document information dialog Adobe Dialog Manager (ADM) security Encryption and digital signatures SOAP Web Services search Searching and indexing Database connections and queries event JavaScript events Acrobat JavaScript Overview Acrobat JavaScript Object Summary Acrobat JavaScript Scripting Guide app The object is a static object that represents the Acrobat application itself. It offers a number of Acrobat-specific functions in addi object, you can open or create PDF and The object is the primary interface to the PDF document, and it can be used to access and manipulate its content. The IGURE Doc Object Containment Hierarchy Figure represents the containment hierarchy of objects related to the object. Accessing the object, which is normally equivalent to the object of the current underlying document. fieldsound bookmark template data Acrobat JavaScript Scripting Guide Acrobat JavaScript Overview Acrobat JavaScript Object Summary You can use the object, 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 object methods offer the same functionality as the buttons in the JavaScript debugger dialog toolbar, which permit stepwise execution, console The object 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. The 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, 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 . If information about the documents needs to be stored in a object, it is assigned to a so it is accessible to the object. The 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 The object is an object literal used by the objects method to present a modal dialog box identical in appe arance and behavior to those used across all Adobe applications. The object literal consists of a set of event handlers and Acrobat JavaScript Overview Acrobat JavaScript Object Summary Acrobat JavaScript Scripting Guide The object is a static JavaScript object, available without restriction across all Acrobat applications includin g 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 object can be used to add passwords and set security options, add usage rights to a document, encryp t PDF files for a list of recipients, apply and assign security policies, create custom se curity 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 object can be used to make remote pr ocedure calls to a server and invoke Web Services described by the Web Services Description Language (WSDL), and supports both object makes it possible to share comments remotely and to invoke Web Services in form field events. It provides support for rich text responses and queries, HTTP authentication and WS-Security, SOAP headers, error handling, sending or converting file attachments, exchanging compressed binary data, document literal encoding, object serialization, XML streams, and applying DN S service discovery to find collaborative object can be used to evaluate XPath expressions and perform XSLT conversions on XML documents. search The object is a static object that can be used to perform simple and advanced searches for text in one or more PDF documents or index files, create, update, rebuild, or purge indexes for one or more PDF document s, and search through document-level and object has properties that may be used to fine-tune the query, such as a thesaurus, words with simi lar sounds, case-sensiti The object is used in conjunction with the , and objects to interface to a database. These Acrobat JavaScript objects constitute Acrobat Database Connectivity (ADBC), and provide a simplified me ans of utilizing ODBC calls to connect to a database and access its data. SQL statements are passed to the objects Acrobat JavaScript Scripting Guide Acrobat JavaScript Overview Acrobat JavaScript Object Summary event All JavaScript actions are executed when a particular event occurs. For each event, Acrobat JavaScript creates an object. When an event occurs, the object can be used to obtain and manage any information associated with the state of that particular event. An 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 validati on events, and menu item selection events. Acrobat JavaScript Overview What Can You Do with Acrobat JavaScript? Acrobat JavaScript Scripting Guide What Can You Do with Acrobat JavaScript? Acrobat JavaScript enables you to do a wide 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 Make forms accessible to visually impaired users Make forms Web-ready Migrate legacy forms to dynamic XFA Secure forms Facilitating review, markup, and approval Creating and managing comments Approving documents using stamps Integrating digital me dia into documents Controlling and managing media players and monitors Adding movie and sound clips Adding and managing renditions 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 Acrobat JavaScript Overview What Can You Do with Acrobat JavaScript? 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 HTTP authentication and WS-Security SOAP header support Error handling Handling file attachments Exchanging compressed binary data Document literal encoding Serializing objects XML streams XML Performing XSLT conversions on XML documents Evaluating XPath expressions Acrobat JavaScript Overview What Can You Do with Acrobat JavaScript? Acrobat JavaScript Scripting Guide Acrobat JavaScript Scripting Guide Acrobat JavaScript Tools 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, Ac robat supports the use of third-party editors for code development. In this chapter, you will have the opportunit y 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 fo llowing debugger controls and features: Start the debugger at any point within a script. Interactively execute code and display output to the console window. Start a new debugging session without exiting the debugger. Acrobat JavaScript Tools 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 Acrobat JavaScript Tools 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 Ja vaScript Console: either through an Acrobat menu command or through the use of the static object within Acrobat JavaScript code. In either case, it appear s as a component of the Acrobat JavaScript Debugger, and the primary means of displa ying values and results is through the method. Opening the JavaScript Console To open the Acrobat JavaScript console from within Acrobat: Open the debugger window using one of these methods: Select Advanced JavaSc ript Debugger , or Type Ctrl-j (Windows) or Command-j (Macintosh) Select either Console or Script and Console from the debuggers View To open and close the console fr om Acrobat JavaScript code, use and 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, hi ghlight those lines and press either the Enter on the numeric keypad or type Ctrl+Enter on the regular keyboard. In all cases, the result of the most recent si ngle JavaScript statement executed is displayed in the console. Acrobat JavaScript Tools Exercise: Working with the JavaScript Console 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 th e 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 OTE 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 Acrobat JavaScript Tools Exercise: Working with the JavaScript Console 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 Cons ole by performing the following steps (see Figure below): Launch Acrobat. Select Ed it Preferences to open the Preferences dialog box. Select JavaScript from the list of options on the left side of the dialog box. Select Enable Acrobat JavaScript if it is not already selected. In the Preferences dialog box, select Enable JavaScript Debugger after Acrobat is restarted from the JavaScript Debugger options. Select Enable interactive console . This option enables you to evaluate code that you write in the console window. Select Show console on errors and messages . This ensures that whenever you make mistakes, the console displays helpful information. to close the Preferences dialog box. Close and restart Acrobat. Acrobat JavaScript Tools Exercise: Working with the JavaScript Console Acrobat JavaScript Scripting Guide IGURE Enabling JavaScript, Console, and Debugger Acrobat JavaScript Scripting Guide Acrobat JavaScript Tools Exercise: Working with the JavaScript Console Trying out the JavaScript Console Select Advanced JavaSc ript Debugger ) to open the JavaScript debugger. In the debugger, select Console from the View window. The console window should appear, as shown in Figure IGURE Console window in the JavaScript Debugger Type the following code into the console: var jsNum = 10; 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 below Acrobat JavaScript Tools Exercise: Working with the JavaScript Console Acrobat JavaScript Scripting Guide IGURE Evaluating the variable declaration After each Acrobat JavaScript statement executes, the console window prints out , which is the return value of the st atement. 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 does not mean that the value of undefined; it just means that the entire JavaScript statements value is A more convenient way to evaluate the variable is to highlight the variable name and execute it as a JavaScript expression, as shown below in Figure IGURE Evaluating jsNum Acrobat JavaScript Scripting Guide Acrobat JavaScript Tools Exercise: Working with the JavaScript Console button to exit the console and debugger, as shown in Figure below: IGURE Console and Debugger Close Button Acrobat JavaScript Tools Using a JavaScript Editor Acrobat JavaScript Scripting Guide Using a JavaScript Editor There are several ways to invoke the Arobat JavaSc ript 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 an d edit its particular JavaScript. For example, the following are the steps to write a JavaScript for a bookmark: Right-click a bookmark. This triggers a context menu. Select Properties and choose the Actions tab, as shown below in Figure Acrobat JavaScript Scripting Guide Acrobat JavaScript Tools Using a JavaScript Editor IGURE Bookmark Properties The Select Action drop-down list contains all th e possible actions that can be associated with the object, such as Run a JavaScript Go to view Execute a menu item Select Run a JavaScript from the Select Action drop-down list. Add to open the JavaScript editor. In the editor window, write the JavaScript co de to be run when the user opens the page. Acrobat JavaScript Tools Using a JavaScript Editor Acrobat JavaScript Scripting Guide When the code is complete, click 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 IGURE Figure , the quotation mark to the right of the string is missing. OTE 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 fr om all other scriptab the document. Acrobat JavaScript Scripting Guide Acrobat JavaScript Tools Specifying the Default JavaScript Editor Specifying the Default JavaScript Editor Figure above and in Figure below: Choose Ed it Preferences to open the Preferences dialog box. Select JavaScript from the list of options on the left side of the dialog box. This brings up the Preferences dialog box. In the JavaScript Editor section, select the editor you would like to use. IGURE Selecting the Editor in Preferences The Acrobat JavaScript Editor 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. OTE For some external editors, Acrobat provides extra command line options for Additional Editor Capabilities Acrobat JavaScript Tools Using the Built-in Acrobat JavaScript Editor 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 ex pressions 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 Formatting Code If an external editor program has been spec ified as the default application for editing JavaScripts in Acrobat, Acrobat generates a te mporary file and opens it in the external editor program. When editing a file in an ex ternal editor, note the following restrictions: Acrobat is inaccessible while th e external editor is in use. Acrobat JavaScript code cannot be ev aluated within the external editor. Additional Editor Capabilities Acrobat supports some additional command li ne editor capabilities for Windows-based the ). 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 i nto 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 editin g 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 (t his is the best course of action, if available). 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 Acrobat JavaScript Scripting Guide Acrobat JavaScript Tools Using an External Editor For your convenience, Acrobat provides predefined, command line templates for many current external editors. The extern 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 below). If your editor is not one that Acrobat curren tly 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 edit followed by the file name ( ). 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 , each followed by the line number ( ). For most editors, the line number switch and should be enclosed in 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 comm and line template: "C:\Program Files\vslick\win\vs.exe" "%f" +new [-#%n] When Acrobat opens the default JavaScript edit or, it makes the appropriate substitutions in the command line and executes it with the oper ating sytem shell. In the above case, if the syntax error were on line 43, the comman d line generated would appear as follows: "C:\Program Files\vslick\win\vs.exe" "C:\Temp\jsedit.js" +new -#43 OTE To insert as characters in the command line, precede each of them with the escape character, thus using respectively. Acrobat JavaScript Tools Using an External Editor Acrobat JavaScript Scripting Guide Open a script in your editor. Add a syntax error. Move the cursor to a line other than the one containing the syntax error. Close and save the file. 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 woul d 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? OTE If you click , Acrobat discards your file. Always click Yes . Acrobat expands the path to the editor to include the line number in the specified syntax. The edit or opens and the cursor is placed on line 123. ABLE 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] http://www.gnusoftware.com/Emacs [+%n] "%f" Epsilon http://www.lugaru.com [+%n] "%f" 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] http://www.vedit.com -s2 "%f" [-l %n] Visual SlickEdit http://www.slickedit.com +new "%f" [-#%n] Acrobat JavaScript Scripting Guide Acrobat JavaScript Tools Using the Acrobat JavaScript Debugger The Acrobat JavaScript Debugger is a fully capa ble JavaScript debugger that allows you to Though fully supported Acrobat JavaScript debugging is only available in Acrobat The file debugger.js , available at http://partners.adobe.com/asn/acrobat/docs.jsp or in Acrobat 7.0 SDK/JavaScriptSupport/Debugger/debugger.js must be copied to the Acrobat 7.0/Reader/JavaScripts folder. Create key/value pairs in the registry Table , or in the property list file useuse-;.6r;r: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 Type : Array in each case: Console Open Console Input Exceptions . Under each of these ch ildren, add the following children: 0 (number) 1 (boolean) Close and restart Adobe Reader. At this point the debugger will be available. OTE Since Adobe Reader does not provide access to the debugger through its menu items or the key sequence, the only ways to access the debugger are to execute a JavaScript, cause an error, or cu stomize the user interface (for example, you could add a button that runs a JavaSc ript causing the debugger to appear). ABLE Registry Key/Value Pairs for Windows (this will break into the debugger when exceptions occur) Acrobat JavaScript Tools Using the Acrobat JavaScript Debugger Acrobat JavaScript Scripting Guide As you learned earlier when opening the Acroba t 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 exceptio OTE The Acrobat JavaScript Debugger cannot be used to analyze JavaScript stored in HTML pages viewed by Web browsers such as In order to make the debugger available for us e, you will need to enable both JavaScript and the debugger. As you did earlier, use the Ed it Preferences dialog to control the behavior of the Acrobat JavaSc ript 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 , and are explained below in Table Acrobat JavaScript Scripting Guide Acrobat JavaScript Tools Using the Acrobat JavaScript Debugger ABLE JavaScript debugger options Option 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 JavaSc ript Document JavaScripts 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. : stops execution and displa ys 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 ente r 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? Yes to enable this option fr om within the debugger. In Preferences you will now see this option checked. Show console on errors and messages This option opens the console wi ndow in the debugger dialog Acrobat JavaScript Tools Acrobat JavaScript Debugger 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 be fore 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. IMPORTANT: 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 , 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 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 , 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 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 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 the Acrobat JavaScript Console Script and Console : view both the console and script windows at the same time. The script window displays above th e console window, as shown in Figure Acrobat JavaScript Scripting Guide Acrobat JavaScript Tools Acrobat JavaScript Debugger IGURE Debugger Dialog Box Acrobat JavaScript Tools Debugger Buttons Acrobat JavaScript Scripting Guide Debugger Buttons Figure shows the debugger buttons on the toolbar, and Table summarizes the Exercise: Calculator IGURE 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 ABLE 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. InterruptQuit Step Over Step IntoStep Out Acrobat JavaScript Scripting Guide Acrobat JavaScript Tools Debugger Buttons 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 debuggin g session and closes the debugger. Step Over 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 IGURE Position Indicator at a Function Call Excecution is currently ha lted before the call to . Assuming that there are no errors or breakpoints in , clicking Step Over executes the entire 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 . Clicking Step Into at this point advances the position indicator to the first statement within the function. OTE 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 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 ex ecution 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. All scripts associated with a PDF file are available in the debugger dialog. The debugger displays these in the Scripts window (see Figure below for an example). IGURE Scripts window Accessing Scripts in the Scripts Window To display the content a script, clic k 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 Figure , a function has been defined for a mouse-up action on a button named . Click on the script icon to display its code. Acrobat JavaScripts can be stored in several pl aces, which may be either inside or outside PDF files. The following sections describe their possible locations. Acrobat JavaScript Scripting Guide Acrobat JavaScript Tools Debugger Scripts Window Scripts Inside PDF Files Table below lists the types of scripts contained in PDF files. These can be accessed from the Scripts window within the debugger di alog. You can edit them from inside the Breakpoints on OTE 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 T ools Advanced Editing Show Advanced Editing Toolbar . You may want to dock this toolbar, as you will use it frequently. ABLE Scripts inside PDF files Location Access Document level Advanced JavaScri pt Document JavaScripts Document actions Advanced JavaScri pt Set Document Actions Page actions Pages tab; select Op tions Page Properties Forms Double-click the form object in form editing mode (see below) to bring up the Form Properties 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 Acrobat JavaScript Tools Debugger Scripts Window 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 keyword. See Starting the Debugger for details. ABLE Scripts outside PDF files Location Access Folder level Stored as JavaScript ( .js ) files in the App User folder areas Console Typed and evaluated in the console window Batch Choose Advanc ed Batch Processing Acrobat JavaScript Scripting Guide Acrobat JavaScript Tools 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 it Figure . When the debugger has been used to suspend execution at a given statement, th e 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 fr ame in the stack, click on that entry. They appear in the Inspect Figure IGURE 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 Acrobat JavaScript Tools Inspect Details Window Acrobat JavaScript Scripting Guide The Inspect The three buttons at the bottom right of the Inspect details window, shown in Figure 2.14 IGURE Edit Acrobat JavaScript Scripting Guide Acrobat JavaScript Tools Inspect Details Window 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 Figure 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. IGURE Watches The Watches list enables you to customize how variables are inspected. Watches are JavaScript expressions evaluated when the debu gger 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 To set a watch, select Watches from the Inspect drop-down list. Click the New button, and a dialog prompts you for the JavaScript va riable or expression to be evaluated. To change the value of a watch, select the watch from the list. Click the button, which displays a dialog prompting you to specify a Acrobat JavaScript Tools Inspect Details Window 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 ex ecution 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 sa me line as the function name, for example, function callMe() { // curly brace on same line as function name var a = 0; Style 2: Place the left curly brace on a separate line, for example function callMe() { // curly brace is on a separate line var a = 0; Figure . It is possible to set the breakpoint on the line below the function heading for , and on the line containing the function heading for . Setting a breakpoint at a function heading causes execution to stop at the first statement within the function. IGURE Setting a Breakpoint at a Function Heading Acrobat JavaScript Scripting Guide Acrobat JavaScript Tools Starting the Debugger Listing Breakpoints To view the list of all breakpoints set for the debugging session, select the Breakpoints option from the Inspect Figure Using Conditional Breakpoints A conditional breakpoint causes the interpre ter 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 execut ion. For example, if you are only interested in debugging after 100 iterations in a loop, The condition is a JavaScript expression. If the expression evaluates to , 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 To change a breakpoint condition, select Breakpoint from the Inspect drop-down list and . 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 exec ution, 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 th e 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 From Start This option causes the debugging session to begin at the start of execution of any new script. OTE Debug From Start does not turn off automatically. Be sure to turn off this option when you have finished debugging, otherw ise it continues to stop on every new script you execute in Acrobat. Acrobat JavaScript Tools Exercise: Calculator 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. Debug From Start 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 sp Breakpoints Using the debugger keyword You can also insert the keyword in any line of your code to stop execution and enter the debugger when that particular line is reached. OTE Breakpoints created using the keyword are not listed in the Inspect Inspect drop-down list. OTE TestDebugger.zip and open Calc.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 Create, edit, and delete watches. Use the debugger buttons to control how the in terpreter executes the code in the script. Calculator Calc.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 ( equals sign ( ), and Cancel ( ) and Cancel Entry ( ) keys. Acrobat JavaScript Scripting Guide Acrobat JavaScript Tools Exercise: Calculator How the Calculator Displays Output Calc.pdf uses the Acrobat s method to place values in the calculator display window, which is the text field . In this statement, the variable to this field: Every time a numeric key is clicked, its value should be shown in the calculator display window. To do this, we define a action 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 button, the action associated with the button could assign the value returned by to the calculator window as shown below: display.value = digit_button(7); Calc.pdf uses a similar mechanism to display text field, which is used to display the operation (PLUS, MINUS, MULT, DIV). In this statement, binds the variable to this field: The code below is contained in the action for the division ( ) key, and represents a call to the func_button("DIV"); The action passes the string "DIV" to the , which is thus bound to that value. Later in the function, this statement is encountered: func.value = req_func Because has bound the variable to the field, this statement displays the string "DIV" 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 button, the new current valu e is 23 (10 times 2 plus 3). For decimal values, a action is associated with the button. In this action, the calculator multiplies the divisor by 10. Su bsequently, when other numeric keys are selected, the calculator divides the selected va lue by the divisor, and adds that amount to the current value. For example, if the current divisor is 1 and the user presses the 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 ad ded 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 ba sic calculator operations, open Calc.pdf in Acrobat and try entering expressions and evaluating their results. When you are familiar with the calcul ators operation, close this file. Acrobat JavaScript Tools Summary Acrobat JavaScript Scripting Guide There are limitations to debugging scripts in Ac robat from inside a browser, because not all scripts contained in a PDF file may be availa 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 ev ent initiated by either the The Acrobat JavaScript Debugger is a fully ca pable 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, whic Acrobat JavaScript Scripting Guide Acrobat JavaScript Contexts Acrobat JavaScript can be used to create scri pts that are used for batch sequences and at Chapter Goals At the end of this chapter, you will be able to: List the Acrobat JavaScript contex ts 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 Acrobat JavaScript Scripting Guide level 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 OTE 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: . For example, if you would like to add specialized menus and menu items to be available to all documents opened in Acroba t, you may create and store the scripts for these in folder level JavaScripts. Folder level JavaScripts are placed in separate files that have the " " extension. App folder level scripts are stored in the Acrobat applications JavaScripts folder, and User folder level scripts are stored in the users JavaScripts folder. These scripts are loaded when Acrobat starts execution, and are associated with the objects Application Initialization event. When Acrobat is installed on your machine, it provides you with several standard folder level JavaScript files, including Aform.js Annots.js , and ADBC.js . In addition, your User folder may also contain glob.js , which is programmatically generated and contains objects method, and Config.js , which is used to customize the look of the viewer by adjusting its toolbar buttons and menu items. For example, calls would be Config.js 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 Acrobat JavaScript Contexts Document Level JavaScripts Document level JavaScripts are function and va riable 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 Advanc ed JavaSc ript Document JavaScripts You can associate a JavaScript with any comp onent 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 event 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, fi eld level scripts are st ored within the PDF 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 . Additionally, you may select Advanced JavaScripts Edit all JavaScripts ... A batch level JavaScript is a script that ca n 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 Advanc ed Batch Processing... Acrobat JavaScript Contexts Summary Acrobat JavaScript Scripting Guide 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 availabl e 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 le vel 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 Acrobat JavaScript Scripting Guide Creating and Modifying PDF 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 Acrobat JavaScript Scripting Guide Acrobat JavaScript provides support for dynamic PDF file creation and content generation. This means that it is possible to dynamically create a ne w 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 objects var myDoc = app.newDoc(); object, as indicated below in Table 4.1 ABLE Acrobat JavaScript Usage for Crea ting Content in a PDF Document Content Object field icon document-level JavaScript thumbnails bookmark web link template Acrobat JavaScript Scripting Guide Creating and Modifying PDF Documents Creating and Modifying PDF Files 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 objects // Create a new PDF document: var newDoc = app.newDoc(); // Insert doc1.pdf: newDoc.insertPages({ nPage : -1, cPath : "/c/doc1.pdf", }); // Insert doc2.pdf: newDoc.insertPages({ nPage : newDoc.numPages, cPath : "/c/doc2.pdf", }); // Save the new document: newDoc.saveAs({ "/c/myNewDoc.pdf"); }); // Close the new document without notifying the user: newDoc.closeDoc(true); 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 Mu type definitions. One simple approach would be to invoke the objects 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 objects this.importDataObject("myFile", "/c/myFile.xml"); var myData = this.getDataObject("myFile"); for (var i in myData) console.println(myData[i]); Creating and Modifying PDF Documents Creating and Modifying PDF Files Acrobat JavaScript Scripting Guide If you would like to automate the insertio n of multiple PDF files into a single PDF document, you may do so through a series of calls to the objects and this.insertPages({ nPage : -1, cPath : "/c/myCoverPage.pdf", nStart: 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 objects method. For example, suppose the document consists of a se quence of invoices, each of which occupies one page. The following code creates separate PDF files, one for each invoice: var filename = "invoice"; for (var i = 0; i this.numPages; i++) this.extractPages({ nStart: i, cPath : filename + i + ".pdf" }); Cropping and Rotating Pages Cropping Pages The Acrobat JavaScript Art Crop Media Trim The : the type of box : the zero-based index of the beginning page : the zero-based index of the last page : the rectangle in rotated user space Acrobat JavaScript Scripting Guide Creating and Modifying PDF Documents Creating and Modifying PDF Files For example, the following code crops pages 2-5 of the document to a 400 by 500 pixel area: this.setPageBoxes({ cBox: "Crop", nStart: 2, nEnd: 5, rBox: [100,100,500,600] }); The : the type of box : the zero-based index of the page For example, the following code retrieves the crop box for page 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 orientatio n is, the upper portion of the page is placed on the right side of your screen. The objects The : the zero-based index of the beginning page : the zero-based index of the last page : 0, 90, 180, or 270 are the possible values for the clockwise rotation In the following example, pages 2 and 5 are rotated 90 degrees in the clockwise direction: this.setPageRotations(2,5,90); To retrieve the rotation for a given page, invoke the objects method, which requires only the page number as a parameter. The following code retrieves and displays the rotation in degrees for page 3 of the document: var rotation = this.getPageRotation(3); console.println("Page 3 is rotated " + rotation + " degrees."); Creating and Modifying PDF Documents Creating and Modifying PDF Files Acrobat JavaScript Scripting Guide The Acrobat JavaScript object, in combination with the object, can be used to extract pages from one document and place them in another, and moving or copying The object an be used to create or open any document. To create a new document, invoke its method. The : inserts pages from the source document into the current document : replaces pages in the current docu ment with pages from the source Suppose you would like to remove pa ges within a document. Invoke the objects : the zero-based index of the beginning page : the zero-based index of the last page this.deletePages({nStart: 2, nEnd: 5}); Suppose you would like to copy pages from one document to another. Invoke the objects : the zero-based index of the page after which to insert the new pages : the device-independent pathname of the source file : the zero-based index of the beginning page : the zero-based index of the last page For example, the following code inserts pages 2 through 5 from mySource.pdf beginning of the current document: this.insertPages({ nPage: -1, cPath: "/C/mySource.pdf", nStart: 2, nEnd: 5 }); Acrobat JavaScript Scripting Guide Creating and Modifying PDF Documents Creating and Modifying PDF Files You can combine these operations to extract pages from one document and move them to mySource.pdf and move them into this.insertPages({ nPage: -1, cPath: "/C/mySource.pdf", nStart: 2, nEnd: 5 }); var source = app.openDoc("/C/mySource.pdf"); To replace pages in one docume : the zero-based index of the page at which to start replacing pages : the device-independent pathname of the source file : the zero-based index of the beginning page : the zero-based index of the last page In the following example, pages 2 through 5 from mySource.pdf replace pages 30 through this.replacePages({ nPage: 30, cPath: "/C/mySource.pdf", nStart: 2, nEnd: 5 }); To safely move pages within the same document, it is advisable to perform the following Copy the source pages to a temporary file. Insert the pages in the temporary file at the new desired location in the original Creating and Modifying PDF Documents Creating and Modifying PDF Files Acrobat JavaScript Scripting Guide The following example moves pages 2-5 after page 30 in the document: // First create the temporary document: var tempDoc = app.newDoc("/C/temp.pdf"); // Copy pages 2-5 into the temporary file tempDoc.insertPages({ cPath: "/C/mySource.pdf", nStart: 2, nEnd: 5 }); // Copy all of the temporary file pages back into the original: this.insertPages({ nPage: 30, cPath: "/C/temp.pdf" }); this.deletePages({nStart: 2, nEnd: 5}); Adding Watermarks and Backgrounds The objects methods create watermarks within a document, and place them in optional content groups (OCGs). The watermark.pdf as a watermark to the center of all pages within the current document: this.addWatermarkFromFile("/C/watermark.pdf"); In the next example, the watermark.pdf as a watermark to the first 10 pages of the current document. It is rotated counterclockwise by 45 degrees, and positioned one inch down and two inches over from the top left corner of each page: this.addWatermarkFromFile({ cDIPath: "/C/watermark.pdf", nSourcePage: 1, nEnd: 9, nHorizAlign: 0, nVertAlign: 0, nHorizValue: 144, nVertValue: -72, nRotation: 45 }); Acrobat JavaScript Scripting Guide Creating and Modifying PDF Documents Converting PDF Documents to XML Format It is also possible to use the method to create watermarks. In this next example, the word Confidential is placed in the center of all the pages of the document, and its font helps it stand out: this.addWatermarkFromText( "Confidential", 0, font.Helv, 24, color.red 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 objects this.addWatermarkFromText({ cText: "Confidential Document", nTextAlign: 2, nHorizAlign: 2, nVertAlign: 0, nHorizValue: -72, nVertValue: -72 }); Converting PDF Documents to XML Format Since XML is often the basis for information ex change 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 objects 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.acrobat.xml-1-00". The following code converts the current PDF file to C:\test.xml this.saveAs("/c/test.xml", "com.adobe.acrobat.xml-1-00"); Creating and Modifying PDF Documents Converting PDF Documents to XML Format Acrobat JavaScript Scripting Guide Acrobat JavaScript Scripting Guide Print Production This chapter will provide you with an in-depth understanding of the ways in which you may manage print production wo rkflows 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. Control how PDF layers are printed. Contents Topics Printing PDF Documents Printing Documents with Layers Setting Advanced Print Options Print Production Print Production Acrobat JavaScript Scripting Guide 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 Table ABLE PrintParams Properties Property Description Binary printer channel is supported DPI used for bitmaps or rasterizing transparency Color profile based on available color spaces Wrapper object for constants Sends Far East fonts to the printer Filename is used when printi ng to a file instead of a printer The first zero-based page to be printed A bit field of flags to control printing options The DPI used for rasterizing gradients Sets the level of interaction for the user The last zero-based page to be printed How pages will be handled (fit, shrink, or tiled) Even, odd, or all pages are printed Sends pages as large bitmaps The name of the destination printer The level of PostScript emitted to the printer A bit field of flags for outlines, clips, and overprint Acrobat JavaScript Scripting Guide Print Production Print Production In addition to the objects properties, the objects and properties provide a list of available color spaces and printer names, respectively. Also, the objects Printing PDF Documents objects Table 5.2 Prints pages in reverse order Labels each page of tiled output Output marks to cut the page and where overlap occurs The number of points that tiled pages have in common The amount that tiled pages are scaled The degree to which high level drawing operators are preserved ABLE Parameter Description The zero-based index of the beginning page The zero-based index of the last page Suppresses the Cancel dialog box while the document ABLE 5.1PrintParams Properties PropertyDescription Print Production Print Production 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 sh runk to fit the imageable area of the pages: this.print({ bUI: false, bSilent: true, bShrinkToFit: true, nStart: 1, nEnd: 10 }); To print the document to a PostScript file, obtain the object by invoking the objects method. Set its property to the property to a string containing the device- independent path of the PostScript file to whic h it will be printed, as shown in the following example: pp.printerName = ""; pp.fileName = "/C/myPSDoc.ps"; this.print(pp); If you would like send the file to a particular property of the object, as shown in the following example: pp.interactive = pp.constants.interactionLevel.automatic; this.print(pp); The object containing the printing ABLE 5.2Print Method Parameters Acrobat JavaScript Scripting Guide Print Production Print Production Silent Printing There are various ways to print a document with out requiring user interaction. One way is to use the objects attribute to , as shown Printing PDF Documents on page and in the following example: this.print({bUI: false, bSilent: true, bShrinkToFit: true}); If you would like to print without requiring us er 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: pp.interactive = pp.constants.interactionLevel.automatic; There are many options you may choose withou t requiring user interaction. For example, you can select the paper tray: var fv = pp.constants.flagValues; pp.flags |= fv.setPageSize; These coding approaches may be used in menu s 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 Printing Documents with Layers The objects pp.interactive = pp.constants.interactionLevel.silent; pp.printContent = pp.constants.printContent.formFieldsOnly; this.print(pp); Print Production Print Production Acrobat JavaScript Scripting Guide Setting Advanced Print Options objects properties to specify advanced options including output, marks and bleeds, transparency flatte ning, PostScript options, and font options. Specifying Output Settings You may obtain a listing of printer co lor spaces available by invoking the objects method. You may then assign one of these values to the objects property. objects property to specify advanced var fv = pp.constants.flagValues; this.print(pp); Specifying Marks and Bleeds You can specify the types of tile marks and where overlap occurs by setting the objects property. For example, in the following code, Western style tile marks are printed: pp.tileMark = pp.constants.tileMarks.west; this.print(pp); objects property to specify advanced PostScript var fv = pp.constants.flagValues; pp.flags &= ~(fv.suppressBG | fv.suppressUCR); this.print(pp); objects property to specify the level of PostScript emitted to PostScript printers. In addition, if the printer only supports objects property to Acrobat JavaScript Scripting Guide Print Production Print Production You can control the font policy by setting the objects property. There are three values that may be used: : emit needed fonts for every page, freeing fonts from the previous page. This is useful for printers ha ving a small amount of memory. : emit all fonts at the beginning of the print job, free them at the end of the print job. This is useful for printe rs having a large amount of memory. : emit the fonts needed for a given range of pages, free them once those pages are printed. This may be used to In the following example, all the fonts are em itted at the beginning of the print job, and freed once the job is finished: pp.fontPolicy = pp.constants.fontPolicy.jobStart; this.print(pp); objects property. There are three values that may be used: : allow conversion of Type 1 fonts. : do not allow conversion of Type 1 fonts. In the following example, conversion of Type 1 fonts is set to automatic: this.print(pp); Finally, it is possible to send Far Ea objects property to Print Production Print Production Acrobat JavaScript Scripting Guide Acrobat JavaScript Scripting Guide Using Acrobat JavaScript in Forms 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 cont ain, and ensure the proper collection and export of information in various formats rele vant to your workflow needs. In addition, you will understand how to leverage the XM L 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 Se rvices 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 Acrobat JavaScript Scripting Guide 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. Fina lly, 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 Using Acrobat JavaScript in Forms Forms Essentials 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 fi elds. 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 in teractions and compatibility with document processing needs within ente rprise-wide infrastructures. The new Adobe XML forms model uses a Docu ment 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 fi elds. In addition, all calculations, validations, and formatting are specified and managed within the DOM and XML processes. were supported in Acrobat 6.0, and are now supported in Acrobat 7.0. Both types are created using Adobe LiveCycle Designer. A static XML form Elements of Acrobat Forms The form fields used in Acrobat forms are th e 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 enha nce the appearance and value of your forms through the use of tables, templates, watermar ks, 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 Using Acrobat JavaScript in Forms Forms Essentials 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, Usability is a major factor in the design of forms since they are essential graphical user interfaces, so layout and clarity will be a majo r 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 th e 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 th rough 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 coll How size, alignment, and distribution of form fields within the document will be When to create multiple form fields for array-based access and algorithms. The tab order of form fields. Acrobat JavaScript Scripting Guide Using Acrobat JavaScript in Forms Forms Essentials Creating Acrobat Form Fields There are seven types of Acrobat form fields, each associated with a field type value as shown below in Table You can use Acrobat JavaScript to create a form field by invoking the objects method, which returns a The field name. This may include hierarchical syntax in order to facilitate logical groupings. For example, the name implies that the form field belongs to a group of fields called . The advantage of creating logical hierarchies is that yo u can enforce consistency among the properties of related One of the seven field type values li sted above, surrounded by quotes. The page number where the form field is placed, which corresponds to a zero-based indexing scheme. Thus, the first page is considered to be page 0. The location, specified in rotated user space (the origin is located at the bottom left corner of the page), on the page where the form field is placed. The location is specified through the use of an array of 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-left x, upper-left y, lower-right x, lower-right y ABLE Acrobat Form Field Types Form Field Field Type Value Button Check Box Combo Box List Box Radio Button Text Field Digital Signature Using Acrobat JavaScript in Forms Forms Essentials Acrobat JavaScript Scripting Guide For example, suppose you would like to place a Button named on the first page of the document. Assume that the button is one inch wide, one inch tall, and located 100 points in from the left side of the page an d 400 points up from th e bottom of the page (there are 72 points in 1 inch). The code for creating this button would appear as follows: var name = "myButton"; var type = "button"; var page = 0; var location = [100, 472, 172, 400]; var myField = this.addField(name, type, page, location); This approach to creating form fields is applic able to all fields, but it should be noted that 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 . We will place them on page 5 of the document, and their export values will be . They can be created as shown in the code given below: var name = "myRadio"; var type = "radiobutton"; var page = 5; this.addField(name, type, page, [400, 442, 412, 430]); this.addField(name, type, page, [400, 427, 412, 415]); var rb = this.addField(name, type, page, [400, 412, 412, 400]); This code actually creates an array of 3 radio buttons, named Acrobat JavaScript Scripting Guide Using Acrobat JavaScript in Forms Forms Essentials Acrobat Javascript provides a large number of properties and methods for determining the appearance and associated acti ons of form fields. In this section you will learn what 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 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 class contains many , 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. There are also specific settings you can apply to text characteristics, button and icon size and position relationships, button appearan ce when pushed, check box and radio button glyph appearance, and the numb er and selection options for combo box and list box items. All formatting options are listed and described below in Table ABLE Format Options Format Description Field Properties display rectangle position and size of field on border style rectangle border appearance stroke color applied to edge of surrounding rectangle border thickness width of the edge of the surrounding rectangle orientation rotation of field in 90-degree increments background color background color of field (gray, transparent, RGB, or CMYK) tooltip short description of field that appears on mouse-over read only scrolling display visible or hidden on screen or in print Acrobat JavaScript Scripting Guide Using Acrobat JavaScript in Forms Forms Essentials text font, color, size, rich text, comb format, multiline, limit to number of characters, file selection format, or password format richValue, comb, text alignment controls text layout in text fields button alignment controls alignment of icon on button face button icon relative scaling of an icon to fit inside a button face buttonScaleHow, indicates how a button will appear when pushed glyph style for checkbox and radio buttons number of number of items in a combo box or list box multiple selection ABLE 6.2Format Options FormatDescriptionField Properties Using Acrobat JavaScript in Forms Forms Essentials Acrobat JavaScript Scripting Guide Button Properties We will begin by creating a button named var f = this.addField("myButton", "button", 0, [200, 250, 250, 400]); To create a blue border along the edges of property: f.strokeColor = color.blue; In addition, you may select from one of the following choices to specify its border style: beveled , , ( . In this case we will make the bo property: f.borderStyle = border.b; To set the line thickness (in points) of the border, set its property: f.lineWidth = 1; To set its background color to yellow, we will set its property: f.fillColor = color.yellow; To specify the text that appears on the button, invoke its method: f.textSize = 16; f.textColor = color.red; f.textFont = font.Times; property: f.userName = "This is a button tooltip for myButton."; In addition to the text, it is also possible to specify the relative positioning of the icon and text on the buttons face. In this case, we will f.buttonPosition = position.iconTextH; property: f.display = display.visible; property to one of the following values: invert In this example , we will specify that the button appears to be pushed: f.highlight = highlight.p; Acrobat JavaScript Scripting Guide Using Acrobat JavaScript in Forms Forms Essentials It is possible to specify the scaling characteri stics of the icon within the button face. You property to one of the following values: always never ), if the icon is too big ), or if the icon is ). In this case, we will specify that the button always scales: f.buttonScaleWhen = scaleWhen.always; property to one of the following values: or . In this case, we will specify that the butt on scales proportionally: f.buttonScaleHow = buttonScaleHow.proportional; To guarantee that the icon scales within th e bounds of the rectangular region for the property: f.buttonFitBounds = true; You can specify the alignment characte properties. This is done by specif ying the percentage of the unused horizontal space from the left or the vertical space from the bottom that is distributed. A value of would 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.buttonAlignX = 50; f.buttonAlignY = 50; Now that you have prepared the space within the button for the icon, you can import an icon into the document and plac e it within the buttons area. To import an icon, invoke the objects method. To place the icon in the button, invoke the button objects , the following code would cause the icon to appear on the buttons face: f.setIcon(myIcon); property: f.rotation = 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 method, which requires a trigger (an indication of the type of mouse ev ent) and an associated script. The possible triggers are f.setAction("MouseUp", "app.alert(Hello);" ); Using Acrobat JavaScript in Forms Forms Essentials 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: In the case of , however, the font is always set to 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 cross star ), and square ). For example, the following code causes a check to appear when the user clicks in the check box: f.style = style.ch; When the user selects a check box, an export value may be associated with the option invoking the objects property. For example, the code below associates the export value with the check box: f.setExportValues(["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: Invoke the fields method. Note that since there may be several check boxes that belong to the same group, objects This process is shown in the following code: f.defaultIsChecked(0); // 0 means that check box #0 is checked this.resetForm([f.name]); Acrobat JavaScript Scripting Guide Using Acrobat JavaScript in Forms Forms Essentials 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 property, as shown in the following code: f.editable = true; property. The following code indicates that the spelling is not f.doNotSpellCheck = true; 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 button. In the first case, as soon as th e user clicks on an item in the combo box, an action may property to . Otherwise, set the value to . The following code commits the selected value immediately: f.commitOnSelChange = true; f.setItems( ["Ohio", "OH"], ["Oregon", "OR"], ["Arizona", "AZ"] ); In many cases, it is desirable to maintain a sorted collection of values in a combo box. In order to do this, you will need to write your own sorting script. Recall that the JavaScript object has a This means that you must first define a function that accepts two parameters. Using Acrobat JavaScript in Forms Forms Essentials Acrobat JavaScript Scripting Guide In the following example, we define a ["Ohio", "OH"] ["Arizona", "AZ"] the function returns , since "Ohio" is greater than "Arizona" function compare (a,b) Create a temporary array of values and populate it with the user/export value pairs in your combo box field. The following code creates the array, iterates through the combo box items, and copies them into the array: var arr = new Array(); for (var i = 0; i f.numItems; i++) At this point you may invoke the objects f.clearItems(); f.setItems(arr); Table . Their definitions are located in the file Javascripts\aform.js : trigger name as the first f.setAction("Format", AFNumberFormat(2,0,0,0,"\u20ac",true)); OTE You may also create Custom formatting. ABLE Combobox Formatting Functions Format Function Number Percentage Date Time Special Acrobat JavaScript Scripting Guide Using Acrobat JavaScript in Forms Forms Essentials 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 en property to , as shown in the code below: f.multipleSelection = true; method and pass in the trigger name as the first parameter, as shown in the code below: f.setAction( "Keystroke", "myListboxJavascript();" ); 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 proper method and passing in the trigger Once a document is signed, you may wish to lo ck certain form fields within the document. You may do so by creating a script cont aining a call to the signature fields method and passing that script as the second parameter to the signature fields method. The object, which you will obtain by invoking the form fields method. Once you obtain the properties. The action (lock all fields), (lock all fields except for these), or (lock only these fields). The property is an array of fields. For example, suppose you created a signature an d would like to lock the form field whose name is after the user signs the document. The following code would lock oLock.action = "include"; oLock.fields = new Array("myField"); f.setLock(oLock); To actually sign a document, you must do two things: choose a security handler, and then invoke the signature fields method. The following code is an example of how to choose a handler and actually sign the document: Using Acrobat JavaScript in Forms Forms Essentials Acrobat JavaScript Scripting Guide var ppklite = security.getHandler("Adobe.PPKLite"); var oParams = { password: "myPassword", cDIPath: "/C/signatures/myName.pfx" // digital signature profile ppklite.login(oParams); f.signatureSign(ppklite, password: "myPassword", location: "San Jose, CA", reason: "I am approving this document", contactInfo: "userName@adobe.com", appearance: "Fancy" ); //end of signature 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 ABLE Text Field Formatting Property Description justify text f.alignment = "center"; set a default text string f.defaultValue = "Name: "; allow multiple lines in the area f.multiline = true; permit scrolling of long text f.doNotScroll = true; set rich text formatting f.richText = true; limit on number of characters in area f.charLimit = 40; use special formatting to protect the users password f.password = true; format field as a file f.fileSelect = true; set spell checking f.doNotSpellCheck = true; comb of characters subject to limitation set by f.comb = true; Acrobat JavaScript Scripting Guide Using Acrobat JavaScript in Forms Forms Essentials 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 method, and pass is located in Javascripts\aform.js value), (first value in the range), (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: "Validate", AFRange_Validate(true, 0, true, 100) Calculation Options Calculation options make it possible to auto mate mathematical calculations associated with form fields. To apply a calculation to a form field action, invoke the form fields 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 in the second parameter. The function is located in Javascripts\aform.js (the type of calculation to be performed) and (a field list that may be separated by commas or spaces, or ), product ( ), average ( ), minimum ( ), or maximum ( For example, the following code calculates th e sum of the values entered into two text areas on a form: var arr = new Array("line.1", "line.2"); "Calculate", AFSimple_Calculate("SUM",arr) Using Acrobat JavaScript in Forms Forms Essentials 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: this.addAnnot({ page: 2, strokeColor: color.yellow, type: "Highlight", }); Alerting Users Automatically for Required Form Fields A user action such as clicking a button or leaving a page could trigger validation For example, suppose the user has forgotten to fill in the text field and has clicked the button. The following script would alert the user to the problem, and could be followed with code that highlights the text: app.alert("You forgot the field shown in yellow."); 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 property to as shown in the following code: f.readonly = false; property to , as shown in the following code: f.editable = true; Acrobat JavaScript Scripting Guide Using Acrobat JavaScript in Forms Forms Essentials Setting the Hierarchy of Form Fields . The 4 radio buttons would then be named . The convenience of this naming system becomes most apparent when you decide that all members of the group f.style = style.ch; // glyph style for all radio buttons 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 . The 3 groups would be named . Suppose the first group, , has 2 radio buttons in it. They would be named . 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: f.style = style.ch; // glyph style for all 3 groups You can also differentiate the groups within the hierarchy. Suppose you would like to designate a yellow background color for the thir f.fillColor = color.yellow; // affects only the 3rd group 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 objects 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 Using Acrobat JavaScript in Forms Forms Essentials 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 temp late 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 inch = 72 points var inch = 72; // obtain the page coordinates in Rotated User Space // position the top left corner 1 inch from the left side aRect[0] += 1 * inch; // make the rectangle 1 inch wide aRect[2] = aRect[0] + 1*inch; // top left corner is 0.5 inch down from the top of the page aRect[1] -= 0.5*inch; // make the rectangle 2 inches tall aRect[3] = aRect[1] - 2*inch; // draw the button var f = this.addField("myButton", "button", 2, aRect); Duplicating Form Fields 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 th e same name and actions to each of them. In the example below, we will create duplicate text fields, each named , on page 2 of the document for (var i = 0; i 5; p++) var aRect = [36, 36+100*i, 72, 144+100*i]; var f = this.addField("myField", "text", 2, aRect); f.fillColor = yellow; Acrobat JavaScript Scripting Guide Using Acrobat JavaScript in Forms Forms Essentials 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 myColumn = new Array(3); myColumn[0] = "myFieldCol.name"; myColumn[1] = "myFieldCol.birthday"; myColumn[2] = "myFieldCol.ssn"; var aRect = [36, 36, 72, 144]; for (var i=0; imyColumn.length; i++) aRect[1] += 100; // move the next field down 100 points aRect[3] += 100; // move the next field down 100 points var f = this.addField(myColumn[i], "text", 0, aRect); Creating Form Fields Th at 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 th e same name and actions to each of them. In the example below, we will create duplicate text fields, each named , on every and we will set the background color of every instance to yellow: for (var p = 0; p this.numPages; p++) var aRect = [36, 36, 72, 144]; var f = this.addField("myField", "text", p, aRect); f.fillColor = yellow; Defining the Tabbing Order You may specify the tabbing order on a given page by invoking the objects There are three options for tabbing order: you may specify tabbing by rows ( columns ( ), or document structure ( Using Acrobat JavaScript in Forms Forms Essentials 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 fo rm fields in the array runs, beginning with the first element in the array (array index ) 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 inde x, accessed through the objects property. A form field script with a lower ca lculation index executes first. The following code guarantees that the calculation script for form field will run before the one for form b.calcOrderIndex = a.calcOrderIndex + 1; Acrobat JavaScript Scripting Guide Using Acrobat JavaScript in Forms Forms Essentials Making PDF Forms Web-Ready PDF forms can be used in workflows that re quire the exchange of information over the Web. You can create forms that run in Web browsers, and can submit and retrieve You will need a CGI application on the Web serv er that can facilitate the exchange of your forms information with a database. The CG I 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 HT ML, 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 pars er or library to read the XFDF data. The equivalent MIME types for all posted form data are shown below in Table Creating Submit Buttons When you use the Button tool, use the trigger 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 recogn ize and reconstruct a digital signature, it is advisable that you choose the Incremental Changes to the PDF option. In this case, when you create the trigger, select Reset a Form . Now you will be Creating Import Data Buttons trigger, select Import Form Data ABLE MIME Types for Data Formats Data Format MIME Type application/x-www-form-urlencoded application/vnd.fdf application/vnd.adobe.xfdf application/pdf application/xml Using Acrobat JavaScript in Forms Forms Essentials 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 co mbo 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 repr esents identifying info rmation 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 thro ugh the use of templates based on the XML 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. Us e XDP if the data is processed by server applications, and PDF if the data is processed by Acrobat. Acrobat JavaScript Scripting Guide Using Acrobat JavaScript in Forms Forms Essentials 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 contai ned 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 base d 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 chec ks 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 consider ed to have their own field type. There is automatic support for browsing images in al l 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. Acrobat JavaScript provides access to the XFA container, which provides the properties and methods indicated below in Table Table 6.7 ABLE appModel Properties appModel Property Description The node represented by the alias for this model Returns all nodes with the same name or class Returns Using Acrobat JavaScript in Forms Forms Essentials Acrobat JavaScript Scripting Guide Returns all nodes with the same class name Returns the position of this node in the collection of nodes having the same class name Returns the class name of the object The current node (needed for resolveNode and resolveNodes) The ID of the current node Returns the position of this node in the collection of nodes having the same name Returns true if this is a container object Returns true if the node has a null value Returns the XFA model for this node The name of this node A list of child nodes for this node The namespace for this node (or XFAModel) Retrieves the parent of this node Retrieves the SOM expression for this node Retrieves the current node (starting node for resolveNode and resolveNodes) ABLE 6.6appModel Properties appModel PropertyDescription Acrobat JavaScript Scripting Guide Using Acrobat JavaScript in Forms Forms Essentials ABLE appModel Method Description Performs an XSL transformation of the current node Sets the value of the node, and creates one if necessary Clears the current list of errors Clones a node (and its subtree if specified) Creates a new XFA node based on a valid classname Retrieves a specified attribute value Retrieves a specified property element Determines if two namespaces are equivalent Checks if a specific property has been defined for the Loads and appends the current XML document to the Obtains the node corresponding to the SOM expression Obtains the XFATreeList corresponding to the SOM expression Saves the current node to a string Sets a specified attribute value Sets a specified property element Using Acrobat JavaScript in Forms Forms Essentials Acrobat JavaScript Scripting Guide The XFA DOM model contains a root ob ject that consists of either a or a consists of a list of nodes (which consists of a hierarchical structure of nodes, each of which may contain content, a model, or a The following properties and methods are available in a object: Properties: , and The following properties and methods are available in a object: Properties: element represents an element and its ch ildren in the XML DOM. To obtain a string representation of the node, invoke its method. To apply an XSL transform (XSLT) to the node and its children, invoke its object: Properties: 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 The permits the manipulation of an XM L document via an XPath, and the object. The first approach involves the usage of the objects objects Both approaches are illustrated below. Acrobat JavaScript Scripting Guide Using Acrobat JavaScript in Forms Forms Essentials In this first example, the usage of the // Create the XML stream var parseString = "purchasepu6;rch6; se6;"; parseString += "produpro;mu6;t00;ct"; parseString += "pricepri;泦299.00/pric/pr;ic6;e"; parseString += "namnam;渀eiPod/na/6na;me0;me"; parseString += "/product/pr;od6;uct6;"; parseString += "produpro;mu6;t00;ct"; parseString += "pricepri;泦49.95/price/6pr;i6ce;怀"; parseString += "namnam;渀ecase/na/6na;me0;me"; parseString += "/product/pr;od6;uct6;"; parseString += "/purchas/pu;rc6;has6;e"; // Now create the DOM: var x = XML.parse(parseString); // Use the XFA API to obtain the XFA tree list for products: var products = x.resolveNodes("product"); // Obtain the iPod product: var iPod = products.item(0); // Obtain the iPod price: // Convert the price to a string: var priceString = price.saveXML(); This next example accomplishes the same task through the usage of the method: // Create the XML stream var parseString = "purchasepu6;rch6; se6;"; parseString += "produpro;mu6;t00;ct"; parseString += "pricepri;泦299.00/pric/pr;ic6;e"; parseString += "namnam;渀eiPod/na/6na;me0;me"; parseString += "/product/pr;od6;uct6;"; parseString += "produpro;mu6;t00;ct"; parseString += "pricepri;泦49.95/price/6pr;i6ce;怀"; parseString += "namnam;渀ecase/na/6na;me0;me"; parseString += "/product/pr;od6;uct6;"; parseString += "/purchas/pu;rc6;has6;e"; // Now create the DOM: var x = XMLData.parse(parseString,false); var xPathExpr = "//purchase/product/[name='iPod']/price"; // Now get the iPod price: var price = XMLData.applyXPath(x, xPathExpr); Using Acrobat JavaScript in Forms Filling in PDF Forms Acrobat JavaScript Scripting Guide The following Acrobat JavaScript 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 objects object. 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 Acrobat JavaScript Scripting Guide Using Acrobat JavaScript in Forms Filling in PDF Forms 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 mu ch smaller than the original PDF file. When importing XFDF data, you will need an XM L 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 objects method using the conversion ID for XML, as shown in the code below: this.saveAs("myDoc.xml", "com.adobe.acrobat.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: this.saveAs("myDoc.xml", "com.adobe.acrobat.xdp"); objects method, which exports the data to FDF and sends it via email. To make an interactive email session, pass this.mailForm(true); To send the exported FDF data automatically, pass to the first parameter, and specify the fields (all of which are optional), as shown in the code below: this.mailForm(false, "recipient@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 action 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 objects method to upload the combined XML data to the server. Using Acrobat JavaScript in Forms Filling in PDF Forms Acrobat JavaScript Scripting Guide The following example merges the data from several XML form attachments and submits it to a server: var oParent = event.target; var oDataObjects = oParent.dataObjects; if (oDataObjects == null) app.alert("This form has no attachments!"); else { // Create the root node for the global submit: "dataGroup", "globalSubmitRootNode" // Iterate through all the attachments: var nChildren = oDataObjects.length; for (var iChild = 0; iChild nChildren; i++) { // Open the next attachment: var oNextChild = oParent.openDataObject( oDataObjects[iChild].name // Transfer its data to the XML collection: oSubmitData.nodes.append( oNextChild.xfa.data.nodes.item(0) close the attachment// oNextChild.closeDoc(); // Submit the XML data collection to the server oParent.submitForm({ cURL: "http://theserver.com/cgi-bin/thescript.cgi", cSubmitAs: "XML", oXML: oSubmitData }); Acrobat JavaScript Scripting Guide Using Acrobat JavaScript in Forms 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. On ce 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 structure d 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 alte rnative 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 Proper ties 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 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 console.println("TTS available: " + tts.available); The next code sample illustrates how to enumerate through all available speakers, queue a for (var i=0; itts.numSpeakers; i++) { console.println("Speaker[" + i + "] = " + cSpeaker); tts.speaker = cSpeaker; tts.qText("Hello"); tts.talk(); Using Acrobat JavaScript in Forms Making Forms Accessible Acrobat JavaScript Scripting Guide The properties and methods of the object are summarized below in Table Table ABLE TTS Properties Property Description Returns if the Text-To-Speech engine is available Returns the number of speakers in the engine A speaker with desired tone quality The rate in words per minute The volume between 0 and 10 Acrobat JavaScript Scripting Guide Using Acrobat JavaScript in Forms Using JavaScript to Secure Forms 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 th e original content. The annotation types supported for accessibility are: Text FreeText Square Circle Polygon Polyline Squiggly Strikeout Stamp Caret Popup FileAttachment Sound To add an accessible tag, select Advanced Accessibility and choose Add Tags to Document 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 Acrobat JavaScript provides a number of obje cts that support security. These are managed by the and objects for building certificates and signatures, as well as the , and objects which are used to access the user certificates. (The object provides read-only access to an X.509 public key certificate). ABLE TTS Methods Description Retrieves Nth speaker in current Text-To-Speech engine Pauses the audio output Queues a period of silence into the text Inserts a sound cue using a .wav file Inserts text into the queue Stops playback, flush the queue, reset all Text-To-Speech properties Resumes playback on a paused object Stops playback and flush the queue Sends queue contents to Text-To-Speech engine Using Acrobat JavaScript in Forms Using JavaScript to Secure Forms Acrobat JavaScript Scripting Guide These objects, in combination, provide you wi th the means to digitally sign or encrypt a document. Once you have built a list of authorized recipients, you may then encrypt the objects 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: // Invoke the recipients dialog to select which recipients // will be authorized to view the encrypted document: var oOptions = { bAllowPermGroups: false, cNote: "Recipients with email and certificates", bRequireEmail: true, bUserCert: true var oGroups = security.chooseRecipientsDialog(oOptions); // Build the mailing list var numCerts = oGroups[0].userEntities.length; var cMsg = "Encrypted for these recipients:\n"; var mailList = new Array; for (var i=0; inumCerts; i++) { var ue = oGroups[0].userEntities[i]; var oCert = ue.defaultEncryptCert; if (oCert == null) oCert = ue.certificates[0]; cMsg += oCert.subjectCN + ", " + ue.email + "\n"; var oRDN = oCert.subjectDN; if (ue.email) mailList[i] = ue.email; else if (oRDN.e) mailList[i] = oRDN.e; // Now encrypt the document this.encryptForRecipients(oGroups); Acrobat JavaScript Scripting Guide Using Acrobat JavaScript in Forms Using JavaScript to Secure Forms The and Table ABLE Security Properties Property Description Returns an array of security handler names User preference to be automatically validated when document opens ABLE Security Methods Description Opens a dialog to choose a list of recipients Obtains a security handler object Saves a object to a local disk Reads in a object from a local disk Using Acrobat JavaScript in Forms Using JavaScript to Secure Forms Acrobat JavaScript Scripting Guide Acrobat JavaScript Scripting Guide Review, Markup, and Approval 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 availabl e 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 Acrobat JavaScript Scripting Guide Introduction You may initiate several types of review workflows for PDF documents: 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 Re ader. 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 objects : permits full and unrestricted access to the entire document. : permits content accessed for readers with visual or motor impairments. : permits content copying and extraction. : permits either no changes, or chan ges to part or all of the document assembly, content, forms, signatures, and notes. : 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 Review, Markup, and Approval Online Collaboration Essentials The following code allows full and unrestricted access to the entire document for one set of ), and allows high quality prin var sh = security.getHandler("Adobe.PPKMS"); var dir = sh.directories[0]; var dc = dir.connect(); var importantUsers = dc.search({oParams:{lastName:"Smith"}}); var otherUsers = dc.search({oParams:{lastName:"Jones"}}); this.encryptForRecipients({ oGroups:[ oCerts: importantUsers, oPermissions: { allowAll: true } oCerts: otherUsers, oPermissions: { allowPrinting: "highQuality" } }); 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 objects method. In the code shown below, the document is automatically sent to recipient@adobe.com this.mailDoc( false, "recipient@adobe.com", "", "", "Review", "Please review this document and return. Thank you." OTE For Windows systems, the default mail program must be MAPI-enabled. Review, Markup, and Approval Online Collaboration Essentials 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 do ne 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 object provides you with control over the possible states objects may have, and may be used in conjunction with the object to create an annotation store. There are several methods available within the object that enable you to describe the state model for the review: these include , and The method is used to add a new state model to Acrobat describing the possible states for an object using the model, and the method removes the model, though it does not affect previously created objects. Their usage is shown in the code below: // Add a state model try{ var myStates = new Object; myStates["initial"] = {cUIName: "Havent reviewed it"}; myStates["approved"] = {cUIName: "I approve"}; myStates["resubmit"] = {cUIName: "Make some changes"}; Collab.addStateModel({ cName: "ReviewStates", cUIName: "My Review", oStates: myStates, cDefault: "initial" }); // Now transition myAnnot to the "approved" state: myAnnot.transitionToState("ReviewStates", "approved"); catch(e){console.println(e);} // Now remove the state model try {Collab.removeStateModel("ReviewStates");} catch(e){console.println(e);} Acrobat JavaScript Scripting Guide Review, Markup, and Approval Online Collaboration Essentials You may also use the objects methods 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 objects methods. The objects : The internal name for the annotation store. : The display name for the annotation store. : The definition for the new store class. The new store class must contain the following definitions for the functions used to add, delete, update, and enumerate through the array of annotations: : Communicates with the Web service to request the array of annotations stored on the server. It is used when the PD F document is loaded for online review, or when the user clicks Send on the Commenting Toolbar : Passes the annotation data to the collaboration server so that it can be updated. : Uploads new and modified annotations to the server. The class , as shown in the sample code below, is defined sdkSOAPCollabSample.js The sample code below provides a standard example of how to use the and objects to customize your online collaborative review. Note that all of the reviewers must have a copy of the JavaScript collabor ation store code. In Acrobat 7.0, the Custom collaboration store type allows you to put the JavaScript on the server. The store type used CUSTOM , and the setting is a URL to the JavaScript file: // Here is the URL for a SOAP HTTP service: // Here is the internal name for the collaborative store: var myType = "mySOAPCollabSample"; Collab.setStoreSettings(mySetting, myType); Collab.defaultStore = myType; Review, Markup, and Approval Using Commenting Tools Acrobat JavaScript Scripting Guide // Add the collab store to the Acrobat Collab servers: if (typeof SOAPFileSys == "undefined") Collab.addAnnotStore( myType, "SOAP Sample", // Annot store instantiation function is required: create: function(doc, user, settings) return new SDKSampleSOAPAnnotStore( else return null; 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 Review, Markup, and Approval Using Commenting Tools Adding Note Comments The Acrobat JavaScript support for note comments is available through the objects and types. Making Text Edits Text edit comments, also known as markup, are us ed to indicate text that should either be removed or inserted. Text that should be remo ved 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 objects and types. Highlighting, Crossing Out, and Underlining Text The Acrobat JavaScript support for highlighting, crossing out, and underlining text is available through the objects types. A stamp can be created from a set of predefin ed 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 objects method. 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 objects and types, as shown in the example below: this.addAnnot({ page: 0, type: "Square", rect: [0,0,100,100], name: "OnMarketShare", author: "A.C. Robat" contents: "This section needs revision" }); Review, Markup, and Approval Using Commenting Tools Acrobat JavaScript Scripting Guide Adding Attachments You may use Acrobat JavaScript to embed soun d clips, images, and files within comments. The Acrobat support for sound and file attachments within comments is available through the objects and types. Also, you may pass an Icon Stream Generic Object as an optional property ( object literal used objects Sound Attachments To add a sound attachment using Acrobat JavaScript, invoke the objects method to attach the sound file to the PDF. Then create an annotation objects object with the annotation by assigning the name of the object to the objects property. An example is given below: // Attach the sound file to the PDF file this.importSound("mySound", "/C/mySound.wav"); // Create the annotation and assign its soundIcon property this.addAnnot({ page: 0, type: "Sound", rect: [0,0,100,100], name: "mySoundAnnot", soundIcon: "mySound" }); File Attachments To add a file attachment to a document, invoke one of the objects . Once the file contents have been imported they can be , and either merged with your document content or saved to a disk location. For example, the following code imports the contents of myFile.xml and displays its contents: // Open the file attachment named myFile.xml this.importDataObject(myData, "/C/myFile.xml"); // Access its contents: var contents = this.getDataObject("myData"); // Display its contents: for (var i in contents) console.println(contents[i]); objects property. At this point, you may decide how to associate the attachments name with the icon. Acrobat JavaScript Scripting Guide Review, Markup, and Approval Using Commenting Tools Personalizing Attachments with a Description 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: this.addAnnot({ page: 0, type: "Sound", rect: [0,0,100,100], name: "mySoundAnnot", soundIcon: "mySound" contents: "This is a sound file." }); Opening and Saving Attachments You may use Acrobat JavaScript to open any attachment. The general-purpose way to do this is to invoke the objects method. The following code opens an attachment and displays its contents in the console: var cFile = util.stringFromStream(oFile); console.println(cFile); To save and possibly open an attachment, invoke the objects which may be set to one of three values: (do not open, default), (prompt the user for a save path, and open), (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: // just save and do not open this.exportDataObject("MyAttachment"); // save and open this.exportDataObject({ cName: "MyComments.xls", nLaunch: 1} Review, Markup, and Approval Using Commenting Tools 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 objects method in order to begin accessing its contents, and in order to save the modified contents, as shown in the code sample below: // Open the file: this.importDataObject("myFile.txt", "/C/myFile.txt"); // access the FileStream (after which you may modify it): var cFile = util.stringFromStream(oFile, "utf-8"); // now modify the string cFile // ... // Convert the modified string back to a FileStream: oFile = util.streamFromString(cFile, "utf-8"); // Save the modified FileStream contents: this.setDataObjectContents("myFile.txt", oFile); Linking Between Files objects method. To cause the action to open the file. Deleting Attachments You may use Acrobat JavaScript to remove a file attachment from a document by invoking the objects method, as shown in the code below: this.removeDataObject("myAttachment"); Spell-checking in Comments and Forms You may check the spelling of any word using the objects method. This can be applied to any form field or annotation. First retrieve the contents, and submit each word to the method. objects property. Then modify the or der of the array entries, and assign the array to the same property. An array of currently available dictionaries can be objects property. Acrobat JavaScript Scripting Guide Review, Markup, and Approval Using Commenting Tools To set the language order, perform a similar algorithm using the objects property. An array of currently available dictionaries can be objects property. Adding Words to a Dictionary You may use Acrobat JavaScript to add words to a dictionary by invoking the objects spell.addWord(myDictionary, "myNewWord"); Adding Commenting Preferences objects // Create the common properties in an object literal: var myProps = { strokeColor: color.red, popupOpen: true, arrowBegin: "Diamond", arrowEnd: "OpenArrow" // Assign the common properties to a previously created annot: Changing Colors, Icons, a nd 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 property. To change the icon, assign a value to its property. All the comment properties are available through the Review, Markup, and Approval Using Commenting Tools Acrobat JavaScript Scripting Guide Adding Watermarks A watermark is an area containing text or grap hics 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 objects or method 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 objects Acrobat JavaScript Scripting Guide Review, Markup, and Approval Using Commenting Tools For example, the following code adds an "Approved" stamp to the document: var annot = this.addAnnot({ page: 0, type: "Stamp", author: "Me", name: "myStamp", rect: [400,400,550,500], contents: "Good work!", AP: "Approved" }); Header and Footer Functionality You may use Acrobat JavaScript to add headers and footers to your documents. For example, you may use the objects method, which has several properties useful for this specific purpose: The actual text displayed in the header or footer. How the text is aligned in the header or footer. How the watermark is aligned vertically: a value of aligns it at the top of the page (header), and a value of aligns it at the bottom of the page (footer). The starting page for the watermark. A value of 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 The font name. The font size (in points). The text alignment. The rotation in degrees. The opacity from 0.0 to 1.0, where 0 means transparent and 1 means opaque. Approval Approval workflows may include an automa ted 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 objects method. The user may then objects property), use a custom stamp, or use a Hanko stamp to cr eate a secure digital signature. Review, Markup, and Approval Managing Comments Acrobat JavaScript Scripting Guide Just as you can access the Comments List in the Acrobat user interface, you may likewise do so through Acrobat JavaScript, using the objects and method guarantees th at all annotations in the documents are scanned, and the For example, the following code scans all the annotations on page 2 of the document and captures them all in the variable myAnnotList this.syncAnnotScan(); var myAnnotList = this.getAnnots({nPage: 2}); To move a comment, use the corresponding objects method to specify objects for (var i=0; imyAnnotList.length; i++) myAnnotList[i].destroy(); Topics 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 Review, Markup, and Approval Managing Comments Using the Comments List Once you have acquired the comments list through the objects Changing the Status of Comments To change the status of a comment using Ac robat JavaScript, invoke the corresponding objects // Transition myAnnot to the "approved" state: myAnnot.transitionToState("ReviewStates", "approved"); Changing the Appearance of Comments You may change the appearance of a comment property. In general, the appearance of any comment ma y be changed by invoking the objects page: 0, points: [[10,40], [200,200]], strokeColor: color.red, popupOpen: true, popupRect: [200,100,400,200], arrowBegin: "Diamond", arrowEnd: "OpenArrow" }); 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 Acrobat JavaScript Scripting Guide Sorting Comments If you would like to sort comments using Acro bat JavaScript, you may do so by submitting an optional parameter to the objects method. The Do not sort. Sort by page number. Sort by author. Sort by modification date. Sort by annotation type. In addition, you may specify that the sorting be performed in reverse order by submitting parameter to the method. The code sample given below shows how to obta in a list of comments from page 2 of the document, sorted in reverse order by author: this.syncAnnotScan(); var myAnnotList = this.getAnnots({ nPage: 2, nSortBy: ANSB_Author, bReverse: true }); Showing and Hiding Comments objects property. For example, the following code hides myAnnot.hidden = true; 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 objects method. Otherwise you may obtain all the comments by invoking the objects The Acrobat JavaScript Scripting Guide Review, Markup, and Approval Managing Comments Exporting and Importing Comments To use Acrobat JavaScript to export all the comments in a file, invoke the objects methods. In both cases, set the , as shown in the code sample below, which exports only the comments this.exportAsFDF({bAnnotations: true}); To use Acrobat JavaScript to import comments from an FDF or XFDF into a file, invoke the objects methods. 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 objects method for each document you would like to analyze. Each 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"); console.println("Doc 1: " + annotsDoc1.length + " annots."); console.println("Doc 2: " + annotsDoc2.length + " annots."); Aggregating Comments for Use in Excel The objects 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 objects objects method. Extracting Comments in a Batch Process In a batch process, you may open any number of objects using the objects method. For each open document, you may invoke its corresponding objects Review, Markup, and Approval Approving Documents Using Stamps (Japanese Workflows) 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 ma y be sent to the initiator. Setting up a Hanko Approval Workflow A registered Hanko is a stamp used in Japa nese 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 Adding Instructions 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 objects method. Topics Setting up a Hanko Approval Workflow Participating in a Hanko Approval Workflow Acrobat JavaScript Scripting Guide Review, Markup, and Approval Approving Documents Using Stamps (Japanese Workflows) Participating in a Hanko Approval Workflow A participant receives an email with instructions for opening the document and 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 individual s 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 othe r stamps by creating a stamp annotation and objects property. You can obtain a list of stamp names available in the document by accessing the objects property. Installing and Customizing Hanko Stamps Creating custom Hanko stamp information invo lves the combination of user information Stamps 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 contai ning personal informatio n. In addition, it is possible to add secure digital sign ature information to an Inkan stamp. Deleting Custom Stamps Review, Markup, and Approval Approving Documents Using Stamps (Japanese Workflows) Acrobat JavaScript Scripting Guide Acrobat JavaScript Scripting Guide Working with Digital Media in PDF 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. 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 Acrobat JavaScript Scripting Guide 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 ABLE Media Player Objects Object Description Primary object for media control, settings, and renditions Time or frame position within a media clip A multimedia event fired by a object A collection of multimedia event objects An instance of a multimedia player A location representing a frame or time value in a media clip Aall the markers in the c urrently loaded media clip Contains error information when a object is rejected A media selection object used to create the object object A display monitor used for playback An array of display monitors connected to the users system An available media player An array of objects Contains information needed to play a media clip A display area used for media playback Acrobat JavaScript Scripting Guide Working with Digital Media in PDF Documents Media Players: Control, Settings, Renditions, and Events Accessing a List of Active Players To obtain a list of available players, call the objects method, which accepts an optional parameter sp ecifying the MIME type and returns a object. The object is an array of objects that can be filtered using its method. The following code sample shows how to obtain a list of all available players: The following code sample shows how to obtain a list of all available MP3 players and prints them out to the console: for (var i = 0; i mp.length; i++) { console.println("\nmp[" + i + "] Properties"); for (var p in mp[i]) console.println(p + ": " + mp[i][p]); To filter the list of players using the objects properties, each of which may be either a string or a regular expression. For example, the following code obta ins the QuickTime media player: In addition, the objects objects. With this array, you can stop or close all players, for (var i in players) players[i].stop(); 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 Acrobat JavaScript Scripting Guide Specifying Playback Settings You can use Acrobat JavaScript to obtain and ad objects object, as shown in the code below: In additon to the properties and methods, a object, which is used to create a object, contains many properties related to the functional capabilities of players. These are described below in Table ABLE Property Description Determines whether to play media clip automatically when the player is opened Used to resolve any relative URLs used in the media clip Specifies the background color for the media player window Specifies the background opacity for the media player window Defines the ending time or frame for playback The contents of the media clip ( object) The number of seconds required for playback An object containing the locati on and size properties of a floating window used for playback Defines the rectangle containing the display monitor used for playback The category of display monitor used for playback (such The document page number used in case a docked media player is used Indicates that the media can play from beginning to end, and then in reverse from the end to the beginning The list of available players for this rendition The playback speed Acrobat JavaScript Scripting Guide Working with Digital Media in PDF Documents Media Players: Control, Settings, Renditions, and Events if (nRepeat == 1) nRepeat = 2; else nRepeat = 1; app.media.openPlayer(args); The example below illustrates how to play a docked media clip in a Screen annotation: app.media.openPlayer({ annot: this.media.getAnnot({ nPage: 0, cAnnotTitle: "myScreen" }), windowType: app.media.WindowType.docked }); The number of times the playback repeats Defines the starting time or frame for playback The playback volume An enumeration obtained from ABLE 8.2MediaSettings Object Properties PropertyDescription Working with Digital Media in PDF Documents Media Players: Control, Settings, Renditions, and Events Acrobat JavaScript Scripting Guide The next example illustrates how to play back th e alternate text of a rendition in a floating window: var args = { showAltText: true, showEmptyAltText: true var selection = rendition.select(); canResize: app.media.canResize.keepRatio, hasClose: true, width: 400, height: 100 // play the alternate text in the floating window args = { rendition: rendition, annot: this.media.getAnnot({ nPage: 0, cAnnotTitle: "myScreen" }), app.media.openPlayer(args); Acrobat JavaScript Scripting Guide Working with Digital Media in PDF Documents The Acrobat JavaScript object is a read-only array of objects, each of which represents a display monitor connected to the users system. It is available as a property of the object, and you may write customized Acrobat JavaScript code to iterate through this array to obtain informatio n about the available monitors and select one for a full-screen or popup media player. It is possible to apply filtering criteria to se lect 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 object, and are listed below in Table ABLE Description Creates a new monitor representing the entire virtual desktop Returns the monitors containing the greatest amount of the document Returns the monitors with the greatest height in pixels Working with Digital Media in PDF Documents Monitors Acrobat JavaScript Scripting Guide In addition to the ca pabilities within the object, the 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 monitors = app.monitors.primary(); if (monitors.leng th 0) console.println("Color depth: " + monitors[0].colorDepth); The next example llustrates how to obtain the mo nitor with the greatest color depth, with a minimum specified depth of 32: var monitors = app.monitors.bestColor(32); if (monitors.leng th 0) console.println("Found the best color depth over 32!"); The next example llustrates how to obtain the monitor with the greatest width in pixels, var monitors = app.monitors.widest(); var isIsNot = (monitors[0].isPrimary) ? " is " : " is not "; console.println("Widest monitor" + isIsNot + "the primary."); ABLE Monitor Object Properties Property Description The color depth of the monitor in bits per pixel if the monitor is the primary one The boundaries of the monitor in virtual desktop coordinates The monitors workspace boundaries in virtual desktop coordinates Acrobat JavaScript Scripting Guide Working with Digital Media in PDF Documents Integrating Media into Documents You may use Acrobat JavaScript to integrate media into documents, which may be played Screen Annot objects or floating windows. The object 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 objects // create the media player object var player = app.media.createPlayer(); // filter for those that can play a movie (specify MIME type) player.settings.players = app.media.getPlayers("video/x-mpg"); // choose which file to play player.settings.data = "myClip.mpg"; // open the player player.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 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 myURLClip = "http://myWebSite.com/mySoundClip.mp3"; var args = { URL: myURLClip, mimeType: "audio/mp3", doc: this, windowType: app.media.windowType.floating, floating: {height: 400, width: 600} app.media.openPlayer(args); Adding and Editing Renditions object contains information needed to play a media clip, including embedded media data (or a URL), and play back settings, and corresponds to the 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 action. 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 objects rendition. object. There are several properties to which you have read-only access when editing a rendition. These are listed below in Table Acrobat JavaScript Scripting Guide Working with Digital Media in PDF Documents Setting Multimedia Preferences In addition to these properties, you may invoke the objects method, which returns a object. As you learned earlier in , you can adjust the settings through this object. You may also invoke its In general, you may choose which media player should be used to play a given clip, dubbed audio, or supplemental text captions). In addition, you may use Acrobat JavaScript to access or customize multimedia preferences. For example, the objects property may be used to indicate objects property can be used to specify the background color for the media player window. Examples of each are given below: var canPlay = doc.media.canPlay; if (canPlay.no) { if (canPlay.no.security) { if (canPlay.canShowUI) app.alert("Security prohibits playback."); else console.println("Security prohibits playback."); ABLE Rendition Object Properties Property Description The alternate text string for the rendition The document that contains the rendition Returns the filename or URL of an external media clip object or a rendition list The name of the rendition Working with Digital Media in PDF Documents Setting Multimedia Preferences Acrobat JavaScript Scripting Guide Acrobat JavaScript Scripting Guide Acrobat Templates This chapter will help you gain a greater dept h 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 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. Specify the proper syntax and usage of 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 Acrobat JavaScript Scripting Guide Introduction Acrobat JavaScript defines a object that supports interactive form architectures. In this context, a is 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 cont ain 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 includ e form fields such as text fields and buttons, digital signatures, and embedded logic such as JavaSc ripts that email form data to another user. To create a template based on a page, invoke the objects 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 based on page 5 of the current document: this.createTemplate({cName: "myTemplate", nPage: 5}); There are two steps required to generate pages based on a template contained in the Select a template from the objects property, which is an array of objects. Spawn a page invoking the objects method. 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 myTemplateArray = this.templates; var myTemplate = myTemplateArray[0]; myTemplate.spawn(this.numPages, false, false); Acrobat JavaScript Scripting Guide Acrobat Templates Spawning Templates Spawning Templates Dynamic Form Field Generation When spawning templates, you may specify wh , 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 othe r pages. This would be useful, for example, in , the form fields on each spawned page have the same name as their counterparts on all the other spawned pages. This might be us eful 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 and the field name on the template is . If the template is named and is spawned onto page 4, the new corresponding field name is . The page number embedded in the new field guarantees its uniqueness. Dynamic Page Generation objects (external graphics objects), and the other is to generate page contents as objects, which only requires that those objects be repositioned. The , the new page overlays onto the page number specified in the parameter. If the value is set to the new page is inserted as a new page before the specified page. To append a page at the value to false and the Acrobat Templates Spawning Templates 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 ( ), and the resultant pages will be appended to the end of the document ( will be ). The parameter will be used to prevent size inflation: // Obtain the collection of templates: var t = this.templates; // Spawn each template once as a page appended at the end: for (var i = 0; i t.length; i++) t[i].spawn(this.numPages, false, false); In this next example, the same template will be spawned 10 times, will overlay onto pages 0 through 9 ( will be ), and the field names will be unique on each page // Obtain the template: var t = this.templates; var T = t[0]; // Prevent file size inflation by using the XObject. Do this by // spawning once, saving the result (an XObject), and passing var XO = T.spawn(0, true, true); for (var i = 1; i 10; i++) T.spawn(i, true, true, XO); In this next example, we will retrieve the template named , overlay it onto pages 5 through 10 ( will be ), and use the same field names on each page // Obtain the template name "myTemplate": // Prevent file size inflation: var XO = t.spawn(5, true, false); // Spawn the remaining pages: for (var i = 6; i = 10; i++) t.spawn(i, true, false, XO); Acrobat JavaScript Scripting Guide Modifying the User Interface This chapter will provide you with an in-depth understanding of the ways in which you may present and modify the user interface. You wi ll 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 an d 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 Acrobat JavaScript Scripting Guide Using Adobe Dialog Manager Introduction The Adobe Dialog Manager (ADM) is a cross-pl atform 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 di alogs containing list objects and other controls normally included in graphical user interfaces, including buttons, text, text boxes, check boxes, radio buttons, progress bars, sc roll bars, and sliders. These are summarized below in Table 10.1 ABLE ADM Dialog Elements Element Type Description push button check box radio button list box hierarchical list box static text box editable text box popup control OK button OK and Cancel button OK, Cancel, and Other button place holder Acrobat JavaScript Scripting Guide Modifying the User Interface Using Adobe Dialog Manager (ADM) in Acrobat JavaScript ADM Object Hierarchy An ADM user interface consists of dialog objects and the items they contain. All items have ADM Hierarchy List Hierarchy List Box 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 Acrobat JavaScript Scripting Guide Popup Control Button Popup Spin Edit Control Password Text Edit Access to ADM through JavaScript The objects method is the Acrobat JavaScript method used to execute An instance of the object is passed to the method handlers. The object has two important methods: the method is used to initialize dialog elements, and the 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 , and each child node is a dialog element containing the properties shown below in Table . In addition to the standard properties described in Table 10.5 for dialog elements, there are sets of properties available for the elements. These are listed below in Table ABLE Dialog Handlers Description Method that runs when the dialog is created Method called when validating field values Method called when OK button is selected Method that runs when the dialog is destroyed Method called when an elements property is Acrobat JavaScript Scripting Guide Modifying the User Interface Using Adobe Dialog Manager (ADM) in Acrobat JavaScript ABLE Dialog Descriptor Element Properties Element Properties ABLE Root Node of Dialog Descriptor Property Description Title bar value for the active dialog item when the dialog is created value for the dialog item first in tab order Width of the dialog in pixels Height of the dialog in pixels Width of the dialog in characters Height of the dialog in characters Alignment for all descendants Array of elements contained in the dialog Modifying the User Interface Using Adobe Dialog Manager (ADM) in Acrobat JavaScript Acrobat JavaScript Scripting Guide ABLE Dialog Element Object Literal Property Description Displayed name of dialog element value for the dialog Dialog element type value for the next dialog item in the tab order Width of the element in pixels Height of the element in pixels Width of the element in characters Height of the element in characters The elements font: Bold font Italic font Alignment for the element Alignment for all descendents Array of elements contained in this element Acrobat JavaScript Scripting Guide Modifying the User Interface Using Adobe Dialog Manager (ADM) in Acrobat JavaScript The following example creates the modal dialog as shown below in Figure IGURE 10.1 ADM Dialog with Item Cluster To create a dialog such as the one above in Figure , first create an object literal containing a dialog descriptor, and pass it as a parameter to the objects Table , 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 handler is called as the dialog is created, and the handler is called when is selected. The handler processes those items. Modifying the User Interface Using Adobe Dialog Manager (ADM) in Acrobat JavaScript Acrobat JavaScript Scripting Guide The following handler initializes th e items used in the list_box . Note that it receives the // Event handler to initialize the list_box initialize: function(dialog) // Create a list_box named sub1 and set up 4 choices: dialog.load({ "sub1": "one": -1, "two": -2, "three": +3, "four": -4 }); The following is clicked, retrieves the values of the items used in the , and can take action based on those values. Note that it receives the commit: function(dialog) var elements = dialog.store()["sub1"]; // Iterate through items and take actions as needed for (var e in elements) // perform action It is also possible to write event handlers for specific items selected in the dialog. The following handler is called when the button labeled "butn": function(dialog) app.alert("butn was clicked."); Finally, to create the root node, we must create the object literal, which is the Acrobat JavaScript Scripting Guide Modifying the User Interface Using Adobe Dialog Manager (ADM) in Acrobat JavaScript var myDialog = initialize: function(dialog) dialog.load({ "sub1": // Note: positive value represents the selected item "one": -1, "two": -2, "three": +3, // currently selected item "four": -4 }); commit: function(dialog) var elements = dialog.store(); // Iterate through items and take actions as needed for (var e in elements["sub1"]) // If the value is positive, it was selected: if (elements["sub1"][e ] 0) // display the list value selected: app.alert("You chose:\n" + e); // call a related function for the selection rc = elements["sub1"][e]; ListHandler(rc); // event handler for butn button clicks "butn": function(dialog) app.alert("JavaScript ADM Dialog in Acrobat 7."); Modifying the User Interface Using Adobe Dialog Manager (ADM) in Acrobat JavaScript Acrobat JavaScript Scripting Guide // Dialog object descriptor (root node) description: name: "Sample Dialog", elements: type: "view", align_children: "align_left", elements: type: "cluster", name: "Item Cluster", elements: type: "static_text", name: "Select Item", font: "default" type: "list_box", item_id: "sub1", width: 200, height: 100 type: "button", item_id: "butn", name: "Press Me" type: "ok_cancel" Acrobat JavaScript Scripting Guide Modifying the User Interface Using Adobe Dialog Manager (ADM) in Acrobat JavaScript // Function to handle the users list selection: function ListHandler(rc) switch (rc) { case 1: app.alert("ListHandler response for 1 - one"); break; case 2: app.alert("ListHandler response for 2 - two"); break; case 3: app.alert("ListHandler response for 3 - three"); break; case 4: app.alert("ListHandler response for 4 - four"); break; default: app.alert("Invalid selection"); break; rc = app.execDialog(myDialog); Modifying the User Interface Adding Navigation to PDF Documents Acrobat JavaScript Scripting Guide Acrobat JavaScript provides a number of cons tructs that enable you to add and customize navigation features within PDF documents. Th ese features make it convenient for the user to see and visit areas of interest within th 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 Modifying the User Interface Adding Navigation to PDF Documents Thumbnails Creating Page Thumbnails The object provides methods for adding and removing thumbnails in a document. To add a set of thumbnails, invoke the objects method, which represent the beginning and en d of an inclusive range of page numbers. For example, to add thumbnails for page s 2 through 5, use the following command: this.addThumbnails({nStart: 2, nEnd: 5}); To add a thumbnail for just one page, just provide a value for . The following example adds a thumbnail for page 7: this.addThumbnails({nStart: 7}); To add thumbnails from page 0 to a sp ecified page, just provide a value for . The following example adds thumbnails for pages 0-7: this.addThumbnails({nEnd: 7}); To add thumbnails for all the pages in this.addThumbnails(); objects method, Adding Page Actions with Page Thumbnails You may associate a event 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 objects this.setPageAction(2, "Open", "app.alert(Hello);"); The advantage of this approach is that you ca n dynamically build JavaScript strings to be Bookmarks You can use Acrobat JavaScript to custom ize the appearance and behavior of the bookmarks that appear in the Bookmarks navigation panel. Every PDF document has an object known as , which is the root of the bookmark tree for the document. It is possible to recursively add an d modify levels of bookmarks underneath the root. Each node is a object which can have any number of children. Modifying the User Interface Adding Navigation to PDF Documents Acrobat JavaScript Scripting Guide Acrobat JavaScript makes the object available as a property of the object. This root node contains a property called , which is an array of objects. The object has the properties shown below in Table 10.6 and the methods shown below in Table 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 , which is a property of the current document representing the top node in the bookmark tree: var myRoot = this.bookmarkRoot; Assume there are no bookmarks in the docume nt. To create a new bookmark, invoke the objects (the name to appear in the navigational panel), (an optional JavaScript to be executed when the bookmark is clicked), and (an optional zero- based index into the array). ABLE Bookmark Properties Property Description Specifies the color for the bookmark The document object for the bookmark The text string appearing in the navigational panel Determines if children are shown The parent bookmark Font style ABLE Description Creates a new child bookmark Executes the action for the bookmark Inserts a bookmark as a new child for this bookmark (this may be used to move existing bookmarks) Removes the bookmark and all its children Sets a action for the bookmark Acrobat JavaScript Scripting Guide Modifying the User Interface Adding Navigation to PDF Documents The following code creates a bookmark that disp value means that it is plac ed at position 0 in the array: myRoot.createChild("myBookmark", "app.alert(Hello!);"); The following code adds a bookmark called as a child of var current = myRoot.children[0]; current.createChild("grandChild"); Suppose that you would like to move so that it becomes a child of the root. Invoke the root bookmarks var grandChild = myRoot.children[0].children[0]; myRoot.insertChild(grandChild, 1); Managing Bookmarks You can use Acrobat JavaScript to change the , and properties of a bookmark. Note that the property is an integer: means normal, means italic, means bold, and means bold-italic. The code below changes the name to color to red, and the font style to bold: var myRoot = this.bookmarkRoot; var myChild = myRoot.children[0]; myChild.name = "New Name"; myChild.color = color.red; myChild.style = 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 method. The following line of code removes all bookmarks from the document: this.bookmarkRoot.remove(); 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 hier archy, first add bookmarks to the root, then to the children of the root, and recursively to their children. The following code creates bookmarks . Each section has 3 children. Child children , and has children , and has children Modifying the User Interface Adding Navigation to PDF Documents Acrobat JavaScript Scripting Guide var myRoot = this.bookmarkRoot; myRoot.createChild("A"); myRoot.createChild({cName: "B", nIndex: 1}); myRoot.createChild({cName: "C", nIndex: 2}); for (var i = 0; i myRoot.children.length; i++) { var child = myRoot.children[i]; for (var j = 0; j 3; j++) { var name = child.name + j; child.createChild({cName: name, nIndex: 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: function DumpBookmark(bm, nLevel) // build indents to illustrate the level var s = ""; for (var i = 0; i nLevel; i++) s += " "; // print out the bookmarks name: console.println(s + "+-" + bm.name); // recursively print out the bookmarks children: if (bm.children != null) for (var i = 0; i bm.children.length; i++) DumpBookmark(bm.children[i], nLevel+1); // open the console to begin: console.clear(); console.show(); // recursively print out the bookmark tree DumpBookmark(this.bookmarkRoot, 0); Acrobat JavaScript Scripting Guide Modifying the User Interface Adding Navigation to PDF Documents Acrobat JavaScript provides support for the addition, customization, or removal of links within PDF documents. These links may be us ed to access URLs, fi le attachments, or destinations within the document. The Table . This is used in conjunction with the object, which contains properties as well as a method for customizing the appearance and behavior of a given link. Its properties are listed below in Table In addition, the object contains a property called , which can be used ABLE Doc Object Link Methods Description Adds a new link to a page Converts text instances to Web links with URL actions Opens a web page Goes to a named destination within the document Removes the links within a specifed area on a page Removes Web links created with the Acrobat user interface ABLE Link Properties Property Description The border color of the bounding rectangle The border width of the surrounding rectangle The visual effect when The rotated user space coordinates of the link Modifying the User Interface Adding Navigation to PDF Documents 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 objects var numberOfLinks = this.addWeblinks(); console.println("Converted " + numberOfLinks + " links."); To add a single link to a PDF document, first invoke the objects objects properties. The var linkWidth = 36, linkHeight = 18; for (var i = 0; i this.numPages; i++) // Create the coordinates for the left link: var lRect = [0, linkHeight, linkWidth, 0]; // Create the coordinates for the right link: var offset = cropBox[2] - cropBox[0] - linkWidth; // Create the Link objects: var leftLink = this.addLink(i, lRect); var rightLink = this.addLink(i, rRect); // Calculate the previous and next page numbers: var nextPage = (i + 1) % this.numPages; var prevPage = i - 1; if (prevPage 0) prevPage = this.numPages - 1; rightLink.setAction("this.pageNum = " + nextPage); // Customize the link appearance: leftLink.borderColor = color.red; leftLink.borderWidth = 1; rightLink.borderColor = color.red; rightLink.borderWidth = 1; Acrobat JavaScript Scripting Guide Modifying the User Interface Adding Navigation to PDF Documents Defining the Appearance of a Link The previous example contained code that se t the appearance of the bounding rectangle for the links through their properties. You may also specify how the link will appear wh property to one of four values: (the default), or for myLink.borderColor = color.blue; myLink.borderWidth = 2; myLink.highlightMode = "Outline"; 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 objects method. In the following example, is removed from page 2 of the document: var linkRect = myLink.rect; this.removeLinks(2, linkRect); To remove all links from the document, simply use the crop box for each page, as shown in the code below: for (var page = 0; page this.numPages; page++) var box = this.getPageBox("Crop", page); this.removeLinks(page, box); Creating Links from URLs To open a web page for a given link, invoke the objects objects method. For example, suppose you have created a object named . The following code opens http://myWebPage.com myLink.setAction("this.getURL( http://myWebPage.com )"); Linking to File Attachments To open a file attachment, embed a JavaScript in the call to the objects method. The script contains a call to the objects method. The following example opens myDoc.pdf when myLink.setAction("app.openDoc('/C/myDoc.pdf');"); Modifying the User Interface Adding Navigation to PDF Documents Acrobat JavaScript Scripting Guide Removing Web Links To remove Web links that were authored in Acrobat, invoke the objects represent the beginning and end of an inclus ive range of page numbers. The following examples illustrate how to remove Web links from different page ranges in the document: // remove the Web links from pages 2 through 5: this.removeWeblinks({nStart: 2, nEnd: 5}); // remove the Web links from page 7 this.removeWeblinks({nStart: 7}); // remove the Web links from pages 0 through 7: this.removeWeblinks({nEnd: 7}); // remove all the Web links in the document: this.removeWeblinks(); Using Destinations To go to a named destination within a docume nt, embed a JavaScript in the call to the objects objects method. The following example goes to in the current when myLink.setAction("this.gotoNamedDest('Chapter5');"); Using Actions for Special Effects Thumbnails, bookmarks, links, and other obje cts have actions associated with them, and you may use Acrobat JavaScript to customiz e their behavior. For example, you can use them to display messages, jump to destinations in the same document or any other, open Adding Actions As you learned earlier, you ma y associate a thumbnail with a event, and associate bookmarks and links with events. You may use Acrobat JavaScript to customize the actions asso ciated with a thumbnail by invoking the objects method. To customize the actions associated with bookmarks and links, create a string contai ning Acrobat JavaScript code and pass it to the objects method. In the examples shown below, a greeting is displayed when a thumbnail, bookmark, and link are clicked: Acrobat JavaScript Scripting Guide Modifying the User Interface Adding Navigation to PDF Documents // Open action for thumbnail: this.setPageAction(2, "Open", "app.alert('Hello!');"); // MouseUp actions for bookmark and link: myLink.setAction("app.alert('Hello!');"); Action Types The actions applied to navigational components represent a small portion of the possible Table ABLE Action Types and Associated Events Action Type Event Names Modifying the User Interface Adding Navigation to PDF Documents Acrobat JavaScript Scripting Guide Type of Triggers The event names shown above in Table represent the types of triggers that initiate the actions associated with events. They are described below in Table ABLE Trigger Descriptions Trigger Description Acrobat or Adobe Reader starts Batch sequence starts After document has printed After document has saved When the document is opened New page is opened or document is closed Just before the document is closed Just before the document is printed Just before the document is saved Just as the field loses focus A calculation is required for a field After and before After dependent events occurs Keystroke in textbox or combobox, or item is selected in combobox or listbox Mouse button is down Mouse button has been released Mouse enters a field or screen rectangle Mouse exits a field or screen rectangle After value has been committed to a field New page comes into view Old page leaves view Acrobat JavaScript Scripting Guide Modifying the User Interface Adding Navigation to PDF Documents 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 appear ance after the user has clicked on them. For a button, which is a field, you can invoke its property, which allows you to specify how the button appears once it has b een clicked. There are four choices, as shown below in Table 10.12 For example, the following code makes th e button appear pushed when clicked: f.highlight = highlight.p; As you learned earlier, the object also has a property. There are other ways in which you can creati vely 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 method. In the following example, the button displays a greeting and changes its background color to blue when the mouse enters its area: var script = "app.alert('Hello!');"; script += "var myButton = this.getField('myButton');"; script += "myButton.fillColor = color.blue;"; f.setAction("MouseEnter", script); This idea can be applied to the objects property, as well as the objects property. In both cases, similar code to that shown in the example above can be used in the methods. For objects, you may additionally consider changing the text or font style through its properties. For example, the following code adds the word and changes the font style to bold: myBookmark.name += " - VISITED"); myBookmark.style = 2; ABLE Button Appearance Type Keyword Modifying the User Interface Adding Navigation to PDF Documents 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 ap propriate 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 objects property, as well as the objects 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 triggere d when the application is first started: app.fullscreen = true; Defining an Initial View The objects property allows you to specify page layout by assigning one of the following values: To set up the dimensions of the various view windows, assign a value to one of the following object properties: : the inner application window (e xcludes title bar, border, etc) : the inner document window : the outer application window : the outer document window : the page view window for the document content objects property. For example, this.zoom = 125; Acrobat JavaScript Scripting Guide Modifying the User Interface Adding Navigation to PDF Documents Table , to the objects property: this.zoomType = zoomtype.fitW; To specify the page to which the objects property. If the following code is included in the script used in the document event, the document automatically opens to page 30: this.pageNum = 30; Finally, you may choose whether menu items and toolbar buttons will be visible by invoking the following methods of the object: : removes a specific menu item : 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: ABLE ZoomType Settings Zoom Type Property Value Modifying the User Interface Adding Navigation to PDF Documents Acrobat JavaScript Scripting Guide Adding Page Transitions You may use Acrobat JavaScript to customize how page tran sitions occur for any pages within a document. This is accomplished through the objects and The : the zero-based index of the beginning page : the zero-based index of the last page : a page transition array containing three values: : the time a page is displayed before automatically changing : the name of the transition to be applied : the duration in seconds of the transition effect The name of the transition to be applied ca n be chosen from a comprehensive list made available through the objects property. To obtain the list, type the following code into the Console console.println("[" + app.fs.transitions + "]"); objects property. 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: this.setPageTransitions({ nStart: 2, nEnd: 5, aTrans: { nDuration: 10, cTransition: "WipeLeft", nTransDuration: 1 }); // Set the viewing mode to full screen app.fullScreen = true; Acrobat JavaScript Scripting Guide Modifying the User Interface Adding Navigation to PDF Documents Numbering Pages You may use Acrobat JavaScript to cust omize 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 objects and methods can be used to control and customize the appearan ce of numbering schemes within a PDF document. The The is the zero-based index for the page to be labeled, and is an array of three values representing the numbering scheme. If is not supplied, the method removes page numbering for the specified page and any others up to the next specified label. The array contains three required values: : the style of page numbering as shown below in Table : the string used to prefix the numeric portion of the page label : the ordinal with which to start numbering the pages ABLE Page Numbering Style Values cStyle value Description Decimal numbering Upper case Roman numbering Lower case Roman numbering Upper case alphabetic numbering Modifying the User Interface Adding Navigation to PDF Documents Acrobat JavaScript Scripting Guide For example, the code shown below labels 10 pages within a document using the following 5, Appendix-A, Appendix-B // Pages 0-2 will have lower case roman numerals i, ii, iii: this.setPageLabels(0, ["r", "", 1]); // Pages 3-7 will have decimal numbering 1-5: this.setPageLabels(3, ["D", "", 1]); // Pages 8-9 will have alphabetic numbering: this.setPageLabels(8, ["A", "Appendix-", 1]); // The page labels will be printed to the console: var labels = this.getPageLabel(0); for (var i=1; ithis.numPages; i++) console.println(labels); It is also possible to remove a page label by omitting the // The labels for pages 3-7 will be removed: this.setPageLabels(3); Creating Buttons Though buttons are normally considered form fields, you can add them to any document. A and events or other types of control mechanisms to manage the usage of the button fields For example, the following code shows one icon when the mouse enters the button field, and a different icon when the mouse exits: script = "var f = this.getField( myButton );"; Acrobat JavaScript Scripting Guide Modifying the User Interface Working with PDF Layers 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, naviga tion, 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 comb ine PDF layered documents. PDF layers are supported through the usage of Acrobat JavaScript Optional Content Group (OCG) objects. To obtain an array of the objects for a given page in the document, invoke the objects method. The following code obtains the array of OCG objects contained on page 3 of the document: var ocgArray = this.getOCGs(3); Navigating with Layers Since information can be stored in different layers of a PDF document, navigational controls can be customized within different layers, wh objects and methods. In the following example, the display order of all the layers is reversed: var ocgOrder = this.getOCGOrder(); var newOrder = new Array(); for (var i=0; iocgOrder.length; i++) newOrder[i] = ocgOrder[ocgOrder.length - i - 1]; this.setOCGOrder(newOrder); Modifying the User Interface Working with PDF Layers Acrobat JavaScript Scripting Guide Editing the Properties of PDF Layers The Table 10.15 The property can be used to set the default state for an optional content group. In the following example, by default: myLayer.initState = true; The property, which is an array of values, ca n be used to define the intent of a particular optional content group. There are two possible values used in the array: layer is created for informationa l purposes only affect the visibility of content. Its purpose is to represent a document designers structural organization of artwork. The layer is intended for interactive use by document consumers. If is used, the visibility of the layer is affected. In the following example, the intent of all the for (var i=0; iocgs.length; i++) ocgs[i].intent = ["View", "Design"]; The is locked, meaning that it cannot be toggled through the user interface: myLayer.locked = true; The property represents the current on/off state for a given OCG. In the following example, all the OCGs are turned on: for (var i=0; iocgs.length; i++) ocgs[i].state = true; ABLE OCG Properties Property Description object is on or off by default The intent of the object (View or Design) The text string seen in the user interface for the object The current on/off state of the object Acrobat JavaScript Scripting Guide Modifying the User Interface Working with PDF Layers The property represents the text string seen in the user interface that is used to identify layers. In the following example, the OCG is toggled: for (var i=0; iocgs.length; i++) if (ocgs[i].name == "Watermark") ocgs[i].state = !ocgs[i].state; Merging Layers You can use Acrobat JavaScript to merge laye rs in a PDF document. A merged layer (the is merged into sourceLayer.state = targetLayer.state; Flattening PDF Layers Flattening layers means that they will be cons olidated. 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 nece ssary 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, source1.pdf source2.pdf are combined into . It is assumed that there are Modifying the User Interface Working with PDF Layers Acrobat JavaScript Scripting Guide // Open the source documents: var source1 = app.openDoc("/C/source1.pdf"); var source2 = app.openDoc("/C/source2.pdf"); // Obtain the OCG order array for each source document: var mergedOCGArray = new Array(); for (var i=0; isource1OCGArray.length; i++) mergedOCGArray[i] = source1OCGArray[i]; var offset = source1OCGArray.length; for (var j=0; jsource2OCGArray.length; j++) mergedOCGArray[offset + j] = source2OCGArray[j]; var target = app.newDoc("/C/target.pdf"); // Insert source1.pdf: nPage : -1, cPath : "/c/source1.pdf", }); // Insert source2.pdf: cPath : "/c/source2.pdf", }); // Save the target document: "/c/target.pdf"); }); Acrobat JavaScript Scripting Guide Search and Index Essentials 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 objects. You will learn how to use these obje cts 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. Contents Topics Searching for Text in PDF Documents Indexing Multiple PDF Documents Searching Metadata Search and Index Essentials Searching for Text in PDF Documents Acrobat JavaScript Scripting Guide Introduction Acrobat JavaScript provides a static object, which provides powerful searching capabilities that may be applied to PDF documents and indexes. Its properties and Table Table ABLE Search Properties Property Description Searches PDF attachments along with base document Determines if searching is possible Searches document metadata information Searches document text Searches document XMP metadata Searches document bookmarks Ignores accents and diactrics in search Matches Kana characters in query Obtains all accessible objects Searches EXIF data in associated JPEG images Searches annotations Maximum number of documents returned Uses proximity in results ranking for AND Range of proximity search in number of words Uses previous results in query Uses word stemming in searches Acrobat JavaScript Scripting Guide Search and Index Essentials Searching for Text in PDF Documents Finding Words in an PDF Document The objects : the text for which to search : where to search for the text: : search within the active document : search within a specified folder : search within a specified index : path to folder or index used in search Performing a Simple Search of a Document The simplest type of search is applied to th e text within the PDF document. For example, the following code performs a case-insensitive search for the word within the current document: search.query("Acrobat"); Using Advanced Search Options objects properties to use advanced searching options, which can be used to determine how to match search strings, and whether to use proximity or stemming. objects property to one of the following values: Determines how words will be matched (phrase, all words, any words, boolean query) ABLE Search Methods Description Adds an index to the list of searchable indexes Searches the index list according to a specified path Searches the document or index for specified text Removes an index from the list of searchable indexes ABLE 11.1Search Properties PropertyDescription Search and Index Essentials Searching for Text in PDF Documents Acrobat JavaScript Scripting Guide : match the exact phrase : match all the words without regard to the order in which they appear : match any of the words in the search string : perform a boolean query for multiple-document searches (the default) For example, the following code matches the phrases search.wordMatching = "MatchAllWords"; search.query("My Search"); objects property to property to . In the example below, all instances of the words that are not separated by more than 900 words will be listed in the search: search.wordMatching = "MatchAllWords"; search.proximity = true; search.query("My Search"); To use stemming in the search, set the objects property to . For example, the following search lists words th at begin with "run", such as "running" search.stem = true; search.query("run"); Acrobat JavaScript Scripting Guide Search and Index Essentials Searching for Text in PDF Documents Searching Across Multiple PDF Documents Searching all PDF Files in a Specific Location objects . In the following example, all documents in /C/MyFolder will be searched for the word "Acrobat": search.query("Acrobat", "Folder", "/C/MyFolder"); 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 To specify that a search should be case sensitive, set the objects property to . For example, the following code matches "Acrobat" but not "acrobat": search.matchCase = true; search.query("Acrobat", "Folder", "/C/MyFolder"); objects property to . For example, the following code matches "stick", but not "tick" or "sticky": search.matchWholeWord = true; search.query("stick", "Folder", "/C/MyFolder"); To set the maximum number of documents to objects property to the desired number (the default is 100). For example, the following code limits the nu mber of documents to be searched to 5: search.maxDocs = 5; objects property to , as shown in the following code: search.refine = true; Search and Index Essentials Searching for Text in PDF Documents 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 ea ch of the corresponding individual PDF files. objects method to . In the following example, is searched for the word "Acrobat": search.query("Acrobat", "Index", "/C/MyIndex.pdx"); Using Boolean Queries in Multiple Document Searches Boolean queries may be applied to mult iple PDF documents using the following operations: (exclusive or) For example, the phrase used in a search would return all documents containing both the words and The phrase used in a search would return all documents containing one or both of the words The phrase used in a search would return all documents containing exactly one (not both) of the words and The phrase used in a search would return all documents containing that do not contain the word In addition, parentheses may be used. For example, the phrase would be equivalent to performing tw o searches: one using the statement , followed by another using the statement To specify that a boolean query wi ll be used, be sure that the objects property is set to (which is the default). Acrobat JavaScript Scripting Guide Search and Index Essentials Indexing Multiple PDF Documents It is possible to extend and customize in dexes for multiple PDF documents using the Acrobat JavaScript objects. These objects may be used to build, retrieve, or remove indexes. The object represents a generated index, contains a method that is used to crea te an index (and returns a object containing information about the index), and has the properties shown below in Table The object may be used to manage indexi ng jobs and retrieve indexes. It method for retrieving an index, a method for removing a pending indexing job, and properties co ntaining information about indexing jobs. Creating, Updating, or Rebuilding Indexes objects property, which contains an array of property. In the code below, the names and paths of all available selected indexes are pr inted to the console: var arr = search.indexes; for (var i=0; iarr.length; i++) if (arr[i].selected) var str = "Index[" + i + "] = " + arr[i].name; str += "\nPath = " + arr[i].path; console.println(str); ABLE Index Properties Property Description The name of the index The device-independent path of the index Search and Index Essentials Indexing Multiple PDF Documents Acrobat JavaScript Scripting Guide To build an index, first invoke the objects method to retrieve the object. Then invoke the objects method, which returns a object. The : an Acrobat JavaScript expression executed once the build operation is complete Finally, the returned object contains three properties providing useful information about the indexing job: : the device-independent path of the index : the type of indexing operation ( : the status of the indexing operation ( In the code shown below, the index var idx = catalog.getIndex("/C/myIndex.pdx"); // Build the Index var job = idx.build("app.alert(Index build);", true); // Confirm the path of the rebuilt index: console.println("Path of rebuilt index: " + job.path); // Confirm that the index was rebuilt: console.println("Type of operation: " + job.type); // Report the job status console.println("Status: " + job.status); Acrobat JavaScript Scripting Guide Search and Index Essentials Using Acrobat JavaScript to 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. objects property to , as shown in the following code: search.docXMP = true; Search and Index Essentials Searching Metadata Acrobat JavaScript Scripting Guide Acrobat JavaScript Scripting Guide Security This chapter will introduce you to the variou s security options available through Acrobat JavaScript. You will understand how to custom ize security in PDF documents by applying passwords and digital signatures, certifying docu ments, encrypting files, adding security to attachments, managing digital IDs and certif icates, and customizing security policies. Chapter Goals At the end of this chapter, you will be able to: Understand the Acrobat JavaScript secu rity model supporting PDF documents. Use Acrobat JavaScript to add, remove, and validate digital signatures in a PDF 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 Security Security Essentials Acrobat JavaScript Scripting Guide Acrobat JavaScript provides a number of obje cts that support security. These are managed by the , and objects for managing certificates, security policies, and signatures. The , and objects are used to manage digital signatures and access the user certificates. The general procedures for applying various types of security to a PDF document are 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 objects Certifying Documents The author signature for a document is what To apply an author signature to a document, create an author signature field using the objects objects object containing an property value other than , and a legal attest explaining why cert ain legal warnings ar e embedded in the object has properties common to all security handlers. These properties are described below in Table ABLE SignatureInfo Properties Property Description Software build and version for the signature Date and time of the signature Security handler name specified in the Filter attribute in the signature dictionary Security handler name specified by Security handler name specified by Acrobat JavaScript Scripting Guide Security Security Essentials Encrypting Files Using Certificates When you invoke the objects method, it encrypts the document using the public key certificates of each recipient. The groups of recipients are specified in the objects, each of which contains two properties: . The property is an array of objects (described below in Table ), each of which describes a user and their associated certif icates, and is returned by a call to the objects objects (described below in Table each of which contains read-only access to th e properties of an X.509 public key certificate. To obtain a group of recipients (the objects Physical location or hostname Name of the user Number of fields altered since the previous signature Number of fields filled in since the previous signature Number of pages altered since the previous signature The number of revisions in the document Reason for signing Signature revision Validity status ( String representation of signature status Formats used for public key signatures Security handler used to validate signature Handler specified by ABLE 12.1SignatureInfo Properties PropertyDescription Security Security Essentials Acrobat JavaScript Scripting Guide ABLE UserEntity Object Properties Property Description the first name of the user the last name of the user the full name of the user array of objects for the user the preferred ABLE Certificate Object Properties Property Description the raw bytes of the certificate the distinguished name of the user the value of the certificate key usage extension the MD5 digest of the certificate the SHA1 digest of the certificate a unique identifier for the certificate the common name of the signer the distinguished name of the signer purposes: end-user signing or encryption an application object Acrobat JavaScript Scripting Guide Security Digitally Signing PDF Documents Security Policies Security policies are common specifications that include the type of encryption, the objects, which may be accessed and managed by the objects objects methods. Secure Forms You can lock form fields by creating a script containing a call to the fields method, and passing that script as the second parameter to the fields method. In addition, you may sign an embedded FDF data object by invoking its method. A digital signature contains identifying information about the person signing the document. When applying an au thor 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. To sign a document, create a signature field, choose a security handler, and invoke the fields method, which accepts the following parameters: : the security handler object : a object : the device-independent path to which the file will subsequently be saved : a string explaining legal warnings (for author signatures only) The creation and usage of these parameters ar e explained below in the following sections: The Security Handler Object The SignatureInfo Object Applying the Signature Security Digitally Signing PDF Documents Acrobat JavaScript Scripting Guide The Security Handler Object To obtain a security handler (the objects : the name of the security handler (contained in the objects property) : the existing engine associated with the Acrobat user interface engine associated with the Acrobat user interface: // Validate signatures when the document is opened: security.validateSignaturesOnOpen = true; // List all the available signature handlers for (var i=0; isecurity.handlers.length; i++) console.println(security.handlers[i]); // Select the Adobe.PPKLite engine with Acrobat user interface: var ppklite = security.getHandler("Adobe.PPKLite", true); After obtaining the security handler, invoke the objects var oParams = { password: "myPassword", cDIPath: "/C/signatures/myName.pfx" // digital signature profile ppklite.login(oParams); The SignatureInfo Object To create the method, create a generic object containing the pr operties as described above in Table its usage when creating an author signature is given below: var myInfo = { password: "myPassword", location: "San Jose, CA", reason: "I am approving this document", contactInfo: "userName@adobe.com", appearance: "Fancy", mdp: "allowNone" // an mdp value is needed for author signatures Acrobat JavaScript Scripting Guide Security Digitally Signing PDF Documents Applying the Signature Now that the security handler and signatur e information have been created, you may invoke the signature fields method, as shown in the code below: // Obtain the signature field object: // Sign the field: f.signatureSign( oSig: ppklite, oInfo: myInfo, cDIPath: "/C/mySignedFile.pdf", bUI: true, cLegalAttest: "Fonts are not embedded to reduce file size" ); //end of signature Creating a New Signature Appearance You may create a new signature appearance th rough the Acrobat user interface, access signature appearances through the property of the object, and use the signature fields object used to control signature properties. properties is called , which is an array of acceptable formats to use for the signature. In the following example, the signing handler is set to and the format is set to filter: "Adobe.PPKMS", subFilter: ["adbe.pksc7.sha1"], flags: 0x03 }); Clearing a Digital Signature from a Signature Field To clear a signature, invoke the objects method. In the example below, is cleared: this.resetForm(f); Security Digitally Signing PDF Documents Acrobat JavaScript Scripting Guide You may maintain a list of trusted user identiti es 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 objects method, which returns a object, as shown in the example below: // Open the FDF file sent to you by the other user: var fdf = app.openFDF("/C/myDoc.fdf"); // Obtain the security handler: // Check to see if the FDF has been signed: if (fdf.isSigned) // Obtain the other users signature info: sigInfo = fdf.signatureValidate({ oSig: engine, bUI: true }); // Display the signature status and description: console.println("Signature Status: " + sigInfo.status); console.println("Description: " + sigInfo.statusText); else console.println("This FDF was not signed."); Removing Signatures To remove a signature field, invoke the objects method. In the example below, is removed: this.removeField(f); Certifying a Document When applying an author signat ure to certify a document, check , which is a read-only property of the object. If its value is , the signer is trusted for certifying documents. Acrobat JavaScript Scripting Guide Security Digitally Signing PDF Documents Validating Signatures To validate a signature, invoke the signature fields : not a signature field : signature is blank : unknown status : signature is invalid : signature is valid, identity of signer could not be verified : signature and identity of signer are both valid : the security handler used to validate the signature (a or object) object contains two properties: : the security handler object In the following example, is analyzed for validity: // Obtain the signature field: // Validate the signature field: var status = f.signatureValidate(); // Obtain the signature information var sigInfo = f.signatureInfo(); // Check the status returned from the validation: if (status 3) var msg = "Signature is not valid: " + sigInfo.statusText; else var msg = "Signature is valid: " + sigInfo.statusText; // Display the status message: app.alert(msg);; Using Approval Stamps You may apply a stamp annotation to a docu property to either , as shown in the example below: Security Adding Security to PDF Documents Acrobat JavaScript Scripting Guide var annot = this.addAnnot({ page: 0, type: "Stamp", author: "A.C. Robat", rect: [400, 400, 550, 500], contents: "This is good." AP: "Approved" }); When applying digital signatures, you may sp ecify the appearance and the default signing objects property 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 method. At this point you can customize the behavior based on the information found within the object. The following example illustrates how to access the signature information: // Obtain the signature field: // Validate the signature field: var status = f.signatureValidate(); // Obtain the signature information var sigInfo = f.signatureInfo(); console.println("Name: " + sigInfo.name); console.println("Reason: " + sigInfo.reason); console.println("Date: " + sigInfo.date); console.println("Contact Info: " + sigInfo.contactInfo); Adding Security to PDF Documents Adding Passwords and Se tting Security Options 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 Acrobat JavaScript Scripting Guide Security Adding Security to PDF Documents application of an author signature accompan ied 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 pe Rights-Enabled PDF Files Encrypting PDF Files fo r a List of Recipients As you have seen throughout this chapter, the objects , which is a repository of user information. The object contains property with which it is possible to cr eate and activate a new directory, and is accessible either through the property or the object. The object is a object, 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 object, obtain a object and invoke its object to the new directorys property. An example of this is given below: // Create and activate a new directory: var newDirInfo = { dirStdEntryID: "dir0", dirStdEntryName: "Employee LDAP Directory", dirStdEntryPrefDirHandlerID: "Adobe.PPKMS.ADSI", dirStdEntryDirType: "LDAP", server: "ldap0.acme.com", port: 389 // Obtain the security handler: var sh = security.getHandler("Adobe.PPKMS"); // Create the new directory object: var newDir = sh.newDirectory(); // Store the directory information in the new directory: newDir.info = newDirInfo; Security Adding Security to PDF Documents Acrobat JavaScript Scripting Guide In order to obtain certificates from a directory, you must first connect to it using the objects method, which returns a object. An example is given below: // Obtain the security handler: var sh = security.getHandler("Adobe.PPKMS"); var dc = sh.directories[0].connect(); It is then poss ible to use the object to search for certificates. You can specify the list of attributes to be used for the search by invoking the objects : an array of attributes to be used in the search : whether the attributes are st andard output attribute names For example, the following code spec ifies standard output attributes ( and To perform the search, invoke the objects method, which accepts the following parameters: : an array of key-value pairs consisting of search attribute names and their corresponding strings : the name of the group to which to restrict the search contains standard attribute names In the following example, the directory is sear ched for certificates for the user whose last name is "Smith", and displays the users email address: Acrobat JavaScript Scripting Guide Security Adding Security to PDF Documents 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 object that contains the following properties: : a machine-readable policy id string : the policy name : the policy description : the date when the policy was last modified : the handler that implements the policy ( : the target data covered by the policy ( To obtain a list of the security poli cies currently available, invoke the objects method, which accepts two parameters: The object is a generic object used to filter the list of security policies that will be returned by the me thod, and contains the following properties: : returns policies using the specified filter ( : returns policies using the specified Security Adding Security to PDF Documents Acrobat JavaScript Scripting Guide The following example illustrates how to request and display a list of favorite security var options = { bFavorites: true, cFilter: "Adobe.PubSec" // Obtain the filtered list of security policies: // Display the list of security policies by name: for (var i=0; ipolicyArray.length; i++) console.println(policyArray[i].name); To encrypt a PDF file using a security policy, you must first choose a security policy by invoking the objects method, and then encrypt the file by invoking either the objects or method. The objects method opens a dialog that permits the user to choose from a list of security policies, filtered according to a object. The objects method accepts three parameters: : the policy id to use when encrypting the document object containing a list of recipients Acrobat JavaScript Scripting Guide Security Adding Security to PDF Documents In the following example, a newly created document is encrypted for a list of recipients, // Create the new document var myDoc = app.newDoc(); var options = { bCheckOnline: true, cFilter: "Adobe.APS" // Choose the security policy: var policy = security.chooseSecurityPolicy(options); // Choose the list of recipients var recipients = { userEntities: [ {email: "user1@adobe.com"}, {email: "user2@adobe.com"}, {email: "user3@adobe.com"} // Encrypt the document using the security policy: var policyID = myDoc.encryptUsingPolicy({ cPolicyId: "adobe_secure_for_recipients", oRecipients: [recipients] }); // Display the policy ID: console.println("Policy ID = " + policyID); Security Adding Security to PDF Documents Acrobat JavaScript Scripting Guide The objects : the policy ID to use when encrypting the document : the handler to use wh en applying the policy : an array of email addresses for the in tended recipients (used only if the template policy ID is In the following example, a newly created document is encrypted using the template policy: // Obtain the APS security handler: // Access the digital ID: aps.login({ oParams: { cURI: "http://adobe.com/guardian", cUserId: "test", cPassword: "test" }); // Specify the recipients: var recipients = [ "user1@adobe.com", "user2@adobe.com", "user3@adobe.com" // Create the new document var myDoc = app.newDoc(); // Encrypt the document: myDoc.encryptForAPS({ cPolicyId: "adobe_secure_for_recipients", aRecipients: recipients, oHandler: aps, bUI: false }); Acrobat JavaScript Scripting Guide Security Adding Security to PDF Documents Adding Security to Document Attachments You may add security to a document by encryp ting its attachments and enclosing them in eEnvelope . To do this with Acrobat JavaScript, invoke the objects : the name of the encryption filter : an array of objects representing the intended recipients Thus, an eEnvelope is a PDF file that conta ins encrypted attachment s. The name of the crypt filter, which represents the recipient li when importing the attachment. An example is given below: // Create instructions to be used in the recipient dialog: var note = "Select the recipients. Each must have "; note += "an email address and a certificate."; // Specify the remaining options used in the recipient dialog: var options = { bAllowPermGroups: false, cNote: note, bRequireEmail: true // Obtain the intended recipient Group objects: var groupArray = security.chooseRecipientsDialog(options); // Open the eEnvelope document: var env = app.openDoc("/C/myeEnvelope.pdf"); env.addRecipientListCryptFilter("myFilter", groupArray); // Attach the current document to the eEnvelope: env.importDataObject("secureMail0", this.path, "myFilter"); // Save the eEnvelope: env.saveAs("/C/outmail.pdf"); Security Acrobat JavaScript Scripting Guide It is possible to customize and extend th e 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 info rmation contained within certificates. As you learned earlier, a digital ID is represented with a object, 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 ABLE SignatureInfo Public Key Security Handler Properties Property Description User-configured appearance name Chain of certificates from signer to certificate authority User-specified contact information for determining trust Bytes covered by this signature Validity status of the document byte range digest Validity of the identity of the signer Numerical validity of the identity of the signeN Validity status of the object digest What the signer is trusted for Password used to access private key for signing Acrobat JavaScript Scripting Guide Security About Digital ID Providers A digital ID provider is a trusted 3rd party, often called a certificate authority or signature , that verifies the identity, issues the priv ate key, and protects the public key. The property of the object 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 de tails of the certificate issued by the digital ID provider, such as its property. For example, the following code encrypts the current document for everyone in the address book. It does this by creating a collec tion 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 certif icates, or certificates otherwise unsuitable for encryption: // Obtain the security handler: // Connect to the directory containing the certificates: var dc = eng.directories[0].connect(); // Obtain the list of all recipients in the directory: var rcp = dc.search(); // Create the filtered recipient list: var fRcp = new Array(); // Populate the filtered recipient list: for (var i=0; ircp.length; i++) { if (rcp[i].defaultEncryptCert && rcp[i].defaultEncryptCert.usage.endUserEncryption) fRcp[fRcp.length] = rcp[i]; if (rcp[i].certificates) { for (var j=0; jrcpp[i].certificates.length; j++) if (rcp[i].certificates[j].usage.endUserEncryption) fRcp[fRcp.length] = rcp[i]; // Now encrypt for the filtered recipient list: this.encryptForRecipients({[userEntities: fRcp]}); Security 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 objects method, which supports enrollment with the security handlers by creating a new self-sign credential, and prevents the : the password needed to access the digital ID file : the location of the digital ID file relative distinguished name (represented as an object) containing the issuer or subject name for the certificate : the certificate policy information, wh ich is a generic object containing the following properties: : the certificate policy object identifier : URL pointing to detail ed policy information The relative distinguished name is a generic object containing the properties shown below Table 12.5 ABLE RDN Object Property Description Country or region Common name Organization name Email address Acrobat JavaScript Scripting Guide Security An example is given below: // Obtain the security handler: var ppklite = security.getHandler("Adobe.PPKLite"); // Create the relative distinguished name: var newRDN = { cn: "newUser", c: "US" // Create the certificate policy information: var newCPS = { oid: "1.2.3.4.5", url: "http://newca.com/newCPS.html", notice: "This is a self-generated certificate" // Create the new users certificate: security.newUser({ cPassword: "newUserPassword", cDIPath: "/C/newUser.pfx", oRDN: newRDN, oCPS: newCPS, bUI: false }); The object has a property that contains the certificates associated with the currently selected digital IDs for the security handler. The property is a generic object containing the following properties: : the certificate used when signing : the certificate used when encrypting : an array of certificates corr esponding to all the digital IDs : an array of strings (one for every object) indicating where the digital IDs are stored You may use the objects // Obtain the security handler: var sh = security.getHandler("Adobe.PPKMS"); // Obtain the certificates: var ids = sh.DigitalIDs; // Write the signing certificate to disk: security.exportToFile(ids.oEndUserSignCert, "/C/mySignCert.cer"); Security 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 field and create the relative distinguished name using the information it contains, as shown in the following example: // Obtain the security handler: var ppklite = security.getHandler("Adobe.PPKLite"); // Obtain the signature field: // Validate the signature: f.signatureValidate(); // Obtain the signature information: var sigInfo = f.signatureInfo(); // Obtain the certificates and distinguished name information var certs = sigInfo.certificates; var rdn = certs[0].subjectDN; // Now create the digital signature: ppklite.newUser({ cPassword: "newUserPassword", cDIPath: "/C/newUser.pfx", oRDN: rdn, }); Acrobat JavaScript Scripting Guide Security Managing Digital IDs (Windows Certificate Security) object is a repository of user inform ation, including public key certificates. On Windows, the security handler provides access, through the Microsoft Active Directory Script Interface ), to the directories created by the user. These are created sequentially with the names directory handler includes the directory information object properties shown below in Table For example, the following code displays information for an existing directory: // Obtain the security handler: // Obtain the directory information object: var info = ppkms.directories[0].info; // Display some of the directory information: console.println("Directory: " + info.dirStdEntryName); console.println("Address: " + info.server + ":" + info.port); ABLE Adobe.PPKMS.ADSI Directory Handler Object Properties Property Description The server hosting the data The port number (standard LDAP port is 389) Used to narrow the search to a section of the directory Maximum number of entries retrieved from search Maximum time allowed for search Security Acrobat JavaScript Scripting Guide Managing Digital ID Certificates Sharing Digital ID Certificates You may share a self-signed digita l ID certificate by exporting it as an FDF file. To do this, sign the FDF file by invoking the objects method, which works similarly to that of the object. Its usage is illustrated in the example below: // Obtain the security handler: // Access the digital ID: eng.login("myPassword", "/C/myID.pfx"); // Open the FDF: var myFDF = app.openFDF("/C/myFDF.fdf"); // Sign the FDF: if (!myFDF.isSigned) { // Sign the FDF myFDF.signatureSign({ oSig: eng, nUI: 1, cUISignTitle: "Sign Embedded File FDF", cUISelectMsg: "Please select a digital ID" }); // Save the FDF myFDF.save("/C/myFDF.fdf"); Building a List of Trusted Identities The trust level associated with a digital ID is stored in the property defined in the objects 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 property has a value of ). The following bit assignments are described below: : trusted for signatures : trusted for certifying documents : trusted for dynamic content such as multimedia : Adobe internal use : the JavaScript in the PDF file is trusted to operate outside the normal PDF restrictions Acrobat JavaScript Scripting Guide Security Checking Information on Certificates As you learned earlier, you may obtain a certificates through the property of a object, which is returned by a call to the signature fields Table and the relative distinguished name properties are defined in Table In the following example, the signers common name, the certificates serial number, and the distinguished name in formation are displayed: // Obtain the signature field: // Validate the signature field: var status = f.signatureValidate(); // Obtain the signature information var sigInfo = f.signatureInfo(); // Obtain the certificate: var cert = sigInfo.certificates[0]; console.println("signers common name: " + cert.subjectCN); console.println("serial number: " + cert.serialNumber); // Distinguished name information: console.println("distinguished common name: " + cert.subjectDN.cn); console.println("distinguished organization: " + cert.subjectDN.o); Security Acrobat JavaScript Scripting Guide Tokenized Acrobat JavaScript Security Model In order to maintain security for cases in whic h Acrobat JavaScript connects to data sources external to the current document without us er 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 to ken, which is matched against the resource. The methods and properties shown below in Table use this token-based security ABLE Description Send Send when Send when May mark doc with data sources May mark doc with data sources Acrobat JavaScript Scripting Guide Rights-Enabled PDF Files 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 partic ular document, thereby enabling the user to save, fill in, annotate, sign, certify, auth enticate, 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 do cuments 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 Acrobat JavaScript Scripting Guide Additional Usage Rights Form: fill-in and document full-save Form: import and export 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 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 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 tran sfer via SOAP, thus ensuring seamless integration with business logi c and advanced data transport capabilities available within enterprise applications. Acrobat JavaScript Scripting Guide Rights-Enabled PDF Files Writing Acrobat JavaScript for Reader 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. OTE For rights-enabled documents, certain edit ing features normally available within the Acrobat Standard and Professional prod ucts will be disabled. This will ensure that the user does not inadvertantly inva lidate 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 will be disabled by LiveCycle Reader Extensions: ABLE Features Disabled by Livecycle Reader Extensions Features modify page content add or modify JavaScripts Rights-Enabled PDF Files Writing Acrobat JavaScript for Reader Acrobat JavaScript Scripting Guide In Acrobat Standard and Professional, the follo wing controls will be disabled for rights- enabled documents: Menu items under Adva nced JavaScript that allow the addition or modification of JavaScripts (except for the Menu items under Advanced Forms 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 Table 13.2 ABLE Controls Affected by Livecycle Reade r Extensions in Acrobat Standard and Menu Operation Equivalent JavaScript Method Fi le Reduce File Size Document Pa ges Insert Document Pa ges Replace Document Pa ges Crop Document Pa ges Rotate Document Pa ges Set Page Transitions (read-only), Document Pa ges Number Pages Document Add Watermark & Background Edit Add Bookmark Acrobat JavaScript Scripting Guide Rights-Enabled PDF Files Writing Acrobat JavaScript for Reader When you invoke the objects method, the objects, each of which contains a property. The property is an object containing the properties described below in Table The following code allows full and unrestricted access to the entire document for one set of ), and allows high quality prin // Obtain the security handler: var sh = security.getHandler("Adobe.PPKMS"); // Connect to the directory containing the user certificates: var dir = sh.directories[0]; var dc = dir.connect(); // Search the directory for certificates: var importantUsers = dc.search({oParams:{lastName:"Smith"}}); var otherUsers = dc.search({oParams:{lastName:"Jones"}}); // Allow important users full, unrestricted access: var importantGroup = { oCerts: importantUsers, oPermissions: {allowAll: true} // Allow other users high quality printing: var otherGroup = { oCerts: otherUsers, oPermissions: {allowPrinting: "highQuality"} ABLE Permissions Object Property Description Full, unrestricted access Content access for the visually impaired content copying and extraction Allowed changes ( Printing security level ( Rights-Enabled PDF Files Writing Acrobat JavaScript for Reader Acrobat JavaScript Scripting Guide // Encrypt the document for the intended recipients: this.encryptForRecipients({ oGroups:[importantGroup, otherGroup], }); If a document is rights-enabled but commenting is not allowed, then the JavaScript Table will be disabled: If a document is rights-enabled but file attachments are not allowed, then the following If a document is rights-enabled but digital signatures are not allowed, then the following (for signature fields) (when ABLE When Commenting is Not Allowe d in Reader-Enabled Documents Feature Add a comment Import comments Export comments Acrobat JavaScript Scripting Guide Rights-Enabled PDF Files Enabling Collaboration By using Really Simple Syndication (RSS), co llaboration servers ca n provide customized XML-based user interfaces directly inside of Acrobat itself, thus providing a more dynamic and personalized tool, and providing Jav aScript 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 disc overy 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 Re ader to participate in the review process. The following JavaScript methods will be enabled in Adobe Reader when collaboration is Rights-Enabled PDF Files Enabling Collaboration Acrobat JavaScript Scripting Guide Acrobat JavaScript Scripting Guide Rights-Enabled PDF Files Enabling Collaboration Rights-Enabled PDF Files Enabling Collaboration Acrobat JavaScript Scripting Guide Acrobat JavaScript Scripting Guide Interacting with Databases 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 object, which provides an interface to the ODBC connection. The object interacts with other objects to facilitate database connectivity and interaction: . 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 Acrobat JavaScript Scripting Guide 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 n Thus, a necessary requirement to the usage of ADBC is that ODBC must be installed on a client machine running a Microsoft Windows oper ating 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 object thus provides methods through which you can obtain a list of accessible database . In addition, the object provides a number of properties corres ponding 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 establ ish an ADBC connection. First, obtain a list of accessible databases by invoking the objects method. Then establish the connection by passing th e Data Source Name (DSN) of one of the databases in the list to the objects method. The generic objects, each of which contai ns the following properties: : a string identifying the database : a description containing specific information about the database In the following example, a list of all availa ble databases is retrieved, and the DSN of the object representing is identified and stored in variable Acrobat JavaScript Scripting Guide Interacting with Databases Establishing an ADBC Connection // Obtain a list of accessible databases: // Search the DataSourceInfo objects for the Q32000Data database: if (databaseList != null) { var DB = ""; for (var i=0; idatabaseList.length; i++) if (databaseList[i].name == "Q32000Data") { DB = databaseList[i].name; break; To establish the database connection, invoke the objects : the Data Source Name (DSN) of the database : the user ID : the password The object, which encapsulates the object, obtain information about the list of tables in the data base or columns within a table, and close the connection. In the following example, a conn ection is establ ished with the database: if (DB != "") { // Connect to the database and obtain a Connection object: var myConnection = ADBC.newConnection(DB.name); The ABLE Connection Object Description Closes the database connection Creates a object used to execute SQL statements Interacting with Databases Establishing an ADBC Connection Acrobat JavaScript Scripting Guide The objects generic objects, each of which corresponds to a table within the database and contains the following properties: : the table name : a description of database-depen dent information about the table In the following example, the name and desc ription of every table in the database is printed to the console: // Obtain the array of TableInfo objects representing the database tables: // Print the name and description of each table to the console: for (var i=0; itableArray.length; i++) { console.println("Table Name: " + tableArray[i].name); console.println("Table Description: " + tableArray[i].description); The objects method accepts a parameter containing the name of one of the database tables, and returns an array of generic objects, each of which corresponds to a column wi thin the table and contains the following properties: the name of the column : a description of database-dependent information about the column : a numeric identifier representing an SQL type : a database-dependent string representing the data type database table called is printed to the console: // Obtain the array of ColumnInfo objects representing the Sales table: var columnArray = myConnection.getColumnList("Sales"); // Print a complete description of each column to the console: for (var i=0; icolumnArray.length; i++) { console.println("Column Name: " + columnArray[i].name); console.println("Column Description: " + columnArray[i].description); console.println("Column SQL Type: " + columnArray[i].type); console.println("Column Type Name: " + columnArray[i].typeName); Acrobat JavaScript Scripting Guide Interacting with Databases Executing SQL Statements To execute SQL statements, first create a object by invoking the objects object can be used to access any row or column within the database table and execute SQL commands. In the following example, a object is created for the created in the previous sections: myStatement = myConnection.newStatement(); The object provides the methods shown below in Table In addition to the methods shown above in Table object provides two useful properties: : the number of columns in each row of results returned by a query : the number of rows affected by an update To execute an SQL statement, invoke the objects // Create the SQL statement: var SQLStatement = Select * from \"Client Data\"; // Execute the SQL statement: myStatement.execute(SQLStatement); ABLE Statement Object Description Executes an SQL statement Obtains a column within the table Obtains an array of columns within the table Obtains the current row in the table Iterates to the next row in the table Interacting with Databases Executing SQL Statements Acrobat JavaScript Scripting Guide There are two steps required to obtain a row of data. First, invoke the objects objects generic 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 ca se because there are no spaces in the column names: // Create the SQL statement: var st = Select firstName, lastName, ssn from \"Employee Info\"; // Execute the SQL statement: myStatement.execute(st); // Make the next row (the first row in this case) available: myStatement.nextRow(); // Obtain the information contained in the first row (a Row object): // Display the information retrieved: console.println("First name: " + firstRow.firstName.value); console.println("Last name: " + firstRow.lastName.value); console.println("Social Security Number: " + firstRow.ssn.value); If the column names contain spaces, the syntax can be modified as shown below: // Create the SQL statement: var st = Select \"First Name\", \"Last Name\" from \"Employee Info\"; // Execute the SQL statement: myStatement.execute(st); // Make the next row (the first row in this case) available: myStatement.nextRow(); // Obtain the information contained in the first row (a Row object): // Display the information retrieved: console.println("First name: " + firstRow["First Name"].value); console.println("Last name: " + firstRow["Last Name"].value); Acrobat JavaScript Scripting Guide SOAP and Web Services The basis for most current models of web se rvices is the Extensible Markup Language (XML), which facilitates interoperability by permitting the exch ange of information 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 su pport has made it poss ible to include both SOAP header and body information, send binary data more efficientl y, use document/literal encoding, and facilitate authenticated or encrypted communications. In addition, it also 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. Understand how to apply Acrobats SOAP support to various workflows. SOAP and Web Services Using SOAP and Web Services Acrobat JavaScript Scripting Guide Contents Using SOAP and Web Services Acrobat JavaScript provides a object 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-base d communication with remote servers. The object has a property that sends all XML requests and responses to the JavaScript Console for debugg ing purposes. In addition, the object provides the Table 15.1 Topics Using SOAP and Web Services DNS Service Discovery Managing XML-based Information Workflow Applications ABLE SOAP Object Description Obtains a WSDL proxy object used to invoke a web service Locates network services using DNS Service Discovery Binds a service name to a network address and port Decodes a Base64 or Hex stream object Applies Base64 or Hex encoding to a stream object Converts a string to a stream object Converts a stream object to a string Acrobat JavaScript Scripting Guide SOAP and Web Services Using SOAP and Web Services Using a WSDL Proxy to Invoke a Web Service When connecting to a web service, your Acro bat 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 objects method, which accepts a single parameter containing the HTTP or HTTPS URL of the WSDL document. The returned proxy object contains the In the example shown below, a connection to a web service will be established, and its RPC- contains the address of the // Obtain the WSDL proxy object: var myProxy = SOAP.connect(myURL); var testString = "This is a test string."; var result = myProxy.echoString(testString); // Display the response in the console: console.println("Result is " + result); // Invoke the echoInteger // Since JavaScript does not support XSD-compliant integer values, 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 Acrobat JavaScript Scripting Guide // We will create an integer object compliant with the XSD standard: var myIntegerObject = { soapType: "xsd:int", soapValue: "10" var result = myProxy.echoInteger(myIntegerObject); // Display the response in the console: console.println("Result is " + result); Table ABLE XSD-Compliant Data Types Supported in JavaScript JavaScript Type Equivalent XSD-Compliant Type Acrobat JavaScript Scripting Guide SOAP and Web Services Using SOAP and Web Services Synchronous and Asynchrono us Information Exchange The objects method may be used to establish either synchronous or asynchronous communication wi th 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 ABLE Parameter Description URL for SOAP HTTP endpoint Object containing RPC information SOAPAction header used by firewalls and servers to filter requests Message schema namespace when SOAP encoding is not used SOAP header to be included with request SOAP header to be included with response SOAP protocol version to be used (1.1 or 1.2) Authentication scheme The type and structure of the response information (JS, XML, Message) SOAP and Web Services Using SOAP and Web Services Acrobat JavaScript Scripting Guide Establishing a Synchronous Connection The objects method may be used to establish a synchronous connection , and parameters. The example below demonstrates how to invoke the same web services used in the previous example. method, the parameter contains the URL for the WSDL document. For the purposes of our example, assume that represents the WSDL document location. The : the SOAP type used for the value : the SOAP value used when generating the message : the element name used when generating the SOAP message : an object containing the XML attributes in the request node : the namespace-qualified name of the request node is encoded as an attachment according to the SwA/MTOM specification. In this case, will be a stream. Assume that the namespace is . The following code represents the var echoStringRequest = { inputString: "This is a test." The parameter contains header information described by the WSDL document that is used by firewalls to filter SOAP reques ts. In our example, we will supply the location of the WSDL document: var mySOAPAction = "http://mydomain/methods"; We may now invoke the web method: var response = SOAP.request ({ cURL: myURL, oRequest: echoStringRequest, cAction: mySOAPAction }); Acrobat JavaScript Scripting Guide SOAP and Web Services Using SOAP and Web Services In the case of synchronous requests such as this one, the value returned by the method ( in this example) is an object cont aining 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. OTE In the case of base64 or hex encoding of binary information, the type returned will object. We may now obtain the returned value by usin g syntax that corresponds to the SOAP body sent back by the web method: var result = response[responseString]["return"]; // Display the response in the console: console.println("Result is " + result); Similarly, we can invoke the method. In this case, however, we must supply an XSD- compliant object to represent the integer value: var myIntegerObject = { soapType: "xsd:int", soapValue: "10" var echoIntegerRequest = { inputInteger: myIntegerObject Now we may invoke the var response = SOAP.request ({ cURL: myURL, oRequest: echoIntegerRequest, cAction: mySOAPAction }); var result = response[responseString]["return"]; // Display the response in the console: console.println("Result is " + result); SOAP and Web Services Using SOAP and Web Services Acrobat JavaScript Scripting Guide Asynchronous Web Service Calls The objects method may be used in conjunction with the method to establish asynchronous communication with a web service. In this case, the Asynchronous communication is made po ssible by assigning a value to the methods parameter, which is an object literal that must contain a function called that accepts two parameters: (the result object) and of the requested HTTP endpoint). In the example below, the contains an attribute called , 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 function is to indicating that the asynchronous call has been completed: var mySync = { isDone: false, val: null, result: function(cMethod) this.isDone = false; if (typeof this.val[name] == "undefined") else response: function(oResult, cURI) this.val = oResult; this.isDone = true; wait: function() Acrobat JavaScript Scripting Guide SOAP and Web Services Using SOAP and Web Services // Invoke the web service: SOAP.request({ cURL: myURL, oRequest: echoIntegerRequest, oAsync: mySync, cAction: mySOAPAction }); // The response callback function could contain the following code: // Handle the asynchronous response: var result = mySync.result("echoInteger"); // Display the response in the console: console.println("Result is " + result); Using Document/Literal Encoding You may use document/literal encoding in your SOAP messages by assigning values to the following parameters of the : Assign a value of to this parameter. : Specify a namespace for the message schema. : Assign Once this is done, fill the parameter with an object literal containing the data. An example is given below: var aInt = {soapType: "xsd:int", soapValue: "10"}; var bInt = {soapType: "xsd:int", soapValue: "4"}; var req = {}; req["Add"] = {a: aInt, b: bInt}; // Invoke the web service: var response = SOAP.request({ cURL: myURL, oRequest: req, cAction: mySOAPAction, bEncoded: false, cNamespace: myNamespace, cResponseStyle: SOAPMessageStyle.Message }); // Display the response to the console: var value = response[0].soapValue[0].soapValue; console.println("ADD(10 + 4) = " + value); SOAP and Web Services Using SOAP and Web Services Acrobat JavaScript Scripting Guide Exchanging File Attach ments and Binary Data As you learned earlier, the (SwA) standard or the Message Transmission Optimization Mechanism (MTOM) to send the binary data in a more efficient format. Both SwA and MTOM can SwA can be used by setting the value to , as shown in the example below. Assume is a object containing binary data: // Use the SwA standard: var SwARequest = { dh: soapAttachment: true, soapValue: myStream var response = SOAP.request ({ cURL: myURL, oRequest: SwARequest }); var result = response[responseString]["return"]; Acrobat JavaScript Scripting Guide SOAP and Web Services Using SOAP and Web Services MTOM is used by addi tionally setting the methods parameter to and the object: // Use the MTOM standard: var MTOMRequest = { "echoAttachmentDL": { dh: inclusion: soapAttachment: true, soapValue: myStream var response = SOAP.request({ cURL: myURL, oRequest: MTOMRequest, bEncoded: false, cNamespace: myNamespace }); Converting Between String and ReadStream Information The objects methods are useful for converting between formats. The // Create a ReadStream object from an XML string: var myStream = streamFromString("mom name = 'Mary'm6om; nam;n =; -6';M0a;ry';怀/mo/6mo;m00;m"); // Place the information in an attachment: this.setDataObjectContents("org.xml", myStream); // Convert the ReadStream object back to a string and display in console: console.println(stringFromStream(myStream)); SOAP and Web Services Using SOAP and Web Services 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 foll owing values to the (SOAP Version 1.1) or (SOAP Version 1.2). Its usage is shown in the following example: var response = SOAP.request ({ cURL: myURL, oRequest: myRequest, cVersion: SOAPVersion.version_1_2 }); Accessing SOAP He ader Information You may send SOAP header information to the web service using the methods parameter, and access the return ed header information using the is identical to the object, with the addition of two attributes: : the SOAP actor that should interpret the header Their usage is shown in the following example: var sendHeader = {}; sendHeader[myNamespace + "testSession"] = { soapType: "xsd:string", soapValue: "Header Test String" var responseHeader = {}; responseHeader[myNamespace + "echoHeader"] = {}; // Exchange header information with the web service: var response = SOAP.request({ cURL: myURL, oRequest: {}, cAction: "http://mydomain/methods", oReqHeader: sendHeader, oRespHeader: responseHeader }); Acrobat JavaScript Scripting Guide SOAP and Web Services Using SOAP and Web Services Authentication You may use the The : A string containing the username : A string containing the authentication credential Its usage is shown in the following example: // Create the oAuthenticate object: var myAuthentication = { Username: "myUsername", Password: "myPassword" // Invoke the web service using the username and password: var response = SOAP.request ({ cURL: myURL, oRequest: echoStringRequest, cAction: mySOAPAction oAuthenticate: myAuthentication }); Error Handling The object provides extensive error handling capabilities within its methods. In addition to the standard Acrobat JavaScript exceptions, the object also provides and exceptions. exception is thrown when the SOAP endpoint returns a SOAPFault. The exception object will include informat ion about the SOAP Fault code, the objects and exception is thrown when there is a problem with the underlying HTTP exception object will contain a status code indicating the nature of the problem. The objects , and methods support this exception type. SOAP and Web Services DNS Service Discovery Acrobat JavaScript Scripting Guide Suppose the exact URL for a given service is no t known, but that it is available locally DNS Service Discovery (DNS-SD). You may use the objects and methods to locate the service on the network and bind to it for communications. The objects The : The DNS SRV service name (such as "http" or "ftp") : A notification object used when services are located or removed (implements : the unicode display name of the service : the DNS domain for the service : the DNS SRV service name (identical to : An array of domains for the query. The valid domains are (searches the default DN S domain using unicast Acrobat JavaScript Scripting Guide SOAP and Web Services DNS Service Discovery An example of its usage is shown below: // Create the oAsync notification object: var myNotifications = { addServices: function(services) for (var i=0; iservices.length; i++) { var str = "ADD: "; str += services[i].name; str += " in domain "; str += services[i].domain; console.println(str); removeServices: function(servces) var str = "DEL: "; str += services[i].name; str += " in domain "; str += services[i].domain; console.println(str); // Perform the service discovery: SOAP.requestServices({ cType: "http", oAsync: myNotifications, aDomains: [ServiceDiscovery.local, ServiceDiscover.default] }); Once a service has been discovered, it can be bound through the objects : the DNS SRV service name (such as "http" or "ftp"). : the domain in which the service is located. : the service name to be resolved. : a notification object used when the service is resolved. It implements a ( if successful) and if successful, contains a object). The object contains the following properties: : the IP address or DNS name of the machine providing the service. : the port on the machine. : an object with name/value pairs supplied by the service. SOAP and Web Services Managing XML-based Information Acrobat JavaScript Scripting Guide Its usage is illustrated in the following example: // Create the oAsync notification object: var myNotification = { resolve: function(nStatus, oInfo) // Print the location if the service was bound: if (nStatus == 0){ var str = "RESOLVE: http://"; str += ":"; str += oInfo.port; str += "/"; str += oInfo.info.path; console.println(str); // Display the error code if the service was not bound: else console.println("ERROR: " + nStatus); // Attempt to bind to the service: SOAP.resolveService({ cType: "http", cDomain: "local.", cService: "My Web Server", oAsync: myNotification }); Acrobat JavaScript provides support for XM L-based information generated within your workflows by providing an object, 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 no de and its children using the object). The : Creates an object representing an XML document tree. : 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 objects method. Acrobat JavaScript Scripting Guide SOAP and Web Services Managing XML-based Information The objects param1 : A string containing the text in the XML document. param2 Its usage is illustrated below: // XML string to be converted into a document tree: myXML = "family name = 'Robatྦm;i6ly; 6na;m6e ;= ';Rob;jt6;'000;'\ mom id = 'm1' name = 'Mary' gender = 'F'mom; id; =6; 'm6;' 6;na6m; 6=; 6'M;¦ry;'6 g;nnd;nr6; = 6;'F'6;\ chiÆhi;ld0;ld m2 /chil/ch;il6;퀀d\ personalp6er;son;jl6;\ incomei6nc;ome;怀75000/incom/6in;lom;渀e\ /persona/6pe;rso;na6;l000;l\ /mo/mo;m00;m\ son id = 'm2' name = 'Bob' gender = 'son; -6;id6 ;-6=6; -6';m62'; na6;me =; 'Bo;k' ;ge6n;෦r; = -;'6M;'000;M'\ parentp6ar;nnt;怀 m1 /parent/p6a;r6en;t600;\ personalp6er;son;jl6;\ incomei6nc;ome;怀35000/incom/6in;lom;渀e\ /persona/6pe;rso;na6;l000;l\ /so/so;n00;n\ /famil/fa;mil;y00;y"; // Generate the document tree: var myTree = XML.parse(myXML, false); // Print moms name: console.println("Mom: " + myXML.family.mom.value); // Change sons income: myXML,family.son.personal.income.value = 40000; The objects : An object representing the XML document tree. : A string containing an XPath query to be performed on the document tree. In the following example, assume that is the document tree obtained in the previous example: // Obtain moms information: var momInfo = XML.applyXPath(myXML, "//family/mom"); // Save the information to a string: momInfo.saveXML('pretty'); // Give mom a raise: momInfo.personal.income.value = "80000"; SOAP and Web Services Workflow Applications Acrobat JavaScript Scripting Guide 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 th e DNS Service Discovery support, it is possible to enable dynamic disc overy of collaboration servers, initiation workflows, and RSS feeds that can provide customized user interfac es, via XML, directly inside of Acrobat 7.0. In addition, it is possible to deploy Web-ba sed JavaScripts that always maintain the most updated information and processes, and to conn ect to those scripts via form field actions that invoke web services. In the following example, a form is submitte d to a server using a SOAP-based invocation: // Populate the content object with form and SOAP information: var location = "http://adobe.com/Acrobat/Form/submit/" var formtype = location + "encodedTypes:FormData"; var content = new Array(); for(var i = 0; i document.numFields; i++) { var name = document.getNthFieldName(i); content[i] = new Object(); content[i].soapType = formtype; content[i].name = field.name; content[i].val = field.value; // Send the form to the server: SOAP.request({ cURL: cURL, oRequest: { location + ":submitForm": content: content cAction: location + "submitForm" Acrobat JavaScript Scripting Guide A Short Acrobat JavaScript FAQ Acrobat form fields typically have names like Acrobat form field names can be more useful by creating a hierarchal structure. For example, if we change and to we form a tree of fields. The period (.) separator is used in Acrobat Forms and denotes a hierarchy shift. The portion of these fields is the parent, and become the children. While there is no limit to the depth to which a hierarchical name can be constructed, it is important th at 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 applicatio ns when there are many fields in the Using our original flat names and , 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 name.fillColor = color.yellow; name = this.getField("MiddleName"); name.fillColor = color.yellow; name = this.getField("LastName"); name.fillColor = color.yellow; 1. Frequently Asked Questions A Short Acrobat JavaScript FAQ How should I name my Acrobat form fields? Acrobat JavaScript Scripting Guide With the hierarchy of suggested above, you can change the background color of these fields with just two lines of code instead of name.fillColor = color.yellow When using this hierarchy within a JavaScri pt, you can only change appearance-related properties of the parent field, and those change s will propagate to all its children. However, you cannot change the fields value. For example if you try the following script: name.value = "Lincoln"; the script will fail. is considered a parent field. You can only change the value of terminal fields (i.e. a field that does not have children like ). The following script executes correctly: first.value = "Abraham"; last.value = "Lincoln"; Acrobat JavaScript Scripting Guide A Short Acrobat JavaScript FAQ How do I use date objects? How do I use date objects? This section discusses the use of objects within Acrobat. The reader should be familiar with the JavaScript object and the methods that process dates. JavaScript objects actually contain both a date and a time. All references to this section refer to the date-time combination. OTE OTE When using the object, do not use the method, which returns the current year minus 1900. Instead use the var d = new Date() d.getFullYear(); Converting from a Date to a String Acrobat provides several date-related methods in addition to the ones provided by the JavaScript objects and strings. Because of Acrobats abil ity to handle dates in many formats, the object does not always handle these conversions correctly. To convert a object into a string, the object is used. Unlike the built-in conversion of the object to a string, allows an exact specification of how the date should be formatted. /* Example of util.printd */ var d = new Date(); // Create a Date object containing the current date /* Create some strings from the Date object with various formats with ** util.printd */ var s = [ "mm/dd/yy", "yy/m/d", "mmmm dd, yyyy", "dd-mmm-yyyy" ]; for (var i = 0; i s.length; i++) { /* print these strings to the console */ console.println("Format " + s[i] + " looks like: " + util.printd(s[i], d)); The output of this script would look like: Format mm/dd/yy looks like: 01/15/05 Format yy/mm/dd looks like: 05/1/15 Format mmmm dd, yyyy looks like: January 15, 2005 Format dd-mmm-yyyy looks like: 15-Jan-2005 OTE 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? Acrobat JavaScript Scripting Guide Converting from a string to a date To convert a string into a object, use the objects method. It accepts a format string that it uses as a hint as to th e order of the year, month, and day in the input string. /* Example of util.scand */ /* Create some strings containing the same date in differing formats. */ var s1 = "03/12/97"; var s2 = "80/06/01"; var s3 = "December 6, 1948"; var s4 = "Saturday 04/11/76"; var s5 = "Tue. 02/01/30"; var s6 = "Friday, Jan. the 15th, 1999"; /* Convert the strings into Date objects using util.scand */ var d1 = util.scand("mm/dd/yy", s1); var d2 = util.scand("yy/mm/dd", s2); var d3 = util.scand("mmmm dd, yyyy", s3); var d4 = util.scand("mm/dd/yy", s4); var d5 = util.scand("yy/mm/dd", s5); var d6 = util.scand("mmmm dd, yyyy", s6); /* Print the dates to the console using util.printd */ console.println(util.printd("mm/dd/yyyy", d1)); console.println(util.printd("mm/dd/yyyy", d2)); console.println(util.printd("mm/dd/yyyy", d3)); console.println(util.printd("mm/dd/yyyy", d4)); console.println(util.printd("mm/dd/yyyy", d5)); console.println(util.printd("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 Date(...) is rather forgiving in terms of the string passed to it. OTE Given a two digit year for input, resolves 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 A Short Acrobat JavaScript FAQ How do I use date objects? object 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 ar e 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 object. The constructor allows the construction of a new date from this number. /* Create a Date object with a definite date. */ var d1 = util.scand("mm/dd/yy", "4/11/76"); /* Create a date object containing the current date. */ var d2 = new Date(); /* Number of seconds difference. */ var diff = (d2.valueOf() - d1.valueOf()) / 1000; /* Print some interesting stuff to the console. */ console.println("It has been " + diff + " seconds since 4/11/1976"); console.println("It has been " + diff / 60 + " minutes since 4/11/1976"); console.println("It has been " + (diff / 60) / 60 + " hours since 4/11/1976"); console.println("It has been " + ((diff / 60) / 60) / 24 + " days since 4/11/1976"); console.println("It has been " + (((diff / 60) / 60) / 24) / 365 + " years since 4/11/1976"); It has been 718329600 seconds since 4/11/1976 It has been 11972160 minutes since 4/11/1976 It has been 199536 hours since 4/11/1976 It has been 8314 days since 4/11/1976 It has been 22.7780821917808 years since 4/11/1976 A Short Acrobat JavaScript FAQ Acrobat JavaScript Scripting Guide The following example shows the addition of dates. /* Create a date object containing the current date. */ var d1 = new Date(); /* num contains the numeric representation of the current date. */ var num = d1.valueOf(); /* Add thirteen days to todays date, in milliseconds. */ /* 1000 ms/sec, 60 sec/min, 60 min/hour, 24 hours/day, 13 days */ num += 1000 * 60 * 60 * 24 * 13; /* Create our new date, 13 days ahead of the current date. */ var d2 = new Date(num); /* Print out the current date and our new date using util.printd */ console.println("It is currently: " + util.printd("mm/dd/yyyy", d1)); console.println("In 13 days, it will be: " + util.printd("mm/dd/yyyy", d2)); It is currently: 01/15/1999 In 13 days, it will be: 01/28/1999 methods available to . 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 rest You must obtain a digital ID. You must sign the PDF document containing the restricted JavaScript methods using the digital ID. sign documents, see Acrobat Help. The recipient should trust the signer for certified documents and JavaScript. All trusted certificates can be access ed by selecting Certificates from Advanc ed Manage Digital IDs Trusted Identities in Acrobats main menu. Acrobat JavaScript Scripting Guide A Short Acrobat JavaScript FAQ 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 belo w will make your forms more easily usable by 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 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 Fi le Document Proper ties Initial View and in the Window Options, choose to either the File Name or Document Title Short Description Every field that is not hidden must contain a user-friendly name (too ltip). 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 " ", a good short description would be " ". The name should not depend on the surrounding context. For instance, if both the main section and spouse section of a document contain a " " field, the field in the spouse section might be named " ". This description is also displayed as a toolti p when the user positi ons the mouse over the Setting Tab Order In order to traverse the document in a reasonable manner, the tab order for the fields must A Short Acrobat JavaScript FAQ How can I define global variables in JavaScript? 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 wi ll 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 The Acrobat extensions to JavaScript define a object to which you can attach global variables as properties. To define a new global variable called ' global.myVariable = ""; 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 sess ions unless you specifically make your global varaibles persistent. The predefined ' persist across sessions, use the following syntax: global.setPersistent("myVariable",true); In future sessions, the variable will still exist with its previous value intact. Acrobat JavaScript Scripting Guide A Short Acrobat JavaScript FAQ How can I hide an Acrobat form field based on the value of another? Use the object: title.display = display.hidden; else title.display = display.visible; One way would be to use the object's method to make the field(s) of interest available to others at runtime. For example, a form may co ntain a document-level script (invoked when that document is first opened) that defines a global field value of interest: function PublishValue( xyzForm_fieldValue_of_interest ) { global.xyz_value = xyzForm_fieldValue_of_interest; Then, when your document (Document A) wants to access the value of interest from the other form (Document B), it can subs cribe to the variable in question: global.subscribe("xyz_value", ValueUpdate); In this case, ValueUpdate refers to a user-defined function that is called automatically whenever changes. If you were using in Document A as part of a , you might define the callback function this way: function ValueUpdate( newValue ) { this.getField("MyField").value = newValue;} How can I intercept keystrokes one 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 . By altering this value, you can alter the us er's input as it takes place. A Short Acrobat JavaScript FAQ How can I construct my own colors? Acrobat JavaScript Scripting Guide Colors are 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: color.blue = new Array("RGB", 0, 0, 1); color.cyan = new Array("CMYK", 1, 0, 0, 0); To make a custom color, just declare an arra y containing the color-space type and channel values you want to use. Use the defined in the var dialogTitle = "Please Confirm"; var defaultAnswer = "No."; var reply = app.response("Did you really mean to type that?", dialogTitle, defaultAnswer); Use the 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 A Short Acrobat JavaScript FAQ How can I disallow changes in scri pts 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 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, 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 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 ha ve been disabled by returning to the Security tab. In the Document Restrictions Summary portion, Changing the Document A Short Acrobat JavaScript FAQ How can I hide scripts contained in my document? Acrobat JavaScript Scripting Guide Acrobat JavaScript Scripting Guide Index Acrobat Acrobat Database Connectivity 238 Acrobat forms Acrobat form field action types 179 237 238 238 newConnection 238 adding security to attachments 217 additional usage rights 124 227 159 160 114 Adobe Dialog Manager 159 Adobe Document Server 228 Adobe LiveCycle Designer 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 223 Advanced Editing Toolbar advanced search options 193 annot 129 134 137 attachIcon 130 destroy 136 138 133 136 137 130 transitionToState 137 annotations app execDialog 162 fullscreen 182 hideMenuItem 183 hideToolbarButton 183 newDoc openDoc 139 openInPlace 175 printColorProfiles printerNames app.media 145 151 145 151 windowType 182 Approval 135 140 approval stamp 209 Array sort asynchronous communication base64 encoding 252 255 batch 139 binary data bookmark color 181 hierarchy 173 196 breakpoints conditional button 186 buttonAlignX buttonAlignY buttonScaleHow buttonScaleWhen buttonSetIcon 186 highlight 181 101 106 Acrobat JavaScript Scripting Guide Index call stack catalog 191 197 198 catalogJob 197 certificate 202 203 220 public key 223 certificate authority 219 certifying a document 208 check box defaultIsChecked code formatting Collab 126 addAnnotStore 127 addStateModel 126 126 removeStateModel 126 127 transitionToState 126 Column 237 ColumnInfo 237 240 combining PDF documents combo box commitOnSelChange doNotSpellCheck editable comment aggregate for use in Excel 139 change appearance 137 change status 137 compare 139 find 138 import and export 139 136 137 place checkmarks 137 preferences 133 repository show or hide 138 sort 138 connection 237 240 newStatement 241 console core JavaScript creating a digital ID cropping pages 237 DataSourceInfo 237 238 buttons debug from start 162 load 162 store 162 dictionary 132 add words 133 255 digital ID 218 provider 219 digital signature preferences 210 dirConnection 119 203 212 search 203 212 212 directory 119 202 211 223 connect 212 DirectoryInformation 211 DNS Service Discovery 256 DNS-SD 256 256 256 Service Discovery 243 unicast DNS 256 addField 132 176 addRecipientListCryptFilter 217 addThumbnails 171 addWatermarkFromFile 134 addWatermarkFromText 134 135 addWeblinks 176 Acrobat JavaScript Scripting Guide Index bookmarkRoot 171 bookmark 171 children 172 createChild createDataObject 139 createTemplate 156 dynamicXFAForm 114 encryptForAPS 214 216 encryptForRecipients 120 202 203 211 encryptUsingPolicy 214 exportAsFDF 139 exportAsXFDF 139 exportDataObject 131 139 getAnnot 138 getAnnots 138 139 131 132 187 187 getPageLabel 185 184 gotoNamedDest 178 icons 141 importAnFDF 139 importAnXFDF 139 importDataObject importIcon importSound 130 insertPages layout 182 mailDoc 125 mailForm 115 openDataObject 115 183 print removeDataObject 132 removeField 208 removeLinks 177 removeThumbnails 171 replacePages resetForm saveAs 115 132 187 171 178 setPageBoxes setPageLabels 185 184 spellDictionaryOrder 132 spellLanguageOrder 133 syncAnnotScan 136 templates 156 zoom zoomType 183 doc object doc.media 145 canPlay 153 document/literal encoding 251 manipulating dynamic XML forms architecture 108 ECMAScript Editing Toolbar, Advanced Editor eEnvelope 217 enabling JavaScript encryption 202 203 encrypt for a list of recipients 211 Excel Executing export value Extensible Markup Language 243 external editor 115 208 Acrobat JavaScript Scripting Guide Index signatureValidate 208 field border style button character limit 114 display hierarchy 103 name print rotation signatureSign 202 strokeColor file attachment 130 file creation flattening layers 189 font options footers form accessible 117 creation 115 export 115 save 115 205 spell-check 114 web-ready 107 format options formatting code fullScreen 184 defaultTransition 184 184 115 Group 203 231 Hanko 141 headers highlight annotation 102 HTML JavaScript HTTP 245 authentication 255 HTTPS 245 197 198 196 initial view 182 Inkan 141 Interrupt JavaScript core creating simple scripts 123 143 155 159 191 201 enabling external editors formatting objects JavaScript objects language 133 link 175 176 annotation 132 borderColor 181 remove 177 177 list box multipleSelection Acrobat JavaScript Scripting Guide Index LiveCycle Designer 228 Forms 228 Reader Extensions 227 228 Lock action fields magnification 182 202 143 media player 144 MediaPlayer 146 146 bgColor 153 merging layers 189 Message Transmission Optimization Mechanism 199 Microsoft Active Directory Script Interface 223 MIME 145 202 Monitor 149 150 Monitors 149 movie 143 151 MTOM 252 253 multimedia preferences 153 Multipurpose Internet Mail Extensions 178 navigation 170 with layers 187 NetworkError 255 Object Identifier 228 OCG 187 188 237 238 OID 228 online collaborative review 123 online team review Open Database Connectivity 237 optional content group action 171 insert layout 182 numbering 185 replace transitions 184 password 202 210 PDF documents. Emphasmph; -4.;s-0;.3is;isSee documents 146 PlayerInfo 145 PlayerInfoList 145 select 145 PostScript options Preface options production printParams private key 219 radio buttons readStream 249 Really Simple Syndication 233 relative distinguished name 220 146 146 153 select 152 rendition 152 review, markup, and approval RMA 123 Acrobat JavaScript Scripting Guide Index email-based 124 rotated user space 103 rotating pages 237 242 RSS 233 screen annot 151 script batch-level document-level field-level folder-level search 191 192 query wordMatching 193 119 121 202 203 chooseRecipientsDialog 203 chooseSecurityPolicy 205 206 205 213 handler 206 205 213 corporate policy 213 custom policy 213 token-based security 226 tokenized Acrobat JavaScript security model validateSignaturesOnOpen 210 119 202 206 211 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 205 remove 208 205 signatureSign signature handler 219 signatureInfo 119 202 218 219 certificates 219 225 trustFlags 224 209 Simple Object Access Protocol 243 SOAP 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 streamFromString 253 stringFromStream 253 version 254 wireDump 244 143 152 sound attachment 130 132 addWord 133 checkWord dictionaryNames 132 languages 133 237 238 241 134 statement 237 239 241 execute 241 242 nextRow 242 synchronous connection 248 tab order 105 TableInfo 237 240 tagged annot 117 119 template 155 156 spawn 156 Text 117 Acrobat JavaScript Scripting Guide Index Toolbar Advanced Editing 180 trust level 224 trusted user identities 208 TTS 117 211 UserEntity 203 validation 101 viewing modes 182 full screen regular 182 watches list watermark 134 246 web services 243 244 Web Service Security 255 Web Services Description Language 243 What Can You Do with Acrobat JavaScript? Windows certificate security 223 workflows 243 proxy 245 115 XFA 109 appModel 109 112 Tree 112 treeList 112 115 112 applyXPath 258 DOM 112 forms Node 112 parse Schema Definition Language 243 XMLData 258 199 XPath 112 XSL transform 112 zoom type 183 Acrobat JavaScript Scripting Guide Index