InDesign Scripting Guide
InDesign Scripting Guide
InDesign Scripting Guide
Adobe InDesign CS2 Scripting Guide 2005 Adobe Systems Incorporated. All rights reserved. NOTICE: All information contained herein is the property of Adobe Systems Incorporated. No part of this publication (whether in hardcopy or electronic form) may be reproduced or transmitted, in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior written consent of Adobe Systems Incorporated. The software described in this document is furnished under license and may only be used or copied in accordance with the terms of such license. This publication and the information herein is furnished AS IS, is subject to change without notice, and should not be construed as a commitment by Adobe Systems Incorporated. Adobe Systems Incorporated assumes no responsibility or liability for any errors or inaccuracies, makes no warranty of any kind (express, implied, or statutory) with respect to this publication, and expressly disclaims any and all warranties of merchantability, tness for particular purposes, and noninfringement of third party rights. Any references to company names in sample templates are for demonstration purposes only and are not intended to refer to any actual organization. Adobe, the Adobe logo, Acrobat, Adobe PDF, Adobe Creative Suite, Illustrator, InDesign, InCopy, GoLive, and Photoshop are either registered trademarks or trademarks of Adobe Systems Incorporated in the United States and/or other countries. Apple, Mac, Macintosh, and Mac OS are either registered trademarks or trademarks of Apple Computer, Inc., registered in the United States and other countries. Microsoft and Windows are either registered trademarks or trademarks of Microsoft Corporation in the United States and other countries. UNIX is a trademark in the United States and other countries, licensed exclusively through X/Open Company, Ltd. All other trademarks are the property of their respective owners. If this guide is distributed with software that includes an end user agreement, this guide, as well as the software described in it, is furnished under license and may be used or copied only in accordance with the terms of such license. Except as permitted by any such license, no part of this guide may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, electronic, mechanical, recording, or otherwise, without the prior written permission of Adobe Systems Incorporated. Please note that the content in this guide is protected under copyright law even if it is not distributed with software that includes an end user license agreement. The content of this guide is furnished for informational use only, is subject to change without notice, and should not be construed as a commitment by Adobe Systems Incorporated. Adobe Systems Incorporated assumes no responsibility or liability for any errors or inaccuracies that may appear in the informational content contained in this guide. Adobe Systems Incorporated, 345 Park Avenue, San Jose, California 95110, USA.
Contents
Contents 1
Introduction................................................................. 1
What is in this book ...................................................................................................... 1 Who should read this book........................................................................................ 1 What you need to use scripting ............................................................................... 1
JavaScript..................................................................................................................................... 2 Macintosh .................................................................................................................................... 2 Windows ...................................................................................................................................... 2
ii
Contents
Your rst InDesign script........................................................................................... 22 Adding features to Hello World .......................................................................... 25 Adding a user interface to "Hello World" ............................................................ 29
Dialog box overview .............................................................................................................29
Contents
iii
Changing the pasteboard's appearance ............................................................. 82 Using guides and grids .............................................................................................. 82
Dening guides .......................................................................................................................82 Setting grid preferences ......................................................................................................84 Snapping to guides and grids ............................................................................................84
Changing measurement units and ruler ............................................................. 85 Dening and applying document presets ......................................................... 85
Creating a preset by copying values ...............................................................................85 Creating a preset using new values .................................................................................86 Using a preset ..........................................................................................................................87
Adding XMP metadata .............................................................................................. 91 Creating a document template .............................................................................. 92 Printing a document ..................................................................................................96
Printing using page ranges .................................................................................................96 Setting print preferences .....................................................................................................96 Using printer presets .............................................................................................................99 Creating printer presets from printing preferences...................................................99
iv
Contents
Changing the pasteboard's appearance ........................................................... 117 Using guides and grids ............................................................................................ 117
Dening guides ..................................................................................................................... 117 Setting grid preferences ....................................................................................................119 Snapping to guides and grids ..........................................................................................119
Changing measurement units and ruler ........................................................... 119 Dening and applying document presets ....................................................... 120
Creating a preset by copying values .............................................................................120 Creating a preset using new values ...............................................................................121 Using a preset ........................................................................................................................122
Adding XMP metadata ............................................................................................ 126 Creating a document template ............................................................................ 127 Printing a document ................................................................................................130
Printing using page ranges ...............................................................................................130 Setting print preferences ...................................................................................................130 Using printer presets ...........................................................................................................133 Creating printer presets from printing preferences.................................................133
Contents
Changing the pasteboard's appearance ...........................................................149 Using guides and grids ............................................................................................150
Dening guides .....................................................................................................................150 Setting grid preferences ....................................................................................................152 Snapping to guides and grids ..........................................................................................152
Changing measurement units and ruler ........................................................... 153 Dening and applying document presets .......................................................154
Creating a preset by copying values ............................................................................ 154 Creating a preset using new values ...............................................................................155 Using a preset ........................................................................................................................155
Setting up master spreads ..................................................................................... 155 Setting text-formatting defaults .......................................................................... 157
Setting application text defaults ....................................................................................157 Setting the active document's defaults .......................................................................159 Using text defaults .............................................................................................................. 160
Adding XMP metadata ............................................................................................160 Creating a document template ............................................................................160 Printing a document ................................................................................................165
Printing using page ranges .............................................................................................. 165 Setting print preferences .................................................................................................. 166 Creating printer presets from printing preferences................................................ 169
vi
Contents
Introduction
Introduction
If youre reading this, youve discovered the most powerful feature in Adobe InDesign CS2. No other featureno tool, palette, or dialog box that you see in the programs user interfacecan save you as much time, trouble, and money as scripting.
Chapter 1, Introduction: Provides general information about this book, lists prerequisites for using InDesign, and provides tips for copying script examples from this book into a script editor. Chapter 2, Scripting Basics: Gives a quick introduction to general scripting concepts, for those who have never done scripting or those who are not familiar with the scripting languages supported by InDesign. Chapter 3, Getting Started with InDesign Scripting: Gives background information that is important for you to know when creating scripts for InDesign. Provides simple examples of common scripting operations. Chapter 4, Using ExtendScript Tools and Features for JavaScript: Describes tools for JavaScript, including debugging, interapplication, and assorted others. Chapter 5, Working with Documents in AppleScript: Provides AppleScript examples for many operations necessary to work with InDesign documents. Chapter 6, Working with Documents in JavaScript: Provides JavaScript examples for many operations necessary to work with InDesign documents. Chapter 7, Working with Documents in VBScript: Provides VBScript examples for many operations necessary to work with InDesign documents.
Introduction
Although the scripting systems dier, the ways that they work with InDesign are similar. Each example script in this manual is shown in all languages. Translating a script from one language to another is a fairly easy task.
JavaScript
InDesign supports JavaScript for cross-platform scripting in both Mac OS and Windows. InDesigns JavaScript support is based on an Adobe implementation of JavaScript known as ExtendScript. The ExtendScript interpreter conforms to the current ECMA 262 standard for JavaScript. All language features of JavaScript 1.5 are supported, including try/catch/nally, equality operators, and the new instanceof and in operators. Adobe GoLive and other Adobe products also use the ExtendScript JavaScript interpreter.
Macintosh
To use InDesign scripting on the Macintosh, you can use either JavaScript or AppleScript. To write AppleScripts, you must have AppleScript version 1.6 or higher and an AppleScript script editor. AppleScript comes with all Apple systems, or can be downloaded free from the Apple website. The Apple Script Editor is included with the Mac OS; third-party script editors, such as Script Debugger (from Late Night Software, http://www.latenightsw.com), are also available.
Windows
To use InDesign scripting in Windows, you can use either JavaScript or some version of Microsoft Visual Basic, such as VBScript. To create InDesign scripts using VBScript, you need only a text editor (such as Notepad). Other versions of Visual Basic include Visual Basic 5 Control Creation Edition (CCE), Visual Basic 6, Visual Basic .NET, or an application that contains Visual Basic for Applications (VBA). Microsoft Oce, Visio, AutoCAD, and other programs include VBA. Although InDesign supports VBA, it does not include VBA. To use VBScript or VisualBasic for InDesign scripting in Windows, you must install InDesign from a user with Administrator privileges. After youve completed the installation, any user can run InDesign scripts, and any user with Power User or Adminstrator privileges can add scripts to the InDesign Scripts palette.
Note: You can also store the script le at another location and place an alias (Mac OS) or shortcut (Windows) to the le in the Scripts folder.
Introduction
3. Display the Scripts palette by choosing Window > Automation > Scripts. 4. Run the script by double-clicking the script name in the Scripts palette.
AppleScript example
When you paste the following line into a text editor, remove the line break following properties. If you dont, the script generates an error.
set myBaseNameField to make text editbox with properties {edit contents:myDocumentName, min width:160}
JavaScript example
When you paste the following line into a text editor, remove the line breaks following the commasthe line should end with the semicolon (;). In this example it works correctly with or without line breaks; however, the ExtendScript interpreter can interpret a line break as the end of a statement in some cases.
guides.add(myDocument.layers.item("GuideLayer"), {orientation:HorizontalOrVertical.horizontal, location:marginPreferences.top, fitToPage:false});
VBScript example
When you paste the following line into a text editor, remove the line breaks preceding the equal sign (=). If you don't, the script generates an error.
myInDesign.ActiveDocument.MasterSpreads.Item("B-Master").Pages.Item(1).AppliedMaster = myInDesign.ActiveDocument.MasterSpreads.Item("A-Master")
Introduction
http://partners.adobe.com/public/developer/scripting/index.html http://www.adobeforums.com, the InDesign Scripting User-to-User forum. In the forum, scripters can ask questions, post answers, and share their newest scripts. The forum contains hundreds of example scripts. http://www.adobe.com/products/indesign/scripting.html
Scripting Basics
Scripting Basics
If youve used InDesign, youve worked with frames and their contents, and youve learned to apply colors, formatting, and styles. Youve set up publications, spreads, pages, and the design elements on those pages. If youve done all of this, youve gotten used to thinking of an InDesign publication as a collection of objects. InDesign scripting uses the same approach. The core of InDesign scripting is the object model: a description of all the types of itemsdocuments, spreads, pages, frames, and the contents of those framesthat can appear in an InDesign publication. Each type of object has its own special properties, and every object in an InDesign publication has its own identity. Not every InDesign user will be familiar with programming terms, concepts, and techniques, so this chapter provides introductory information to help get you started with scripting. It covers the basic concepts of scripting, or programming, for both Windows and the Macintosh. For more detailed directions on using your scripting system with InDesign, see Chapter 3, Getting Started with InDesign Scripting. Experienced scripters might want to skip directly to that chapter.
Introduction to scripting
Scripting isnt only for software engineersits for every InDesign user. You dont need a degree in computer science or mathematics to write scripts that can automate a wide variety of common page-layout tasks in InDesign. If you can read this text, you can write InDesign scripts.
What is scripting?
A script is a series of commands that tells InDesign to perform a series of actions. These actions can be simple and aect only a single, selected object in the current publication; or complex and aect all of the objects in all of the InDesign publications on your hard drive. The actions might involve only InDesign, or they might involve other applications, such as word processors, spreadsheets, and database management programs. Virtually every task that you can perform by manipulating InDesigns tools, menus, palettes, and dialog boxes can be performed by a script. Scripting is a way to automate repetitive tasks, but it can also be a creative tool. In addition to performing routine production tasks, such as preparing a set of publications for remote printing, you can use scripts for creative tasks that would be too dicult or too time consuming to do yourself. For example, you could write a script to randomly change the font and color of the characters in a selection, or to gradually increase the size and baseline shift of characters from one end of a range of text to the other. Without scripting, you might not use these creative eects.
Scripting Basics
On the Macintosh, scripting is often accomplished using AppleScript, a scripting system that sends messages to applications or to the operating system using AppleEvents. In Windows, VBScript programs use a similar system for interapplication communication, usually referred to as Windows Automation. JavaScripts, by contrast, run on either platform. The terminology diers among the scripting languages, but the idea is the sameto send information from one program (the scripting system) to another program (InDesign) to make the receiving application perform some task. Not all applications can be controlled by scripts. For scripting to work, an application has to receive messages from another application, and has to be able to turn those messages into actions. In addition, the messages you send to an application have to be constructed in a particular way, or the application cant understand what you want it to do. This book is a kind of language lessonit shows you how to talk to InDesign.
Macros use a programs user interface to do their work. As a macro runs, it displays and closes dialog boxes, pulls down menus, makes menu choices, and types text into documents or elds. Scripts do not use a programs user interface to perform their tasks, and they execute much faster than the fastest macro. Macros have very limited facilities for getting and responding to information from a program. Scripts can get information and then make decisions and calculations based on the information that they receive.
Note: In Microsoft Word, Excel, and some other Microsoft Oce applications, macros are recordings of user actions written as scripts, which can be edited to add scripting features. These macros are not the type of macro were describing in the preceding text, and InDesign does not have the ability to record user actions as a script.
Scripting Basics
In general, therefore, its best to end each line with a semicolon, and to insert returns only at the ends of statements.
Scripting Basics
Objects
Objects belong to classes, and have properties that you manipulate using methods (Windows) or commands (Macintosh). What do these words mean in this context? Heres a way to think about objects and object properties. Imagine that you live in a technologically advanced (or magic) house that responds to your commands. The house is one object. The properties of your house object might include the number of rooms, the color of the exterior paint, and the date of its construction. Imagine that the house can change some of its propertiesif given the correct command. You might say, House, paint yourself blue. Because your house can respond to the method paint, youll soon have a house of a dierent color. Next, your house contains many smaller objects. Each room, for example, might be an object, with each window, door, or appliance being other objects inside the room. You can talk to these objects directly, or you can talk to them through the house. You have to be very specic, thoughyou cant tell your house to open a window without telling it which window to open. You can also give commands to the objects inside the rooms. Tell the kitchen to open the north window, you might say. Each object in the house can respond to various methods according to its capabilities. Windows and doors, for example, can open or closebut the oor and ceiling cannot. Some properties of objects can be changed; some cannot. The location of a piece of furniture can be changed; the construction date of the house cannot. Properties that can be changed are read/write; properties that cannot be changed are read only. To apply this metaphor to InDesignthe application is the house, the spreads and pages are the rooms, and the frames on your pages are the windows and doors. You can tell InDesign pages to add frames, and you can tell frames to change their properties or content. You can then tell the frames to change color, import a graphic, or populate themselves with text. Objects in your publication are arranged in a hierarchyframes are on pages, which are inside a document, which is inside InDesign. When we speak of an object model, or a hierarchy, were talking about this structure.
Object references
When you send a command to an InDesign object, you must send the message to the correct objectthe correct address. To do this, you identify objects by their position in the hierarchy. When you identify an object in this fashion, youre creating an object reference. The dierent languages use dierent ways to create object references, but the idea is the sameto give the script directions for nding the object that you want to work with. The following examples show how to refer to the rst text frame of the rst spread of the active document (note that these are not complete scripts).
Scripting Basics
AppleScript
first text frame of the first spread of the first document
Note: When your AppleScript refers to a text object, InDesign returns the text contained in the objectnot a reference to the object itself. To get a reference to the text object, use the object reference property, as shown in this example:
tell application "Adobe InDesign CS2" set myDocument to make document tell spread 1 of myDocument set myTextFrame to make text frame set contents of myTextFrame to "InDesign" --The following line returns the text "InDesign" get paragraph 1 of myTextFrame --The following line returns a text object get object reference of paragraph 1 of myTextFrame end tell end tell
VBScript
Documents.Item(1).Spreads.Item(1).TextFrames.Item(1)
JavaScript
app.documents.item(0).spreads.item(0).textFrames.item(0)
Values
The point size of a character of text, the horizontal location of a text frame on a page, or the color of stroke of a rectangle are all examples of values used in InDesign scripting. Values are the data that your scripts use to do their work. The type of a value denes what sort of data the value contains. The value type of the contents of a word, for example, is a text string; the value type of the leading of a paragraph is a number. Usually, the values used in scripts are numbers or text. The following table explains the value types most commonly used in InDesign scripting. Value type Boolean Integer What it is Logical True or False Example
True
14 Whole numbers (no decimal points). Integers can be positive or negative. In VBScript, you can use the long data type for integers. In AppleScript, you can also use the xed or long data types for both integers and real numbers.
10
Scripting Basics
Value type Double (VBScript), xed or real (AppleScript), oating point (JavaScript) String Array (VBScript, JavaScript) or list (AppleScript)
Example
13.9972
A series of text characters. Strings appear inside (straight) quotation marks. A list of values (the values can be any type).
"I am a string" AppleScript: {"0p0", "0p0", "16p4", "20p6"} VBScript: Array("0p0", "0p0", "16p4", "20p6") JavaScript: ["0p0", "0p0", "16p4", "20p6"]
Variables
Variables are containers for data. A variable might hold a number, a string of text, or a reference to an InDesign object. Variables have names, and you refer to a variable by its name. To put data into a variable, you assign the data to the variable. The le name of the current InDesign publication, the current date and time, and the number of pages in the publication are all examples of data that you can assign to a variable. Why not simply enter the data itself (the publications name, or the current date and time, or the number of pages in the publication, for example), rather than using variables? Because, if you do, your script will work in only one publication or situation. By using variables, you can write scripts that will work in a wider range of situations. As a script executes, it can assign data to the variables that reect the current publication and selection (for example), and then make decisions based on the content of the variables. Assigning values or strings to variables is fairly simple, as shown in the following examples. AppleScript VBScript JavaScript
set myNumber to 10 set myString to "Hello, World!" myNumber = 10 myString = "Hello, World!" var myNumber = 10; var myString = "Hello, World!";
In AppleScript, you can assign an object reference to a variable as you create the object:
set myTextFrame to make text frame with properties(geometric bounds: (0,0,3.5, 4))
VBScript works in a similar way. For example, to assign a variable as you create a frame (myInDesign in the following line is a reference to the InDesign application object):
Set myTextFrame = myInDesign.Documents.Item(1).Spreads.Item(1).TextFrames.Add
Scripting Basics
11
The same operation in JavaScript is more similar to VBScript than it is to AppleScript (in InDesign JavaScript, app is a reference to the InDesign application). To refer to an existing frame:
var myTextFrame = app.documents[0].spreads[0].textFrames[0]; //or var myTextFrame = app.documents.item(0).spreads.item(0).textFrames.item(0);
Note: In JavaScript, all variables that are not preceded by var are considered global by defaultthat is, they are not bound to a specic function; var is not required, but we recommend that you use var in any script with more than a single function. In AppleScript and VBScript, variables are local unless specically dened as global variables. This means that the variables do not persist outside the function in which they are created. In general, in any of the languages, its best to use local variables and pass specic values to functions/ subroutines/handlers rather than dening and using global variables. In JavaScript, you dene a variable as a local variable using var, as shown in the preceding example. To specify that several variables in a JavaScript function are local variables, you can list them at the beginning of the function; for example:
function myFunction(){ var myNumber, myString; }
Variable names
Try to use descriptive names for your variables, such as firstPage or corporateLogo, rather than x or c. This makes your script easier to read. Longer names do not aect the execution speed of the script. Variable names must be a single word, but you can use internal capitalization (such as myFirstPage) or underscore characters (my _ first _ page) to create more readable names. Variable names cannot begin with a number, and they cant contain punctuation or quotation marks. You might also want to give your variable names a prex so that theyll stand out from the objects, commands, and keywords of your scripting system. All of the variables used in this book, for example, begin with my.
In VBScript or Visual Basic versions other than VB.NET, use Set to assign object references to variables, but not to string, array, or number variable types:
Set myDocument = myInDesign.Documents.Add myString = "X"
12
Scripting Basics
Like VB.NET, JavaScript does not require Set when you assign values to variables, regardless of the type of the variable:
var myDocument = app.documents.add(); var myString = "X";
Array variables
AppleScript, VBScript, and JavaScript all support arrays, which is a variable type that is a list of values. In AppleScript, an array is called a list. AppleScript VBScript JavaScript
set myArray to {1, 2, 3, 4} myArray = Array(1, 2, 3, 4) Rem In Visual Basic.NET: myArray = New Double (1, 2, 3, 4) myArray = [1, 2, 3, 4];
To refer to an item in an array, refer to the item by its index in the array. The rst item in an array in VBScript and JavaScript is item 0; in AppleScript, the rst item in an array is item 1. AppleScript VBScript JavaScript
set myFirstArrayItem to item 1 of myArray myFirstArrayItem = myArray(0) myFirstArrayItem = myArray[0];
Note: The Visual Basic Option Base statement can be used to set the rst item of an array to item 1. The examples in this book and on your InDesign CD assume that the rst item in an array is item 0, not item 1, because that is the default. If you have set the Option Base to 1, you must adjust all the array references in the example scripts accordingly. Arrays can include other arrays, as shown in the following examples. AppleScript VBScript JavaScript
set myArray to {{0, 0}, {72, 72}} myArray = Array(Array(0,0), Array(72, 72)) Rem In Visual Basic.NET: myArray = New Array(New Double(0,0), NewDouble (0,0)) myArray = [[0,0], [72,72]];
AppleScript
--To convert from a number to a string: set myNumber to 2 set myString to (myNumber as string) --To convert from a string to a number: set myString to "2" set myNumber to (myString as integer) --if your string contains a decimal value, use "as real" rather than "as integer"
Scripting Basics
13
VBScript
Rem To convert from a number to a string: myNumber = 2 myString = cstr(myNumber) Rem To convert from a string to an integer: myString = "2" myNumber = cInt(myString) Rem If your string contains a decimal value, use "cDbl" rather than "cInt": myNumber = cDbl(myString)
JavaScript
//To convert from a number to a string: myNumber = 2; myString = myNumber + ""; //To convert from a string to an integer: myString = "2"; myNumber = parseInt(myString); //If your string contains a decimal value, use "parseFloat" rather than "parseInt": myNumber = parseFloat(myString); //You can also convert strings to numbers using the following: myNumber = +myString;
AppleScript
-- Given a variable of unknown type, "myMysteryVariable"... set myType to class of myMysteryVariable --myType will be an AppleScript type (e.g., rectangle)
VBScript
Rem Given a variable of unknown type, "myMysteryVariable"... myType = TypeName(myMysteryVariable) Rem myType will be a string corresponding to the variable type (e.g., "Rectangle")
JavaScript
//Given a variable of unknown type, "myMysteryVariable"... var myType =typeof (myMysteryVariable); //If the variable is an object, "typeof" will return "object". //To get the specific type of the object, add the following: if (myType == "object"){ myType = myMysteryVariable.constructor.name; } //myType will be a string corresponding to the JavaScript type (e.g., "Rectangle")
When you are iterating through a collection, JavaScript insists that the type of the item is the type of the collection. When you iterate through a pageItems collection, for example, the type of each item will be PageItem, rather than Rectangle, Oval, Polygon, GraphicLine, or TextFrame. To get the specic type of an item when you are iterating through a collection of unlike items, use the getElements() method, as shown in the following example:
14
Scripting Basics
for(myCounter = 0; myCounter < app.activeDocument.pages.item(0).pageItems.length; myCounter ++){ var myPageItem = app.activeDocument.pages.item(0).pageItems.item(myCounter); var myPageItemType = myPageItem.getElements()[0].constructor.name; alert(myPageItemType); }
Operators
Operators use variables or values to perform calculations (addition, subtraction, multiplication, and division) and return a value. For example:
MyWidth/2
returns a value equal to half of the content of the variable myWidth. You can also use operators to perform comparisons (equal to (=), not equal to(<>), greater than(>), or less than(<)). For example:
MyWidth > myHeight
returns the value true (or 1) if myWidth is greater than myHeight, or false (0), if it isnt. All the scripting languages provide additional utility operators. In AppleScript and VBScript, the ampersand (&) concatenates (or joins) two strings:
"Pride " & "and Prejudice"
Methods
Methods (sometimes called commands or events) are the verbs of scripting. Theyre the parts of the script that make more-complex things happen than can be achieved simply by assigning property values. The type of the object youre working with determines the quantity and type of methods that you can use to manipulate the object. In AppleScript, the make command creates new objects, while set assigns values to properties or creates object variables. In VBScript, the Add method creates new objects, the Set statement assigns InDesign objects to VBScript variables, and the equal sign (=) assigns property values (in Visual Basic.NET, you can omit the Set). In JavaScript, the add() method creates new objects, and the equal sign (=) assigns objects to a variable. If you use more than one scripting language, its easy to get confused as you switch among them. When youre using AppleScript, remember that the equal sign is used only in logical statements (If) and that set is used for all variable assignments. When youre using VBScript or Visual Basic (versions other than VB.NET), Set is used only when you are creating an object variable. In JavaScript, the equal sign is used for assigning values to a variable; use a double equal sign (==) to compare objects. Parameters are sometimes required; for example, when you create a group, InDesign needs to know which objects to include in the new group. Other parameters are optional; for example, when you create a new document, you can specify that InDesign base the new document on a document preset, but its not required.
Scripting Basics
15
AppleScript
In AppleScript, you can also use the with properties to specify object properties as the object is created.
tell application "Adobe InDesign CS2" --Example of an optional parameter (requires that you have a document preset --named "7x9_book_cover"). set myDocument to make document with document preset "7x9_book_cover" tell page 1 of myDocument --Example of using "with properties" to specify object properties as you create the object. set myOval to make oval with properties {geometric bounds:{"6p", "6p", "18p", "18p"}} --Another "with properties" example. set myRectangle to make rectangle with properties {stroke weight:4} --Example of a required parameter: set myGroup to make group with properties {group items:{myOval, myRectangle}} end tell end tell
VBScript
Set myInDesign = CreateObject("InDesign.Application.CS2") Rem Example of an optional parameter (requires that you have Rem a document preset named "7x9_book_cover"). Set myDocument = myInDesign.Documents.Add(myInDesign.DocumentPresets.Item("7x9_book_cover")) Set myOval = myDocument.Pages.Item(1).Ovals.Add myOval.GeometricBounds = Array("6p", "6p", "18p", "18p") Set myRectangle = myDocument.Pages.Item(1).Rectangles.Add myRectangle.StrokeWeight = 4 Rem Example of a required parameter. Set myGroup = myDocument.Pages.Item(1).Groups.Add(Array(myOval, myRectangle))
JavaScript
//Example of an optional parameter (requires that you have //a document preset named "7x9_book_cover"). var myDocument = app.documents.add(app.documentPresets.item("7x9_book_cover")) //Example of setting object properties as you create the object. var myOval = myDocument.pages.item(0).ovals.add( {geometricBounds:["6p", "6p", "18p", "18p"]}); var myRectangle = myDocument.pages.item(0).rectangles.add( {strokeWeight:4}); //Example of a required parameter. var myGroup = myDocument.pages.item(0).groups.add([myOval, myRectangle]);
Control structures
Most scripts do not proceed sequentially from beginning to endthey take dierent paths depending on decisions, or they repeat commands multiple times. Control structures are the commands to do such things.
Conditional statements
If you could talk to InDesign, you might say, If the selected object is a rectangle, then set its stroke weight to 12 points. This is an example of a conditional statement. Conditional statements make decisionsthey give your scripts a way to evaluate something (such as the color of the selected object, or the number of pages in the publication, or the date) and then act according to the result. Conditional statements almost always start with if. The following examples check the quantity of currently open publications. If no publications are open, the scripts display a message in a dialog box.
16
Scripting Basics
AppleScript
tell application "Adobe InDesign CS2" if (count documents) = 0 then display dialog "No InDesign documents are open!" end if end tell
VBScript
Set myInDesign = CreateObject ("InDesign.Application.CS2") If myInDesign.Documents.Count = 0 MsgBox "No InDesign documents are open!" End If End Sub
JavaScript
if(app.documents.length==0){ alert("No InDesign documents are open!"); }
Note: JavaScript uses a double equal sign (==) for comparing values (as in the preceding example), and a single equal sign (=) for assigning values. VBScript and AppleScript use a single equal sign for comparisons.
Loops
If you could talk to InDesign, you might say, Repeat the following procedure twenty times. In scripting terms, this is a control structure. Control structures provide repetitive processes, or loops. The idea of a loop is to repeat an action over and over again, with or without changes between instances (or iterations) of the loop, until a specic condition is met. Scripting languages have a variety of dierent control structures to choose from. The simplest form of a loop is one that repeats a series of script operations a specic number of times. A more complicated type of control structure loops until some condition is true or false. Note: You can stop a running script by pressing Command+period (.) in Mac OS or Esc in Windows.
AppleScript
Here is a simple loop:
repeat with counter from 1 to 20 --do something end repeat
Scripting Basics
17
VBScript
Here is a simple loop:
For counter = 1 to 20 Rem do something Next
JavaScript
Here is a simple loop:
for(var myCounter = 0; myCounter < 20; myCounter++){ //do something }
AppleScript
--Calculate the geometric center of a selected page item --Assumes you have a single page item selected. tell application "Adobe InDesign CS2" set mySelection to item 1 of selection --Use "my" (or "of me") to specify a handler outside of the current "tell" context. set myCenterPoint to my myCalculateCenterPoint(mySelection) display dialog "x center: " & item 1 of myCenterPoint & return & "y center: " & item 2 of myCenterPoint end tell --The following lines define the handler. on myCalculateCenterPoint(myObject) set myGeometricBounds to geometric bounds of myObject set myX1 to item 2 of myGeometricBounds set myY1 to item 1 of myGeometricBounds set myX2 to item 4 of myGeometricBounds set myY2 to item 3 of myGeometricBounds set myXCenter to myX1 + ((myX2 - myX1) / 2) set myYCenter to myY1 + ((myY2 - myY1) / 2) return {myXCenter, myYCenter} end myCalculateCenterPoint
18
Scripting Basics
VBScript
Rem Calculate the geometric center of a selected page item Rem Assumes you have a single page item selected. Set myInDesign = CreateObject("InDesign.Application.CS2") Set mySelection = myInDesign.Selection.Item(1) myCenterPoint = myCalculateCenterPoint(mySelection) MsgBox "x center: " & myCenterPoint(0) & vbCr & "y center: " & myCenterPoint(1) Function myCalculateCenterPoint(myObject) myBounds = myObject.GeometricBounds myX1 = myBounds(1) myY1 = myBounds(0) myX2 = myBounds(3) myY2 = myBounds(2) myXCenter = myX1 + ((myX2 - myX1) / 2) myYCenter = myY1 + ((myY2 - myY1) / 2) myCalculateCenterPoint = Array(myXCenter, myYCenter) End Function
JavaScript
with(app){ var mySelection = selection[0]; var myCenterPoint = myCalculateCenterPoint(mySelection); var myString = "x center: " + myCenterPoint[0] + "\n" + "y center: " + myCenterPoint[1]; alert(myString); } function myCalculateCenterPoint(myObject){ var myGeometricBounds = myObject.geometricBounds; var myX1 = myGeometricBounds[1]; var myY1 = myGeometricBounds[0]; var myX2 = myGeometricBounds[3]; var myY2 = myGeometricBounds[2]; var myXCenter = myX1 + ((myX2 - myX1)/2); var myYCenter = myY1 + ((myY2 - myY1)/2); return [myXCenter, myYCenter]; }
19
Coordinates
InDesign, like every other page layout and drawing program, uses simple two-dimensional geometry to record the position of objects on a page or a spread. The horizontal component of a coordinate pair (or point) is referred to as x, the vertical position is referred to as y. You can see these coordinates in the Transform palette when you select an object using the Selection tool. As in the InDesign user interface, coordinates are measured relative to the location of the zero point, which could be at the upper-left corner of the spread, or of the page, or at the binding edge of the spread. There is one dierence between the coordinates used in InDesign and the traditional geometric coordinate systemon InDesigns vertical (or y) axis, coordinates below the zero point are positive numbers; coordinates above the zero point are negative numbers. InDesign usually returns coordinates in x, y order, and expects you to provide them in that order. Note: InDesign returns some coordinates in a dierent order, and expects you to supply them in that order. Geometric bounds and visible bounds are both arrays containing four coordinatesthese coordinates dene, in order, the top, left, bottom, and right edges of the objects bounding box (or y1, x1, y2, x2). To tell InDesign to move the current selection to a position two picas to the right and six picas below the zero point, for example, youd use the following scripts.
20
AppleScript
tell application "Adobe InDesign CS2" set mySelection to item 1 of selection move mySelection to {"2p", "6p"} end tell
VBScript
Set myInDesign = CreateObject("InDesign.Application.CS2") myInDesign.Selection.Item(1).Move Array("2p","6p")
JavaScript
with(app){ mySelection = selection[0]; mySelection.move(["2p", "6p"]); }
Measurement units
When you send measurement values to InDesign, you can send either numbers (for example, 14.65) or measurement strings (for example, 1p7.1). If you send numbers, InDesign uses the publications current units of measurement; if you send measurement strings, InDesign uses the units of measurement specied in the string. InDesign returns coordinates and other measurement values using the publications current measurement units. In some cases, these units do not resemble the measurement values shown in the InDesign Transform palette. If the current measurement system is picas, for example, InDesign returns fractional values as decimals, rather than using the picas-and-points notation used by the Transform palette. 1p6, for example, is returned as 1.5. InDesign does this because your scripting system would have trouble trying to perform arithmetic operations using measurement stringstrying to add 0p3.5 to 13p4, for example, would produce a script error; adding .2916 to 13.333 (the converted pica measurements) will not. If your script depends on adding, subtracting, multiplying, or dividing specic measurement values, you might want to set the corresponding measurement units at the beginning of the script. At the end of the script, you can set the measurement units back to whatever they were before you ran the script. Or you can use measurement overrides, as many of the example scripts do. A measurement override is a string containing a special character, as shown in the following examples. Character p pt mm cm c i (or in) Meaning picas (optionally with additional points after the p) points millimeters centimeters ciceros (optionally with additional didots after the c) inches Example 1p6 18pt 6.35mm .635cm 1.4c .25i
21
Application: Preferences (of various sorts) Application: Defaults (Colors, ParagraphStyles, and so on--application default objects apply all new documents) Application: Documents (collection of open documents) Document: Preferences (of various sorts) Document: Defaults (Colors, ParagraphStyles, and so on--document default objects) Document: Spreads/Pages Spread/Page: PageItems (Rectangles, Ovals, Polygons, GraphicLines, TextFrames, etc.) Document: Stories (The text in the document) Story: Text objects (Paragraphs, Words, Characters, Lines, and so on--the text in the story) A button is a page item (its a way to add an interactive button to an exported PDF). Application: Dialogs (script dialog boxes) (includes most of the other user interface gadgets (radio button controls, dropdowns, checkbox controls, and so on) for building modal dialog boxes)
AppleScript
To view the InDesign AppleScript dictionary: 1. Start InDesign and the Apple Script Editor. If you can't nd the Script Editor, see System Requirements in the Introduction. 2. In the Script Editor, choose File > Open Dictionary. The Script Editor displays a standard Open File dialog box. 3. Select the InDesign application and click OK. The Script Editor displays a list of InDesigns objects and commands. You also can see the properties associated with each object.
22
Visual Basic
To view the InDesign object library in Visual Basic (the steps shown are for Visual Basic 6; Visual Basic 5 CCE and Visual Basic.NET users will see slightly dierent dialog boxes): 1. In any Visual Basic project, choose Project > References. Visual Basic displays the References dialog box. 2. Select the Adobe InDesign CS2 Type Library option from the list of available references and click OK. If the library does not appear in the list of available references, click Browse and locate and select the le Resources for Visual Basic.tlb (which is usually inside ~:\Documents and Settings\user_name\Application Data\Adobe\InCopy\Version 4.0\Scripting Support\4.0where user_name is your user name). Once youve found the le, click Open to add the reference to your project. 3. Choose View > Object Browser. Visual Basic displays the Object Browser dialog box. 4. Choose InDesign from the list of open libraries shown in the Project/Library menu. Visual Basic displays the objects that make up the InDesign object model. 5. Click an object class. Visual Basic displays the properties and methods of the object. For more information on a property or method, select the item; Visual Basic displays the denition of the item at the bottom of the Object Browser window.
AppleScript
To create an AppleScript script: 1. Locate and open the Apple Script Editor. 2. Enter the following script. The lines preceded by double dashes (--) are comments and are ignored by the scripting system. Theyre included to describe the operation of the program. As you look through the script, youll see how we create, then address, each object in turn. The AppleScript command tell species which object will receive the next message that we send.
23
--Hello World tell application "Adobe InDesign CS2" --Create a new document and assign its --identity to the variable "myDocument" set myDocument to make document tell myDocument --Create a new text frame on the first page. tell page 1 set myTextFrame to make text frame --Change the size of the text frame. set geometric bounds of myTextFrame to {"0p0", "0p0", "18p0", "18p0"} --Enter text in the text frame. set contents of myTextFrame to "Hello World!" end tell end tell end tell
3. Save the script. 4. Run the script (click Run in the Script Editor). InDesign creates a new publication, adds a text frame, and enters text. During this process, the Script Editor might ask where your copy of InDesign is located. In this case, select the application from the list of displayed applications, and the Script Editor will remember where it is the next time you run the script.
VBScript
To create a VBasic script: 1. Start any text editor (Notepad, for example). 2. Enter the following code. The lines preceded by Rem are comments and are ignored by the scripting system. Theyre included to describe the operation of the program. As you look through the script, youll see how we create, then address, each object in turn. You do not need to enter the comments.
Rem Hello World Set myInDesign = CreateObject("InDesign.Application.CS2") Rem Create a new document. Set myDocument = myInDesign.Documents.Add Rem Get a reference to the first page. Set myPage = myDocument.Pages.Item(1) Rem Create a text frame. Set myTextFrame = myDocument.TextFrames.Add Rem Specify the size and shape of the text frame. myTextFrame.GeometricBounds = Array("0p0", "0p0", "18p0", "18p0") Rem Enter text in the text frame. myTextFrame.Contents = "Hello World!"
3. Save the le as text only to the Scripts folder in the Presets folder inside your InDesign application folder. Give the le the le extension .vbs. 4. Display the Scripts palette, if its not already visible. Double-click the script name in the palette to run the script.
Visual Basic
To create a Visual Basic script (the steps shown are for Visual Basic 6; Visual Basic 5 CCE and Visual Basic.NET users will see slightly dierent dialog boxes): 1. Start Visual Basic and create a new project. Add the InDesign CS Type Library reference to the project, as shown earlier.
24
2. Use the CommandButton tool to create a new button on the default form. Double-click the button to open the Code window. 3. Enter the following code (between the Private Sub and End Sub lines dening the code under the button). The lines preceded by Rem are comments and are ignored by the scripting system. Theyre included to describe the operation of the program. As you look through the script, youll see how we create, then address, each object in turn. You do not need to enter the comments.
Rem Hello World Rem Declare variable types (optional if Option Explicit is off). Dim myInDesign As InDesign.Application Dim myDocument As InDesign.Document Dim myPage As InDesign.Page Dim myTextFrame As InDesign.TextFrame Rem End of variable type declarations. Set myInDesign = CreateObject("InDesign.Application.CS2") Rem Create a new document. Set myDocument = myInDesign.Documents.Add Rem Get a reference to the first page. Set myPage = myDocument.Pages.Item(1) Rem Create a text frame. Set myTextFrame = myDocument.TextFrames.Add Rem Specify the size and shape of the text frame. myTextFrame.GeometricBounds = Array("0p0", "0p0", "18p0", "18p0") Rem Enter text in the text frame. myTextFrame.Contents = "Hello World!"
4. Save the form. 5. Start InDesign. 6. Return to Visual Basic and run the program. 7. Click the button you created earlier. InDesign creates a new publication, creates a new text frame, and then enters the text.
JavaScript
To create a JavaScript: 1. Using any text editor (including InDesign or the ExtendScript Tookit), enter the following text:
//Hello World! var myDocument = app.documents.add(); with(myDocument){ var myPage = myDocument.pages.item(0); with(myPage){ //Create a new text frame and assign it to the variable "myTextFrame" var myTextFrame = textFrames.add(); //Specify the size and shape of the text frame. myTextFrame.geometricBounds = [ "0p0", "0p0", "18p0", "18p0"]; //Enter text in the text frame. myTextFrame.contents = "Hello World!" } }
2. Save the text as a plain text le with the le extension .jsx in the Scripts folder inside the Presets folder in your InDesign folder. 3. Test the script by double-clicking the script name in the InDesign Scripts palette.
25
Get the active document. Use a function (or handler in AppleScript). Get the page dimensions and page margins of the active publication. Resize a text frame. Change the formatting of the text in the text frame.
AppleScript
To create the script: 1. Make sure that you have the Hello World document open; if youve closed the document without saving it, simply run the previous script again to make a new Hello World document. 2. Choose File > New in the Script Editor to create a new script. 3. Enter the following code:
--Improved "Hello World" tell application "Adobe InDesign CS2" --Get a reference to a font. try --Enter the name of a font on your system, if necessary. set myFont to font "Helvetica" end try --Get the active document and assign the result to the variable "myDocument." set myDocument to active document tell myDocument --Use the handler "myGetBounds" to get the bounds of the --"live area" inside the margins of page 1. set myBounds to my myGetBounds(myDocument, page 1) tell text frame 1 of page 1 --Resize the text frame to match the page margins. set geometric bounds to myBounds tell paragraph 1 --Change the font, size, and paragraph alignment. try set applied font to myFont end try set point size to 72
26
set justification to center align end tell end tell end tell end tell --myGetBounds is a handler that returns the bounds of the "live area" of a page. on myGetBounds(myDocument, myPage) tell application "Adobe InDesign CS2" set myPageHeight to page height of document preferences of myDocument set myPageWidth to page width of document preferences of myDocument set myLeft to left of margin preferences of myPage set myTop to top of margin preferences of myPage set myRight to right of margin preferences of myPage set myBottom to bottom of margin preferences of myPage end tell set myRight to myLeft + (myPageWidth - (myRight + myLeft)) set myBottom to myTop + (myPageHeight - (myBottom + myTop)) return {myTop, myLeft, myBottom, myRight} end myGetBounds
VBScript
To create the script: 1. Start any text editor (Notepad, for example). 2. Make sure that you have the Hello World document open; if youve closed the document without saving it, simply run the previous script again to make a new Hello World document. 3. Enter the following code.
Rem Improved "Hello World" Set myInDesign = CreateObject("InDesign.Application.CS2") Rem Enter the name of a font on your system, if necessary. Set myFont = myInDesign.Fonts.Item("Arial") Set myDocument = myInDesign.ActiveDocument Set myPage = myDocument.Pages.Item(1) Rem Get page width and page height using the function "myGetBounds". myBounds = myGetBounds(myDocument, myPage) Set myTextFrame = myPage.TextFrames.Item(1) Rem Resize the text frame to match the publication margins. myTextFrame.GeometricBounds = myBounds Set myParagraph = myTextFrame.Paragraphs.Item(1) Rem Change the font, size, and alignment. If TypeName(myFont) <> "Nothing" Then myParagraph.AppliedFont = myFont End If myParagraph.PointSize = 48 myParagraph.Justification = idJustification.idLeftAlign Function myGetBounds(myDocument, myPage) myPageHeight = myDocument.DocumentPreferences.PageHeight myPageWidth = myDocument.DocumentPreferences.PageWidth myTop = myPage.MarginPreferences.Top myLeft = myPage.MarginPreferences.Left myRight = myPage.MarginPreferences.Right myBottom = myPage.MarginPreferences.Bottom myRight = myPageWidth - myRight myBottom = myPageHeight - myBottom myGetBounds = Array(myTop, myLeft, myBottom, myRight) End Function
27
4. Save the text as a plain text le with the le extension .vbs in the Scripts folder inside the Presets folder in your InDesign folder. 5. Run the new script by double-clicking the script name in the InDesign Scripts palette.
Visual Basic
To create the script: 1. Open the project you created for the Hello World script, if its not already open. 2. Make sure that you have the Hello World document open; if youve closed the document without saving it, simply run the previous script again to make a new Hello World document. 3. Add a new button to the form. 4. Double-click the button to display the Code window, then enter the following code:
Rem Improved "Hello World" Rem Declare variable types (optional if Option Explicit is off) Dim myInDesign As InDesign.Application Dim myDocument As InDesign.Document Dim myPage As InDesign.Page Dim myStory As InDesign.Story Dim myTextFrame As InDesign.TextFrame Rem End of variable type declarations. Set myInDesign = CreateObject("InDesign.Application.CS2") Rem Enter the name of a font on your system, if necessary. Set myFont = myInDesign.Fonts.Item("Arial") Set myDocument = myInDesign.ActiveDocument Set myPage = myDocument.Pages.Item(1) Rem Get page width and page height using the function "myGetBounds". myBounds = myGetBounds(myDocument, myPage) Set myTextFrame = myPage.TextFrames.Item(1) Rem Resize the text frame to match the publication margins. myTextFrame.GeometricBounds = myBounds Set myParagraph = myTextFrame.Paragraphs.Item(1) Rem Change the font, size, and alignment. If TypeName(myFont) <> "Nothing" Then myParagraph.AppliedFont = myFont End If myParagraph.PointSize = 48 myParagraph.Justification = idJustification.idLeftAlign
5. After the End Sub line, enter the following text to create a function.
Private Function myGetBounds(myDocument, myPage) Rem Declare variable types (optional if Option Explicit is turned off) Rem Omit if you are using VBSCript. Dim myPageHeight, myPageWidth, myTop, myLeft, myRight, myBottom As Double Rem End of variable declaractions. myPageHeight = myDocument.DocumentPreferences.PageHeight myPageWidth = myDocument.DocumentPreferences.PageWidth myTop = myPage.MarginPreferences.Top myLeft = myPage.MarginPreferences.Left myRight = myPage.MarginPreferences.Right myBottom = myPage.MarginPreferences.Bottom myRight = myPageWidth - myRight myBottom = myPageHeight - myBottom myGetBounds = Array(myTop, myLeft, myBottom, myRight) Rem If you are using VB.NET, replace the line above with the following: Rem myGetBounds = New Double(myTop, myLeft, myBottom, myRight) End Function
28
6. Save the form. 7. Click the button you created in Step 3 to run the new script.
JavaScript
To create the script: 1. Make sure that you have the Hello World document open; if youve closed the document without saving it, simply run the previous script again to make a new Hello World document. 2. Enter the following JavaScript in a new text le.
//Improved Hello World! //Enter the name of a font on your system, if necessary. myFont = app.fonts.item("Arial"); var myDocument = app.activeDocument with(myDocument){ var myPage = pages.item(0); var myBounds = myGetBounds(myPage,myDocument); with(myDocument.pages.item(0)){ //Get a reference to the text frame. var myTextFrame = textFrames.item(0); //Change the size of the text frame. myTextFrame.geometricBounds = myBounds; var myParagraph = myTextFrame.paragraphs.item(0); myParagraph.appliedFont = myFont; myParagraph.justification = Justification.leftAlign; myParagraph.pointZSize = 48; } } //myGetBounds calculates and return the bounds of the "live area" of the page. function myGetBounds(myPage, myDocument){ var array = new Array() var item = 0; with (myDocument.documentPreferences){ var myPageHeight = pageHeight; var myPageWidth = pageWidth; } with(myPage.marginPreferences){ var myX1 = left; var myY1 = top; var myY2 = bottom; var myX2 = right; } array[item++] = myY1; array[item++] = myX1; array[item++] = myPageHeight - myY2; array[item++] = myPageWidth - myX2; return array; }
3. Save the text as a plain text le with the le extension .jsx in the Scripts folder inside the Presets folder in your InDesign folder. 4. Run the new script by double-clicking the script name in the InDesign Scripts palette.
29
The dialog box object itself does not directly contain the controlsthats the purpose of the dialog column object. Dialog columns give you a way to control the positioning of controls within a dialog box. Inside dialog columns, you can further subdivide the dialog box into other dialog columns or border panels (both of which can, if necessary, contain further dialog columns and border panels). Border panel Static text Radiobutton group Radiobutton control Integer editbox Checkbox control Dialog column Dialog column Dialog column Dialog column
Dropdown
30
Like any other InDesign scripting object, each part of a dialog box has its own properties. A checkbox control, for example, has a property for its text (static label) and another property for its state (checked state). The dropdown control has a property for setting the list of options that appears on the controls menu (string list). To use a dialog box in your script, you create the dialog box object, populate it with various controls, display the dialog box, and then gather values from the dialog box controls to use in your script. Dialog boxes remain in InDesigns memory until they are destroyed. This means that you can keep a dialog box in memory and have data stored in its properties used by multiple scripts, but it also means that the dialog boxes take up memory and should be disposed of when they are not in use. In general, you should destroy the dialog box object before your script nishes execution.
AppleScript
1. Enter the following AppleScript in your script editor.
--Simple User Interface Example tell application "Adobe InDesign CS2" activate set myDocument to make document set myDialog to make dialog tell myDialog set name to "Simple User Interface Example Script" set myDialogColumn to make dialog column tell myDialogColumn --Create a text entry field. set myTextEditField to make text editbox with properties {edit contents:"Hello World!", min width:180} --Create a number (real) entry field. set myPointSizeField to make real editbox with properties {edit contents:"72"} end tell show --Get the settings from the dialog box. --Get the point size from the point size field. set myPointSize to edit contents of myPointSizeField as real --Get the example text from the text edit field. set myString to edit contents of myTextEditField --Remove the dialog box from memory. destroy myDialog end tell tell page 1 of myDocument --Create a text frame. set myTextFrame to make text frame set geometric bounds of myTextFrame to my myGetBounds(myDocument, page 1 of myDocument) --Apply the settings from the dialog box to the text frame. set contents of myTextFrame to myString --Set the point size of the text in the text frame. set point size of text 1 of myTextFrame to myPointSize end tell end tell on myGetBounds(myDocument, myPage) tell application "Adobe InDesign CS2" set myPageHeight to page height of document preferences of myDocument
31
set myPageWidth to page width of document preferences of myDocument set myLeft to left of margin preferences of myPage set myTop to top of margin preferences of myPage set myRight to right of margin preferences of myPage set myBottom to bottom of margin preferences of myPage end tell set myRight to myLeft + (myPageWidth - (myRight + myLeft)) set myBottom to myTop + (myPageHeight - (myBottom + myTop)) return {myTop, myLeft, myBottom, myRight} end myGetBounds
2. Save the text as a compiled script in the Scripts folder inside the Presets folder in your InDesign folder. 3. Test the script by double-clicking the script name in the InDesign Scripts palette, or run it from your script editor.
VBScript
1. Enter the following VBScript using any text editor.
Rem Simple User Interface Example Set myInDesign = CreateObject("InDesign.Application.CS2") Set myDialog = myInDesign.Dialogs.Add myDialog.CanCancel = True myDialog.Name = " Simple User Interface Example Script" Set myDialogColumn = myDialog.DialogColumns.Add Set myTextEditField = myDialogColumn.TextEditboxes.Add myTextEditField.EditContents = "Hello World!" myTextEditField.MinWidth = 180 Rem Create a number (real) entry field. Set myPointSizeField = myDialogColumn.RealEditboxes.Add myPointSizeField.EditValue = 72 myDialog.Show Rem Get the values from the dialog box controls. myString = myTextEditField.EditContents myPointSize = myPointSizeField.EditValue Rem Remove the dialog box from memory. myDialog.Destroy Rem Create a new document. Set myDocument = myInDesign.Documents.Add Set myTextFrame = myDocument.Pages.Item(1).TextFrames.Add Rem Resize the text frame to the "live" area of the page (using the function "myGetBounds"). myBounds = myGetBounds(myDocument, myDocument.Pages.Item(1)) myTextFrame.GeometricBounds = myBounds Rem Enter the text from the dialog box in the text frame. myTextFrame.Contents = myString Rem Set the size of the text to the size you entered in the dialog box. myTextFrame.Texts.Item(1).PointSize = myPointSize Rem Function for getting the bounds of the "live area" Function myGetBounds(myDocument, myPage) myPageHeight = myDocument.DocumentPreferences.PageHeight myPageWidth = myDocument.DocumentPreferences.PageWidth myTop = myPage.MarginPreferences.Top myLeft = myPage.MarginPreferences.Left myRight = myPage.MarginPreferences.Right myBottom = myPage.MarginPreferences.Bottom myRight = myPageWidth - myRight myBottom = myPageHeight - myBottom myGetBounds = Array(myTop, myLeft, myBottom, myRight) End Function
2. Save the text as a plain text le with the le extension .vbs in the Scripts folder inside the Presets folder in your InDesign folder. 3. Test the script by double-clicking the script name in the InDesign Scripts palette.
32
JavaScript
1. Enter the following JavaScript using any text editor or the ExtendScript Toolkit.
//Simple User Interface Example var myDialog = app.dialogs.add({name:"Simple User Interface Example Script",canCancel:true}); with(myDialog){ //Add a dialog column. with(dialogColumns.add()){ //Create a text edit field. var myTextEditField = textEditboxes.add({editContents:"Hello World!", minWidth:180}); //Create a number (real) entry field. var myPointSizeField = realEditboxes.add({editValue:72}); } } //Display the dialog box. var myResult = myDialog.show(); if(myResult == true){ //Get the values from the dialog box controls. var myString = myTextEditField.editContents; var myPointSize = myPointSizeField.editValue; //Remove the dialog box from memory. myDialog.destroy(); //Create a new document. var myDocument = app.documents.add() with(myDocument){ //Create a text frame. var myTextFrame = pages.item(0).textFrames.add(); //Resize the text frame to the "live" area of the page (using the function "myGetBounds"). var myBounds = myGetBounds(myDocument, myDocument.pages.item(0)); myTextFrame.geometricBounds=myBounds; //Enter the text from the dialog box in the text frame. myTextFrame.contents=myString; //Set the size of the text to the size you entered in the dialog box. myTextFrame.texts.item(0).pointSize = myPointSize; } } else{ //User clicked Cancel, so remove the dialog box from memory. myDialog.destroy(); } function myGetBounds(myDocument, myPage){ with(myDocument.documentPreferences){ var myPageHeight = pageHeight; var myPageWidth = pageWidth; } with(myPage.marginPreferences){ var myTop = top; var myLeft = left; var myRight = right; var myBottom = bottom; } myRight = myPageWidth - myRight; myBottom = myPageHeight- myBottom; return [myTop, myLeft, myBottom, myRight]; }
2. Save the text as a plain text le with the le extension .jsx in the Scripts folder inside the Presets folder in your InDesign folder. 3. Test the script by double-clicking the script name in the InDesign Scripts palette.
33
AppleScript
1. Enter the following AppleScript in your script editor.
--Complex User Interface Example tell application "Adobe InDesign CS2" activate set myDocument to make document set myDialog to make dialog --This example dialog box uses border panels and dialog columns to --separate and organize the user interface items in the dialog. tell myDialog set name to "User Interface Example Script" set myDialogColumn to make dialog column tell myDialogColumn set myBorderPanel to make border panel tell myBorderPanel set myDialogColumn to make dialog column tell myDialogColumn make static text with properties {static label:"Message:"} end tell set myDialogColumn to make dialog column tell myDialogColumn set myTextEditField to make text editbox with properties {edit contents:"Hello World!", min width:180} end tell end tell set myBorderPanel to make border panel tell myBorderPanel set myDialogColumn to make dialog column tell myDialogColumn make static text with properties {static label:"Point Size:"} end tell set myDialogColumn to make dialog column tell myDialogColumn set myPointSizeField to make real editbox with properties {edit contents:"72"} end tell end tell set myBorderPanel to make border panel tell myBorderPanel set myDialogColumn to make dialog column
34
tell myDialogColumn make static text with properties {static label:"Vertical Justification:"} end tell set myDialogColumn to make dialog column tell myDialogColumn set myVerticalJustificationMenu to make dropdown with properties {string list:{"Top", "Center", "Bottom"}, selected index:0} end tell end tell set myBorderPanel to make border panel tell myBorderPanel make static text with properties {static label:"Paragraph Alignment:"} set myParagraphAlignmentGroup to make radiobutton group tell myParagraphAlignmentGroup set myLeftRadioButton to make radiobutton control with properties {static label:"Left", checked state:true} set myCenterRadioButton to make radiobutton control with properties {static label:"Center"} set myRightRadioButton to make radiobutton control with properties {static label:"Right"} end tell end tell end tell show --Get the settings from the dialog box. --Get the point size from the point size field. set myPointSize to edit contents of myPointSizeField as real --Get the example text from the text edit field. set myString to edit contents of myTextEditField --Get the vertical justification setting from the pop-up menu. if selected index of myVerticalJustificationMenu is 0 then set myVerticalJustification to top align else if selected index of myVerticalJustificationMenu is 1 then set myVerticalJustification to center align else set myVerticalJustification to bottom align end if --Get the paragraph alignment setting from the radiobutton group. get properties of myParagraphAlignmentGroup if selected button of myParagraphAlignmentGroup is 0 then set myParagraphAlignment to left align else if selected button of myParagraphAlignmentGroup is 1 then set myParagraphAlignment to center align else set myParagraphAlignment to right align end if --Remove the dialog box from memory. destroy myDialog end tell tell page 1 of myDocument set myTextFrame to make text frame set geometric bounds of myTextFrame to my myGetBounds(myDocument, page 1 of myDocument) --Apply the settings from the dialog box to the text frame. set contents of myTextFrame to myString --Apply the vertical justification setting. set vertical justification of text frame preferences of myTextFrame to myVerticalJustification --Apply the paragraph alignment ("justification"). --"text 1 of myTextFrame" is all of the text in the text frame. set justification of text 1 of myTextFrame to myParagraphAlignment --Set the point size of the text in the text frame. set point size of text 1 of myTextFrame to myPointSize end tell end tell on myGetBounds(myDocument, myPage) tell application "Adobe InDesign CS2" set myPageHeight to page height of document preferences of myDocument set myPageWidth to page width of document preferences of myDocument
35
set myLeft to left of margin preferences of myPage set myTop to top of margin preferences of myPage set myRight to right of margin preferences of myPage set myBottom to bottom of margin preferences of myPage end tell set myRight to myLeft + (myPageWidth - (myRight + myLeft)) set myBottom to myTop + (myPageHeight - (myBottom + myTop)) return {myTop, myLeft, myBottom, myRight} end myGetBounds
2. Save the text as a compiled script in the Scripts folder inside the Presets folder in your InDesign folder. 3. Test the script by double-clicking the script name in the InDesign Scripts palette, or run it from your script editor.
VBScript
1. Enter the following VBScript using any text editor.
Rem Complex User Interface Example Set myInDesign = CreateObject("InDesign.Application.CS2") myInDesign.Activate Set myDialog = myInDesign.Dialogs.Add myDialog.CanCancel = True myDialog.Name = "User Interface Example Script" Rem Create a dialog column. Set myDialogColumn = myDialog.DialogColumns.Add Rem Create a border panel. Set myBorderPanel = myDialogColumn.BorderPanels.Add Rem Create a dialog column inside the border panel. Set myTempDialogColumn = myBorderPanel.DialogColumns.Add Set myStaticText = myTempDialogColumn.StaticTexts.Add myStaticText.StaticLabel = "Message:" Rem Create another dialog column inside the border panel. Set myTempDialogColumn = myBorderPanel.DialogColumns.Add Set myTextEditField = myTempDialogColumn.TextEditboxes.Add myTextEditField.EditContents = "Hello World!" myTextEditField.MinWidth = 180 Rem Create another border panel. Set myBorderPanel = myDialogColumn.BorderPanels.Add Rem Create a dialog column inside the border panel. Set myTempDialogColumn = myBorderPanel.DialogColumns.Add Set myStaticText = myTempDialogColumn.StaticTexts.Add myStaticText.StaticLabel = "Point Size:" Rem Create another dialog column inside the border panel. Set myTempDialogColumn = myBorderPanel.DialogColumns.Add Set myPointSizeField = myTempDialogColumn.RealEditboxes.Add myPointSizeField.EditValue = 72 Rem Create another border panel. Set myBorderPanel = myDialogColumn.BorderPanels.Add Rem Create a dialog column inside the border panel. Set myTempDialogColumn = myBorderPanel.DialogColumns.Add Set myStaticText = myTempDialogColumn.StaticTexts.Add myStaticText.StaticLabel = "Vertical Justification:" Rem Create another dialog column inside the border panel. Set myTempDialogColumn = myBorderPanel.DialogColumns.Add Set myVerticalJustificationMenu = myTempDialogColumn.Dropdowns.Add myVerticalJustificationMenu.StringList = Array("Top", "Center", "Bottom") myVerticalJustificationMenu.SelectedIndex = 0 Rem Create another border panel. Set myBorderPanel = myDialogColumn.BorderPanels.Add Rem Create a dialog column inside the border panel. Set myTempDialogColumn = myBorderPanel.DialogColumns.Add Set myStaticText = myTempDialogColumn.StaticTexts.Add myStaticText.StaticLabel = "Paragraph Alignment:" Rem Create another dialog column inside the border panel.
36
Set myTempDialogColumn = myBorderPanel.DialogColumns.Add Set myRadioButtonGroup = myTempDialogColumn.RadiobuttonGroups.Add Set myLeftRadioButton = myRadioButtonGroup.RadiobuttonControls.Add myLeftRadioButton.StaticLabel = "Left" myLeftRadioButton.CheckedState = True Set myCenterRadioButton = myRadioButtonGroup.RadiobuttonControls.Add myCenterRadioButton.StaticLabel = "Center" Set myRightRadioButton = myRadioButtonGroup.RadiobuttonControls.Add myRightRadioButton.StaticLabel = "Right" Rem If the user clicked OK, then create the example document. If myDialog.Show = True Then Rem Get the values from the dialog box controls. myString = myTextEditField.EditContents myPointSize = myPointSizeField.EditValue Rem Create a new document. Set myDocument = myInDesign.Documents.Add Set myTextFrame = myDocument.Pages.Item(1).TextFrames.Add Rem Resize the text frame to the "live" area of the page (using the function "myGetBounds"). myBounds = myGetBounds(myDocument, myDocument.Pages.Item(1)) myTextFrame.GeometricBounds = myBounds Rem Enter the text from the dialog box in the text frame. myTextFrame.Contents = myString Rem Set the size of the text to the size you entered in the dialog box. myTextFrame.Texts.Item(1).PointSize = myPointSize Rem Set the vertical justification of the text frame to the dialog menu choice. Select Case myVerticalJustificationMenu.SelectedIndex Case 0 myTextFrame.TextFramePreferences.VerticalJustification = idVerticalJustification.idTopAlign Case 1 myTextFrame.TextFramePreferences.VerticalJustification = idVerticalJustification.idCenterAlign Case Else myTextFrame.TextFramePreferences.VerticalJustification = idTopAlign.idBottomAlign End Select Rem set the paragraph alignment of the text to the dialog radio button choice. Select Case myRadioButtonGroup.SelectedButton Case 0 myTextFrame.Texts.Item(1).Justification = idJustification.idLeftAlign Case 1 myTextFrame.Texts.Item(1).Justification = idJustification.idCenterAlign Case Else myTextFrame.Texts.Item(1).Justification = idJustification.idRightAlign End Select Rem Remove the dialog box from memory. myDialog.Destroy End If Rem Function for getting the bounds of the "live area" Function myGetBounds(myDocument, myPage) myPageHeight = myDocument.DocumentPreferences.PageHeight myPageWidth = myDocument.DocumentPreferences.PageWidth myTop = myPage.MarginPreferences.Top myLeft = myPage.MarginPreferences.Left myRight = myPage.MarginPreferences.Right myBottom = myPage.MarginPreferences.Bottom myRight = myPageWidth - myRight myBottom = myPageHeight - myBottom myGetBounds = Array(myTop, myLeft, myBottom, myRight) End Function
2. Save the text as a plain text le with the le extension .vbs in the Scripts folder inside the Presets folder in your InDesign folder. 3. Test the script by double-clicking the script name in the InDesign Scripts palette.
37
JavaScript
1. Enter the following JavaScript using any text editor.
//Complex User Interface Example //Create a dialog. var myDialog = app.dialogs.add({name:"User Interface Example Script", canCancel:true}); with(myDialog){ //Add a dialog column. with(dialogColumns.add()){ //Create a border panel. with(borderPanels.add()){ with(dialogColumns.add()){ //The following line shows how to set a property as you create an object. staticTexts.add({staticLabel:"Message:"}); } with(dialogColumns.add()){ //The following line shows how to set multiple properties as you create an object. var myTextEditField = textEditboxes.add({editContents:"Hello World!", minWidth:180}); } } //Create another border panel. with(borderPanels.add()){ with(dialogColumns.add()){ staticTexts.add({staticLabel:"Point Size:"}); } with(dialogColumns.add()){ //Create a number entry field. Note that this field uses editValue //rather than editText (as a textEditBox would). var myPointSizeField = realEditboxes.add({editValue:72}); } } //Create another border panel. with(borderPanels.add()){ with(dialogColumns.add()){ staticTexts.add({staticLabel:"Vertical Justification:"}); } with(dialogColumns.add()){ //Create a pop-up menu ("dropdown") control. var myVerticalJustificationMenu = dropdowns.add({stringList:["Top", "Center", "Bottom"], selectedIndex:0}); } } //Create another border panel. with(borderPanels.add()){ staticTexts.add({staticLabel:"Paragraph Alignment:"}); var myRadioButtonGroup = radiobuttonGroups.add(); with(myRadioButtonGroup){ var myLeftRadioButton = radiobuttonControls.add({staticLabel:"Left", checkedState: true}); var myCenterRadioButton = radiobuttonControls.add({staticLabel:"Center"}); var myRightRadioButton = radiobuttonControls.add({staticLabel:"Right"}); } } } } //Display the dialog box. if(myDialog.show() == true){ var myParagraphAlignment, myString, myPointSize, myVerticalJustification; //If the user didnt click the Cancel button, //then get the values back from the dialog box. //Get the example text from the text edit field. myString = myTextEditField.editContents //Get the point size from the point size field. myPointSize = myPointSizeField.editValue; //Get the vertical justification setting from the pop-up menu.
38
if(myVerticalJustificationMenu.selectedIndex == 0){ myVerticalJustification = VerticalJustification.topAlign; } else if(myVerticalJustificationMenu.selectedIndex == 1){ myVerticalJustification = VerticalJustification.centerAlign; } else{ myVerticalJustification = VerticalJustification.bottomAlign; } //Get the paragraph alignment setting from the radiobutton group. if(myRadioButtonGroup.selectedButton == 0){ myParagraphAlignment = Justification.leftAlign; } else if(myRadioButtonGroup.selectedButton == 1){ myParagraphAlignment = Justification.centerAlign; } else{ myParagraphAlignment = Justification.rightAlign; } myDialog.destroy(); //Now create the document and apply the properties to the text. var myDocument = app.documents.add(); with(myDocument){ var myPage = pages[0]; with(myPage){ //Create a text frame. var myTextFrame = pages.item(0).textFrames.add(); with(myTextFrame){ //Set the geometric bounds of the frame using the "myGetBounds" function. geometricBounds = myGetBounds(myDocument, myPage); //Set the contents of the frame to the string you entered in the dialog box. contents = myString; //Set the alignment of the paragraph. texts.item(0).justification = myParagraphAlignment; //Set the point size of the text. texts.item(0).pointSize = myPointSize; //Set the vertical justification of the text frame. textFramePreferences.verticalJustification = myVerticalJustification; } } } } else{ myDialog.destroy() } //Utility function for getting the bounds of the "live area" of a page. function myGetBounds(myDocument, myPage){ with(myDocument.documentPreferences){ var myPageHeight = pageHeight; var myPageWidth = pageWidth; } with(myPage.marginPreferences){ var myTop = top; var myLeft = left; var myRight = right; var myBottom = bottom; } myRight = myPageWidth - myRight; myBottom = myPageHeight- myBottom; return [myTop, myLeft, myBottom, myRight]; }
2. Save the text as a plain text le with the le extension .jsx in the Scripts folder inside the Presets folder in your InDesign folder. 3. Test the script by double-clicking the script name in the InDesign Scripts palette.
39
Handling errors
Imagine that youve written a script that formats the current text selection. What should the script do if the current selection turns out not to be text at all, but a rectangle, oval, or polygon? Error handling is code that you add to your script to respond to conditions other than those that you expect it to encounter. If you have complete control over the situations in which your script will run, then you don't need error handling. If not, however, you should add error handling capabilities to your script. The following examples show how you can stop a script when no objects are selected in InDesign.
AppleScript
tell application "Adobe InDesign CS2" --First, check to see whether any InDesign documents are open. --If no documents are open, display an error message. if (count documents) is not equal to 0 then set mySelection to selection if (count mySelection) is not equal to 0 then --Something is selected. If this were a real script, you would --now do something with the object or objects in the selection. display dialog "You have " & (count mySelection) & " items selected." else --No objects were selected, so display an error message. display dialog "No InDesign objects are selected. Please select an object and try again." end if else --No documents were open, so display an error message. display dialog "No InDesign documents are open. Please open a document and try again." end if end tell
VBScript
Set myInDesign = CreateObject("InDesign.Application.CS2") Rem First, check to see whether any InDesign documents are open. Rem If no documents are open, display an error message. If myInDesign.Documents.Count <> 0 Then If myInDesign.Selection.Count > 0 Then Rem Something is selected. If this were a real script, you would Rem now do something with the object or objects in the selection. MsgBox "You have " & CStr(myInDesign.Selection.Count) & " items selected." Else Rem Nothing is selected, so display an error message. MsgBox "No InDesign objects are selected. Please select an object and try again." End If Else Rem No documents are open, so display an error message. MsgBox "No InDesign documents are open. Please open a file and try again." End If
JavaScript
//First, check to see whether any InDesign documents are open. //If no documents are open, display an error message. if (app.documents.length > 0){ if (app.selection.length > 0) { //Something is selected. If this were a real script, you would //now do something with the object or objects in the selection. alert("You have " + app.selection.length + " items selected.") } else { //Nothing is selected, so display an error message. alert("Nothing is selected. Please select an object and try again.") }
40
} else { //No documents are open, so display an error message. alert("No InDesign documents are open. Please open a document and try again.") }
You can also use JavaScripts trycatch statement for error handling, as shown in the example below:
//Display the type of the first item in the selection. try { myObjectType = app.selection[0].constructor.name; alert("The first selected item is a " + myObjectType + " object."); } catch (e){ if (app.documents.length == 0){ //No documents are open, so display an error message. alert("No InDesign documents are open. Please open a document and try again."); } else { if (app.selection.length == 0){ //Nothing is selected, so display an error message. alert("Nothing is selected. Please select an object and try again."); } else{ alert("An error occurred, but Im not sure what it was."); } } }
If the Scripts palette is not available, its because the plug-in is not installed or has been disabled. Use the plug-in manager to enable the plug-in, or reinstall the Scripts palette. If you want to run a JavaScript in InDesign, you must have the Scripts palette installed. Here are some common actions using the Scripts palette:
To add a script to the Scripts palette, put the script into the Scripts folder inside the Presets folder in your InDesign folder. You can run compiled or uncompiled AppleScripts, JavaScripts (.jsx), VBScripts (.vbs), or executable programs from the Scripts palette. You can also put le aliases (Mac OS) or shortcuts (Windows) to les or folders in this folder. When you return to InDesign, the le names of the script les (or folders) that you placed in the folder appear in the Scripts palette. To run a script from the Scripts palette, double-click the name of the script in the palette. Scripts run from the Scripts palette run faster than scripts run from the Finder (Mac OS) or Explorer (Windows). When you
41
run a script using the Scripts palette, InDesign suppresses screen drawing until the script has nished. To view the script actions as they execute, choose Enable Redraw from the Scripts palette menu.
To edit a script shown in the Scripts palette, hold down Option (Mac OS) or Alt (Windows) and double-click the scripts name. This opens the script in the editor youve dened for the le type. To open the folder containing a script shown in the Scripts palette, hold down Command (Mac OS) or Ctrl (Windows) and double-click the scripts name, or choose Reveal in Finder (Mac OS) or Reveal in Explorer (Windows) from the Scripts palette menu. The folder containing the script opens in the Finder (Mac OS) or Explorer (Windows). To open a JavaScript in the ExtendScript Toolkit debugger, hold down Shift as you double-click the script's name in the Scripts palette. See Chapter 4, Using ExtendScript Tools and Features, for more information. To add a keyboard shortcut for a script, choose Edit > KeyboardShortcuts, select an editable shortcut set from the Set menu, then select Scripts from the Product Area menu. A list of the scripts in your Scripts palette appears. Select a script and assign a keyboard shortcut as you would for any other InDesign feature.
If the Script Label palette is not available, its because the plug-in is not installed or has been disabled. Use the plug-in manager to enable the plug-in, or reinstall the palette. Access the plug-in manager using Help > Congure Plug-Ins in Windows or InDesign > Congure Plug-Ins in Mac OS . The following examples show how to get a reference to a page item with a specic label.
AppleScript
--Given a reference to a page "myPage" containing a text frame with the label "myTargetFrame" tell myPage set myTextFrame to text frame "myTargetFrame" end if
VBScript
Rem Given a reference to a page "myPage" containing a text frame with the label "myTargetFrame" Set myTextFrame = myPage.TextFrames.Item("myTargetFrame")
JavaScript
// Assuming that the first page of the active document contains // a text frame with the label "myTargetFrame" with(app.documents.item(0).pages.item(0)){ myTargetFrame = textFrames.item("myTargetFrame"); }
42
AppleScript debugging
The Apple Script Editor application doesnt have extensive debugging tools, but it does have the AppleScript Event Log Window. To watch your script send commands to and receive information from InDesign: 1. Choose Controls > Open Event Log. The Script Editor displays the Event Log window. 2. Turn on the Show Events and Show Events Results options. 3. Run your script. As the script executes, youll see the commands sent to InDesign, and the InDesign responses. In addition, the Result window (choose Controls > Show Result) displays the value returned from the most recent script statement. Third-party AppleScript editors, such as Script Debugger (from Late Night Software: www.latenightsw.com) oer more debugging features than the Apple Script Editor. If you will be writing more than a few simple scripts, we recommend that you acquire a script editor with better script debugging capabilities.
VBScript debugging
You can debug your VBScript using a Visual Basic debugger. In Visual Basic, you can stop your script at any point and step through the script one line at a time. You can also observe the values of variables dened in your script using the Watch and Locals windowstwo valuable tool for debugging your scripts. To view a variable in the Watch window: 1. Select the variable and choose Debug > Quick Watch. Visual Basic displays the Quick Watch dialog box. 2. Click Add. Visual Basic displays the Watch window. 3. To stop your script at a particular line (so that you can look at the Watch window), select the line and choose Debug > Toggle Breakpoint. When you run the script, Visual Basic stops at the breakpoint you set, and you can look at the values in your variables (if youve hidden the Watch window, you can display it again by choosing View > Watch Window). 4. Choose one of the following continuation options:
To execute the next line of your script, choose Debug > Step Into (or press F8 in Visual Basic 6 or F11 in Visual Basic.NET). To continue normal execution of the script, choose Run > Start (or press F5) in Visual Basic 6 or Debug > Start (or press F5) in Visual Basic.NET.
JavaScript debugging
JavaScript debugging is described in Chapter 4, Using ExtendScript Tools and Features.
43
The ExtendScript Toolkit , an interactive development and testing environment for ExtendScript. A global debugging object, the Dollar ($) Object. A reporting utility for ExtendScript elements, the ExtendScript Reection Interface. A localization utility for providing user-interface string values in dierent languages. See the Localizing ExtendScript Strings section. Global functions for displaying short messages in dialog boxes; see the User Notication Helper Functions section. An object type for specifying measurement values together with their units. See the Specifying Measurement Values section. Tools for combining scripts, such as a #include directive, and import and export statements. See the Modular Programming Support section. Support for extending or overriding math and logical operator behavior on a class-by-class basis. See the Operator Overloading section.
ExtendScript provides a common scripting environment for all Adobe Creative Suite 2 applications, and allows interapplication communication through scripts.
To identify specic Adobe Creative Suite 2 applications, scripts must use application and namespace speciers as described in the Application and namespace speciers section. Applications can run scripts automatically on startup. See the Script Locations and Checking Application Installation section. For details about interapplication communication, see the Bridge JavaScript Reference, available with Adobe Creative Suite 2.
44
Single-step through JavaScripts inside a CS2 application. Inspect all data for a running script. Set and execute breakpoints.
The Toolkit is the default editor for ExtendScript les, which use the extension .jsx. You can use the Toolkit to edit or debug scripts in JS or JSX les. When you double-click a JSX le in the platforms windowing environment, the script runs in the Toolkit, unless it species a particular target application using the #target directive. For more information, see the Selecting a debugging target and Preprocessor directives sections.
Destination pane is highlighted, and the new tab is added to the tab stack
If you drag a tab so that the entire destination pane is highlighted, it becomes another stacked tab in that pane. If you drag a tab to the top or bottom of a pane (so that only the top or bottom bar of the destination pane is highlighted), that pane splits to show the tabs in a tiled format.
45
Each tab has a yout menu, accessed through the arrow icon in the upper right corner. The same menu is available as a context menu, which you invoke with a right click in the tab. This menu always includes a Hide Pane command to hide that pane. Use the Window menu to show a hidden pane, or to bring it to the front. The Editor, which has a tab for each script, has an additional context menu for debugging, which appears when you right-click in the line numbers area. The Toolkit saves the current layout when you exit, and restores it at the next startup. It also saves and restores the open documents , the current positions within the documents, and any breakpoints that have been set.
If you do not want to restore all settings on startup, hold shift while the Toolkit loads to restore default settings. This reconnects to the last application and engine that was selected. If you want to restore the layout settings on startup, but not load the previously open documents, choose Start with a clean workspace in the Preferences dialog.
46
running halted waiting The current engine is the one whose data and state is displayed in the Toolkits panes. If an application has only one engine, its engine becomes current when you select the application as the target. If there is more than one engine available in the target application, you can select an engine in the list to make it current. When you open the Toolkit, it attempts to reconnect to the same target and engine that was set last time it closed. If that target application is not running, the Toolkit prompts for permission to launch it. If permission is refused, the Toolkit itself becomes the target application. If the target application that you select is not running, the Toolkit prompts for permission and launches the application. Similarly, if you run a script that species a target application that is not running (using the #target directive), the Toolkit prompts for permission to launch it. If the application is running but not selected as the current target, the Toolkit prompts you to switch to it. If you select an application that cannot be debugged in the Toolkit (such as Adobe Help), an error dialog reports that the Toolkit cannot connect to the selected application. The ExtendScript Toolkit is the default editor for JSX les. If you double-click a JSX le in a le browser, the Toolkit looks for a #target directive in the le and launches that application to run the script; however, it rst checks for syntax errors in the script. If any are found, the Toolkit displays the error in a message box and quits silently, rather than launching the target application. For example:
Selecting scripts
The Scripts tab oers a list of debuggable scripts for the target application, which can be JS or JSX les or (for some applications) HTML les that contain embedded scripts.
Select a script in this tab to load it and display its contents in the editor pane, where you can modify it, save it, or run it within the target application.
47
Tracking data
The Data Browser tab is your window into the JavaScript engine. It displays all live data dened in the current context, as a list of variables with their current values. If execution has stopped at a breakpoint, it shows variables that have been dened using var in the current function, and the function arguments. To show variables dened in the global or calling scope, use the Call Stack to change the context (see The call stack). You can use the Data Browser to examine and set variable values.
Click a variable name to show its current value in the edit eld at the top of the tab. To change the value, enter a new value and press enter. If a variable is read-only, the edit eld is disabled.
The yout menu for this tab lets you control the amount of data displayed:
Show Global Functions toggles the display of all global function denitions. Show Object Methods toggles the display of all functions that are attached to objects. Most often, the interesting data in an object are its callable methods. Show JavaScript Language Elements toggles the display of all data that is part of the JavaScript language standard, such as the Array constructor or the Math object. An interesting property is the _ _ proto _ _ property, which reveals the JavaScript object prototype chain.
Each variable has a small icon that indicates the data type. An invalid object is a reference to an object that has been deleted. If a variable is undened, it does not have an icon. null Boolean Number String Object Invalid object You can inspect an object's content by clicking its icon. The list expands to show the objects properties (and methods, if Show Object Methods is enabled); the triangle points down to indicate that the object is open. Note: In Photoshop CS2, the Data Browser pane is populated only during the debugging of a JavaScript program within Photoshop.
48
The command line entry eld accepts any JavaScript code, and you can use it to evaluate expressions or call functions. Enter any JavaScript statement on the command line and execute it by pressing Enter. The statement executes within the stack scope of the line highlighted in the Call Stack tab, and the result appears in the output eld.
The command line input eld keeps a command history of 32 lines. Use the Up and Down Arrow keys to scroll through the previous entries. Commands entered in this eld execute with a timeout of one second. If a command takes longer than one second to execute, the Toolkit generates a timeout error and terminates the attempt.
The output eld is standard output for JavaScript execution. If any script generates a syntax error, the error is displayed here along with the le name and the line number. The Toolkit displays errors here during its own startup phase. The tabs yout menu allows you to clear the contents of the output eld and change the size of the font used for output.
The function containing the breakpoint is highlighted in both the Call Stack and the Editor tabs. You can click any function in the call hierarchy to inspect it. In the Editor, the line containing the function call that led to that point of execution is marked with a green background. In the example, when you select the line [Top Level] in the call stack, the Editor highlights the line where the dayOfWeek function was called.
49
Switching between the functions in the call hierarchy allows you to trace how the current function was called. The Console and Data Browser tabs coordinate with the Call Stack pane. When you select a function in the Call Stack:
The Console pane switches its scope to the execution context of that function , so you can inspect and modify its local variables. These would otherwise be inaccessible to the running JavaScript program from within a called function. The Data Browser pane displays all data dened in the selected context.
50
Right arrow Up arrow Down arrow Page up Page down Ctrl + Up arrow Ctrl + Down arrow Ctrl + Page up Ctrl + page down Ctrl + Left arrow Ctrl + right arrow Home End Ctrl + Home Ctrl + End
Move insertion point right one character Move insertion point up one line; stay in column if possible Move insertion point down one line; stay in column if possible Move insertion point one page up Move insertion point one page down Scroll up one line without moving the insertion point Scroll down one line without moving the insertion point Scroll one page up without moving the insertion point Scroll one page down without moving the insertion point Move insertion point one word to the left Move insertion point one word to the right Move insertion point to start of line Move insertion point to end of line Move insertion point to start of text Move insertion point to end of text
The editor supports extended keyboard input via IME (Windows) or TMS (Mac OS). This is especially important for Far Eastern characters.
Syntax checking
Before running the new script or saving the text as a script le, you can check whether the text contains JavaScript syntax errors. Choose Check Syntax from the Edit menu or from the Editors right-click context menu.
If the script is syntactically correct, the status line shows "No syntax errors". If the Toolkit nds a syntax error, such as a missing quote, it highlights the aected text, plays a sound, and shows the error message in the status line so you can x the error.
51
the variables and functions are already known to the JavaScript engine. During debugging, however, this is an extremely useful way to display the current value of a variable, along with its current data type. You can turn o the display of help tips using the Display JavaScript variables and Enable UI help tips checkboxes on the Help Options page of the Preferences dialog.
Step Over
Step Into
Step Out
Shift+F11 (Windows) When paused within the body of a JavaScript function, resumes script execution until the function returns. Ctrl+U (Mac OS) When paused outside the body of a function, resumes script execution until the script terminates.
When the execution of a script halts because the script reached a breakpoint, or when the script reaches the next line when stepping line by line, the Editor displays the current script with the current line highlighted in yellow.
52
If the script encounters a runtime error, the Toolkit halts the execution of the script, displays the current script with the current line highlighted in red, displays the error message in the status line, and plays a sound.
Scripts often use a try/catch clause to execute code that may cause a runtime error, in order to catch the error programmatically rather than have the script terminate. You can choose to allow regular processing of such errors using the catch clause, rather than breaking into the debugger. To set this behavior, choose Debug > Dont Break On Guarded Exceptions. Some runtime errors, such as Out Of Memory, always cause the termination of the script, regardless of this setting.
Setting breakpoints
When debugging a script, it is often helpful to make it stop at certain lines so that you can inspect the state of the environment, whether function calls are nested properly, or whether all variables contain the expected data.
To stop execution of a script at a given line, click to the left of the line number to set a breakpoint. A lled dot indicates the breakpoint. Click a second time to temporarily disable the breakpoint; the icon changes to an outline. Click a third time to delete the breakpoint. The icon is removed.
Some breakpoints need to be conditional. For example, if you set a breakpoint in a loop that is executed several thousand times, you would not want to have the program stop each time through the loop, but only on each 1000th iteration. You can attach a condition to a breakpoint, in the form of a JavaScript expression. Every time execution reaches the breakpoint, it runs the JavaScript expression. If the expression evaluates to a nonzero number or true, execution stops. To set a conditional breakpoint in a loop, for example, the conditional expression could be i >= 1000, which means that the program execution halts if the value of the iteration variable i is equal to or greater than 1000.
53
You can set breakpoints on lines that do not contain any code, such as comment lines. When the Toolkit runs the program, it automatically moves such a breakpoint down to the next line that actually contains code.
Breakpoint icons
Each breakpoint is indicated by an icon to the left of the line number. The icon for a conditional breakpoint is a diamond, while the icon for an unconditional breakpoint is round. Disabled breakpoints are indicated by an outline icon, while active ones are lled. Unconditional breakpoint. Execution stops here. Unconditional breakpoint, disabled. Execution does not stop. Conditional breakpoint. Execution stops if the attached JavaScript expression evaluates to true. Conditional breakpoint, disabled. Execution does not stop.
You can edit a breakpoint by double-clicking it, or by selecting it and choosing Add or Change from the context menu. A dialog allows you to change the line number, the breakpoints enabled state, and the condition statement.
Whenever execution reaches this breakpoint, the debugger evaluates this condition. If it does not evaluate to true, the breakpoint is ignored and execution continues. This allows you to break only when certain conditions are met, such as a variable having a particular value.
54
Proling
The Proling tool helps you to optimize program execution. When you turn proling on, the JavaScript engine collects information about a program while it is running. It counts how often the program executed a line or function, or how long it took to execute a line or function. You can choose exactly which proling data to display. Because proling signicantly slows execution time, the Prole menu oers these proling options. O Functions Lines Proling turned o. This is the default. The proler counts each function call. At the end of execution, displays the total to the left of the line number where the function header is dened. The proler counts each time each line is executed. At the end of execution, displays the total to the left of the line number. Consumes more execution time, but delivers more detailed information. Add Timing Info Instead of counting the functions or lines, records the time taken to execute each function or line. At the end of execution, displays the total number of microseconds spent in the function or line, to the left of the line number. This is the most time-consuming form of proling. No Proler Data Show Hit Count Show Timing Erase Proler Data Save Data As When selected, do not display proler data. When selected, display hit counts. When selected, display timing data. Clear all proling data. Save proling data as comma-separated values in a CSV le that can be loaded into a spreadsheet program such as Excel.
When execution halts (at termination, at a breakpoint, or due to a runtime error), the Toolkit displays this information in the Editor, line by line. The proling data is color coded:
Green indicates the lowest number of hits, or the fastest execution time. Red indicates trouble spots, such as a line that has been executed many times, or which line took the most time to execute.
This example displays timing information for the program, where the fastest line took 4 microseconds to execute, and the slowest line took 29 microseconds. The timing might not be accurate down to the microsecond; it depends on the resolution and accuracy of the hardware timers built into your computer.
55
The ExtendScript build number. Read only. The date ExtendScript was built. Read only. The most recent run-time error information, contained in a JavaScript Error object. Assigning error text to this property generates a run-time error; however, the preferred way to generate a run-time error is to throw an Error object.
flags
Number
Gets or sets low-level debug output ags. A logical AND of the following bit ag values:
0x0002 (2): Displays each line with its line number as it is executed. 0x0040 (64): Enables excessive garbage collection. Usually, garbage collection
starts when the number of objects has increased by a certain amount since the last garbage collection. This ag causes ExtendScript to garbage collect after almost every statement. This impairs performance severely, but is useful when you suspect that an object gets released too soon.
0x0080 (128): Displays all calls with their arguments and the return value. 0x0100 (256): Enables extended error handling (see the strict property). 0x0200 (512): Enables the localization feature of the toString method. Equivalent to the localize property.
global level
Object Number
Provides access to the global object, which contains the JavaScript global namespace. Enables or disables the JavaScript debugger. One of:
locale
String
Gets or sets the current locale. The string contains ve characters in the form LL _ RR, where LL is an ISO 639 language specier, and RR is an ISO 3166 region specier. Initially, this is the value that the application or the platform returns for the current user. You can set it to temporarily change the locale for testing. To return to the application or platform setting, set to undefined, null, or the empty string.
localize memCache
Boolean Number
Enables or disables the extended localization features of the built-in toString method. See the Localizing ExtendScript Strings section. Gets or sets the ExtendScript memory cache size in bytes.
56
objects os screens
The total count of all JavaScript objects dened so far. Read only. The current operating system version. Read only. An array of objects containing information about the display screens attached to your computer. Each object has the properties left, top, right, and bottom, which contain the four corners of each screen in global coordinates. A property primary is true if that object describes the primary display. When true, any attempt to write to a read-only property causes a runtime error. Some objects do not permit the creation of new properties when true. The version number of the ExtendScript engine as a three-part number and description; for example: 3.6.5 (debug) Read only.
strict version
Boolean String
Displays the About box for the ExtendScript component, and returns the text of the About box as a string. Executes a breakpoint at the current position. Returns undefined. If no condition is needed, it is recommended that you use the JavaScript debugger statement in the script, rather than this method.
Optional. A string containing a JavaScript statement to be used as a condition. If the statement evaluates to true or nonzero when this point is reached, execution stops. Removes a breakpoint from the current script. Returns undefined.
$.clearbp ([line])
Optional. The line at which to clear the breakpoint. If 0 or not supplied, clears the breakpoint at the current line number. Initiates garbage collection. Returns undefined. Returns the value of the specied environment variable, or null if no such variable is dened.
$.gc ()
getenv
$.getenv (envname)
envname list
The name of the environment variable. Collects object information into a table and returns this table as a string. See the following Object statistics section.
$.list ([classname])
classname setbp
Optional. The type of object about which to collect information. If not supplied, collects information about all objects currently dened. Sets a breakpoint in the current script. Returns undefined. If no arguments are needed, it is recommended that you use the JavaScript debugger statement in the script, rather than this method.
line condition
Optional. The line at which to stop execution. If 0 or not supplied, sets the breakpoint at the current line number. Optional. A string containing a JavaScript statement to be used for a conditional breakpoint. If the statement evaluates to true or nonzero when the line is reached, execution stops.
57
sleep
$.sleep (milliseconds)
Suspends the calling thread for the given number of milliseconds. Returns undefined. During a sleep period, checks at 100 millisecond intervals to see whether the sleep should be terminated. This can happen if there is a break request, or if the script timeout has expired.
milliseconds summary
The number of milliseconds to wait. Collects a summary of object counts into a table and returns this table as a string. The table shows the number of objects in each specied class. For example:
3 Array 5 String
$.summary ([classname])
classname write
Optional. The type of object to count. If not supplied, counts all objects currently dened. Writes the specied text to the JavaScript Console. Returns undefined.
text writeln
One or more strings to write, which are concatenated to form a single string. Writes the specied text to the JavaScript Console and appends a linefeed sequence. Returns undefined. One or more strings to write, which are concatenated to form a single string.
text
Object statistics
The output from $.list() is formatted as in the following example. Address 0092196c 00976c8c 00991bc4 L 0099142c L 00991294 L 4 2 1 2 1 Refs 0 1 1 2 0 Prop Function Object LOTest Function Object Class [toplevel] Object LOTest LOTest Object workspace Name
The columns show the following object information. Address L Refs The physical address of the object in memory. This column contains the letter L if the object is a LiveObject (which is an internal data type). The reference count of the object.
58
Prop
A second reference count for the number of properties that reference the object. The garbage collector uses this count to break circular references. If the reference count is not equal to the number of JavaScript properties that reference it, the object is considered to be used elsewhere and is not garbage collected. The class name of the object. The name of the object. This name does not reect the name of the property the object has been stored into. The name is mostly relevant to Function objects, where it is the name of the function or method. Names in brackets are internal names of scripts. If the object has an ID, the last column displays that ID.
Class Name
Reection Object
Every object has a reflect property that returns a Reflection object that reports the contents of the object. You can, for example, show the values of all the properties of an object with code like this:
var f= new File ("myfile"); var props = f.reflect.properties; for (var i = 0; i < props.length; i++) { $.writeln(this property + props[i].name + is + f[props[i].name]); }
Short text describing the reected object, or undefined if no description is available. Longer text describing the reected object more completely, or undefined if no description is available. An Array of ReflectionInfo Objects containing all methods of the reected object, dened in the class or in the specic instance. The class name of the reected object. An Array of ReflectionInfo objects containing all properties of the reected object, dened in the class or in the specic instance. For objects with dynamic properties (dened at runtime) the list contains only those dynamic properties that have already been accessed by the script. For example, in an object wrapping an HTML tag, the names of the HTML attributes are determined at run time.
59
Returns the ReflectionInfo object for the named property of the reected object, or null if no such property exists. Use this method to get information about dynamic properties that have not yet been accessed, but that are known to exist.
name
Examples
ReectionInfo Object
This object contains information about a property, a method, or a method argument.
You can access ReflectionInfo objects in a Reflection objects properties and methods arrays, by name or index:
obj = new String ("hi"); obj.reflect.methods[0]; obj.reflect.methods["indexOf"];
You can access the ReflectionInfo objects for the arguments of a method in the arguments array of the ReflectionInfo object for the method, by index:
obj.reflect.methods["indexOf"].arguments[0];
Array of ReectionInfo
For a reected method, an array of ReflectionInfo objects describing each method argument.
60
dataType
String
Note: Class names start with a capital letter. Thus, the value string stands for a JavaScript string, while String is a JavaScript String wrapper object.
*: Any type. This is the default. null undefined: Return data type for a function that does not return any value. unknown
defaultValue
any
The default value for a reected property or method argument, or undefined if there is no default value, if the property is undened, or if the element is a method. Short text describing the reected object, or undefined if no description is available. Longer text describing the reected object more completely, or undefined if no description is available.
When true, the reected property or method returns a collection; otherwise, false. The maximum numeric value for the reected element, or undefined if there is no maximum or if the element is a method. The minimum numeric value for the reected element, or undefined if there is no minimum or if the element is a method. The name of the reected element. A string, or a number for an array index. The type of the reected element. One of:
readonly: A read-only property. readwrite: A read-write property. createonly: A property that is valid only during creation of an object. method: A method.
61
For portions of your user interface that are displayed on the screen, you may want to localize the displayed text. You can localize any string explicitly using the Global localize function, which takes as its argument a localization object containing the localized versions of a string. A localization object is a JavaScript object literal whose property names are locale names, and whose property values are the localized text strings. The locale name is a standard language code with an optional region identier. For details of the syntax, see the Locale names section. In this example, a msg object contains localized text strings for two locales. This object supplies the text for an alert dialog.
msg = { en: "Hello, world", de: "Hallo Welt" }; alert (msg);
ExtendScript matches the current locale and platform to one of the objects properties and uses the associated string. On a German system, for example, the property de: Hallo Welt is converted to the string Hallo Welt.
To use automatic translation of localization objects, you must enable localization in your script with this statement:
$.localize = true;
The localize function always performs its translation, regardless of the setting of the $.localize variable. For example:
msg = { en: "Yes", de: "Ja", fr: "Oui" }; //Only works if the $.localize=true alert (msg); //Always works, regardless of $.localize value alert ( localize (msg));
If you need to include variables in the localized strings, use the localize function.
62
Locale names
A locale name is an identier string in that contains an ISO 639 language specier, and optionally an ISO 3166 region specier, separated from the language specier by an underscore.
The ISO 639 standard denes a set of two-letter language abbreviations, such as en for English and de for German. The ISO 3166 standard denes a region code, another two-letter identier, which you can optionally append to the language identier with an underscore. For example, en _ US identies U.S. English, while en _ GB identies British English.
This object denes one message for British English, another for all other avors of English, and another for all avors of German:
message = { en_GB: "Please select a colour." en: "Please select a colour." de: "Bitte whlen Sie eine Farbe." };
If you need to specify dierent messages for dierent platforms, you can append another underline character and the name of the platform, one of Win, Mac , or Unix . For example, this objects denes one message in British English to be displayed in Mac OS, one for all other avors of English in Mac OS, and one for all other avors of English on all other platforms:
pressMsg = { en_GB_Mac: "Press Cmd-S to select a colour.", en_Mac: "Press Cmd-S to select a color.", en: "Press Ctrl-S to select a color." };
All of these identiers are case sensitive. For example, EN _ US is not valid.
How locale names are resolved
1. ExtendScript gets the hosting applications locale; for example, en _ US. 2. It appends the platform identier; for example, en _ US _ Win. 3. It looks for a matching property, and if found, returns the value string. 4. If not found, it removes the platform identier (for example, en _ US) and retries. 5. If not found, it removes the region identier (for example, en) and retries. 6. If not found, it tries the identier en (that is, the default language is English). 7. If not found, it returns the entire localizer object.
Testing localization
ExtendScript stores the current locale in the variable $.locale. This variable is updated whenever the locale of the hosting application changes. To test your localized strings, you can temporarily reset the locale. To restore the original behavior, set the variable to null, false, 0, or the empty string. An example:
$.locale = "ru"; // try your Russian messages $.locale = null; // restore to the locale of the app
63
localization_obj
A JavaScript object literal whose property names are locale names, and whose property values are the localized text strings. The locale name is an identier as specied in the ISO 3166 standard, a set of two-letter language abbreviations, such as en for English and de for German. For example:
btnText = { en: "Yes", de: "Ja", fr: "Oui" }; b1 = w.add ("button", undefined, localize (btnText));
The string value of each property can contain variables in the form %1, %2, and so on, corresponding to additional arguments. The variable is replaced with the result of evaluating the corresponding argument in the returned string.
args
Optional. Additional JavaScript expressions matching variables in the string values supplied in the localization object. The rst argument corresponds to the variable %1, the second to %2, and so on. Each expression is evaluated and the result inserted in the variables position in the returned string.
Example
today = { en: "Today is %1/%2", de: "Heute ist der %2.%1." }; d = new Date(); alert (localize (today, d.getMonth()+1, d.getDate()));
ZString
Internal use only. A ZString is an internal Adobe format for localized strings, which you might see in Adobe scripts. It is a string that begins with $$$ and contains a path to the localized string in an installed ZString dictionary. For example:
w = new Window ("dialog", localize ("$$$/UI/title1=Sample"));
Alert: Displays a dialog containing a short message and an OK button. Conrm : Displays a dialog containing a short message and two buttons, Yes and No, allowing the user to accept or reject an action. Prompt: Displays a dialog containing a short message, a text entry eld, and OK and Cancel buttons, allowing the user to supply a value to the script.
64
These dialogs are customizable to a small degree. The appearance is platform specic.
Displays a platform-standard dialog containing a short message and an OK button. Returns undefined.
The string for the displayed message. Optional. A string to appear as the title of the dialog, if the platform supports a title. Mac OS does not support titles for alert dialogs. The default title string is Script Alert. Optional. When true, the platform-standard alert icon is replaced by the platform-standard error icon in the dialog. Default is false.
Examples
This gure shows simple alert dialogs in Windows and Mac OS.
Displays a platform-standard dialog containing a short message and two buttons labeled Yes and No. Returns true if the user clicked Yes, false if the user clicked No.
message noAsDflt
The string for the displayed message. Optional. When true, the No button is the default choice, selected when the user types Enter. Default is false, meaning that Yes is the default choice. Optional. A string to appear as the title of the dialog, if the platform supports a title. Mac OS does not support titles for conrmation dialogs. The default title string is Script Alert.
title
65
Examples
This gure shows simple conrmation dialogs in Windows and Mac OS.
Displays a platform-standard dialog containing a short message, a text edit eld, and two buttons labeled OK and Cancel. Returns the value of the text edit eld if the user clicked OK, null if the user clicked Cancel.
The string for the displayed message. The initial value to be displayed in the text edit eld. Optional. A string to appear as the title of the dialog. In Windows, this appears in the windows frame, while in Mac OS it appears above the message. The default title string is Script Prompt.
Examples
This gure shows simple prompt dialogs in Windows and Mac OS.
66
UnitValue object
Represents measurement values that contain both the numeric magnitude and the unit of measurement.
67
tpc ci px %
If an unknown unit type is supplied, the type is set to ?, and the UnitValue object prints as UnitValue 0.00000. For example, all of the following formats are equivalent:
myVal = new UnitValue (12, "cm"); myVal = new UnitValue ("12 cm"); myVal = UnitValue ("12 centimeters");
UnitValue
A UnitValue Object that denes the size of one pixel, or a total size to use as a base for percentage values. This is used as the base conversion unit for pixels and percentages; see the Converting pixel and percentage values section . Default is 0.013889 inches (1/72 in), which is the base conversion unit for pixels at 72 dpi. Set to null to restore the default.
type value
String Number
The unit type in abbreviated form; for example, cm or in. The numeric measurement value.
Returns the numeric value of this object in the given unit. If the unit is unknown or cannot be computed, generates a run-time error.
unit
The unit type in abbreviated form; for example, cm or in. Converts this object to the given unit, resetting the type and value accordingly. Returns true if the conversion is successful. If the unit is unknown or the object cannot be converted, generates a run-time error and returns false.
unit
68
To convert pixels into length units, you must know the size of a single pixel. The size of a pixel depends on the display resolution. A common resolution measurement is 72 dpi, which means that there are 72 pixels to the inch. The conversion base for pixels at 72 dpi is 0.013889 inches (1/72 inch). Percentage values are relative to a total measurement. For example, 10% of 100 inches is 10 inches, while 10% of 1 meter is 0.1 meters. The conversion base of a percentage is the unit value corresponding to 100%.
The default baseUnit of a unitValue object is 0.013889 inches, the base for pixels at 72 dpi. If the unitValue is for pixels at any other dpi, or for a percentage value, you must set the baseUnit value accordingly. The baseUnit value is itself a unitValue object, containing both a magnitude and a unit. For a system using a dierent dpi, you can change the baseUnit value in the UnitValue class, thus changing the default for all new unitValue objects. For example, to double the resolution of pixels:
UnitValue.baseUnit = UnitValue (1/144, "in"); //144 dpi
You can override the default value for any particular unitValue object by setting the property in that object. For example, to create a unitValue object for pixels with 96 dpi:
pixels = UnitValue (10, "px"); myPixBase = UnitValue (1/96, "in"); pixels.baseUnit = myPixBase;
For percentage measurements, set the baseUnit property to the measurement value for 100%. For example, to create a unitValue object for 40 % of 10 feet:
myPctVal = UnitValue (40, "%"); myBase = UnitValue (10, "ft") myPctVal.baseUnit = myBase;
You can convert a unitValue from an absolute measurement to pixels or percents in the same way:
myMeterVal = UnitValue (10, "m"); // 10 meters myBase = UnitValue (1, "km"); myMeterVal.baseUnit = myBase; //as a percentage of 1 kilometer pctOfKm = myMeterVal.as (%); // => 1 myVal = UnitValue ("1 in"); // Define measurement in inches // convert to pixels using default base myVal.convert ("px"); // => value=72 type=px
Unary operators (~, !, +, -) The numeric value is converted to a 32-bit integer with inverted bits. Result is true if the numeric value is nonzero, false if it is not. Result is the numeric value. Result is the negated numeric value.
69
If one operand is unitValue object and the other is a number, the operation is applied to the number and the numeric value of the object. The expression returns a new unitValue object with the result as its value. For example:
val = new UnitValue ("10 cm"); res = val * 20; // res is a UnitValue (200, "cm");
If both operands are unitValue objects, JavaScript converts the right operand to the same unit as the left operand and applies the operation to the resulting values. The expression returns a new unitValue object with the unit of the left operand, and the result value. For example:
a = new UnitValue ("1 m"); b = new UnitValue ("10 cm"); a + b; // res is a UnitValue (1.1, "m"); b + a; // res is a UnitValue (110, "cm");
Comparisons (=, ==, <, >, <=, >=) If one operand is a unitValue object and the other is a number, JavaScript compares the number with the unitValues numeric value. If both operands are unitValue objects, JavaScript converts both objects to the same unit, and compares the converted numeric values. For example:
a b a a a = new UnitValue ("98 cm"); = new UnitValue ("1 m"); < b; // => true < 1; // => false == 98; // => true
Preprocessor directives
ExtendScript provides preprocessor directives for including external scripts, naming scripts, specifying an ExtendScript engine, and setting certain ags. You can specify these in two ways:
When a directive takes one or more arguments, and an argument contains any nonalphanumeric characters, the argument must be enclosed in single or double quotes. This is generally the case with paths and le names, for example, which contain dots and slashes.
70
#engine name
Identies the ExtendScript engine that runs this script. This allows other engines to refer to the scripts in this engine by importing the exported functions and variables. See the Importing and exporting between scripts section. Use JavaScript identier syntax for the name. Enclosing quotes are optional. For example:
#engine library #engine "$lib"
#include file
Includes a JavaScript source le from another location. Inserts the contents of the named le into this le at the location of this statement. The le argument is an Adobe portable le specication. See the Specifying Paths section. As a convention, use the le extension .jsxinc for JavaScript include les. For example:
#include "../include/lib.jsxinc"
To set one or more paths for the #include statement to scan, use the #includepath preprocessor directive.
If the le to be included cannot be found, ExtendScript throws a run-time error. Included source code is not shown in the debugger, so you cannot set breakpoints in it.
#includepath path
One or more paths that the #include statement should use to locate the les to be included. The semicolon (;) separates path names. If a #include le name starts with a slash (/), it is an absolute path name, and the include paths are ignored. Otherwise, ExtendScript attempts to nd the le by prexing the le with each path set by the #includepath statement. For example:
#includepath "include;../include" #include "file.jsxinc"
Multiple #includepath statements are allowed; the list of paths changes each time an #includepath statement is executed. As a fallback, ExtendScript also uses the contents of the environment variable
JSINCLUDE as a list of include paths.
Some engines can have a predened set of include paths. If so, the path provided by #includepath is tried before the predened paths. If, for example, the engine has a predened path set to predef;predef/include, the preceding example causes the following lookup sequence:
file. jsxinc: literal lookup include/file. jsxinc: rst #includepath path ../include/file. jsxinc: second #includepath path predef/file. jsxinc: rst predened engine path predef/include/file. jsxinc: second predened engine path
71
#script name
Names a script. Enclosing quotes are optional, but required for names that include spaces or special characters. For example:
#script SetupPalette #script "Load image file"
The name value is displayed in the Toolkit Editor tab. An unnamed script is assigned a unique name generated from a number.
#strict on #target name
Turns on strict error checking. See the Dollar ($) Objects strict property. Denes the target application of this JSX le. The name value is an application specier; see the Application and Namespace Speciers section. Enclosing quotes are optional. If the Toolkit is registered as the handler for les with the .jsx extension (as it is by default), opening the le opens the target application to run the script. If this directive is not present, the Toolkit loads and displays the script. A user can open a le by double-clicking it in a le browser, and a script can open a le using a File objects execute method.
A script running in a dierent engine can import the exported elements. The import statement identies the resource script that exported the variables using the engine name:
import library.random, library.libVersion; print (random (100));
You can use the asterisk wildcard (*) to import all symbols exported by a library: import library.* Objects cannot be transferred between engines. You cannot retrieve or store objects, and you cannot call functions with objects as arguments. However, you can use the JavaScript toSource function to serialize objects into strings before passing them. You can then use the JavaScript eval function to reconstruct the object from the string. For example, this function takes as its argument a serialized string and constructs an object from it:
function myFn (serialized) { var obj = eval (serialized); // continue working }
72
In calling the function, you deconstruct the object you want to pass into a serialized string:
myFn (myObject.toSource()); // pass a serialized object
Operator overloading
ExtendScript allows you to extend or override the behavior of a math or a Boolean operator for a specic class by dening a method in that class with same name as the operator. For example, this code denes the addition (+) operator for the class MyClass. In this case, the addition operator simply adds the operand to the property value:
// define the constructor method function MyClass (initalValue) { this.value = initialValue; } // define the addition operator MyClass.prototype ["+"] = function (operand) { return this.value + operand; }
This allows you to perform the + operation with any object of this class:
var obj = new MyClass (5); Result: [object Object] obj + 10; Result: 15
The operators > and >= are implemented by executing NOT operator <= and NOT operator <. Combined assignment operators such as *= are not supported.
All operator overload implementations must return the result of the operation. To perform the default operation, return undefined . Unary operator functions work on the this object, while binary operators work on the this object and the rst argument. The + and - operators have both unary and binary implementations. If the rst argument is undened, the operator is unary; if it is supplied, the operator is binary. For binary operators, a second argument indicates the order of operands. For noncommutative operators, either implement both order variants in your function or return undefined for combinations that you do not support. For example:
this ["/"] = function (operand, rev) { if (rev) { // do not resolve operand / this return; } else { // resolve this / operand return this.value / operand; } }
73
In all ExtendScript scripts, the #target directive can use an specier to identify the application that should run that script. See the Preprocessor directives section . In interapplication messages, the specier is used as the value of the target property of the message object, to identify the target application for the message. Bridge (which is integrated with all Adobe Creative Suite 2 (CS2) applications) uses an application specier as the value of the document.owner property, to identify another CS2 application that created or opened a Bridge browser window. For details, see the Bridge JavaScript Reference, available with CS2.
When a script for one application invokes Cross-DOM or exported functions, it identies the exporting application using Namespace speciers.
Application speciers
Application speciers are strings that encode the application name, a version number and a language code. They take the following form: appname[-version[-locale]]
appname
version
Optional. A number indicating at least a major version. If not supplied, the most recent version is assumed. The number can include a minor version separated from the major version number by a dot; for example, 1.5. Optional. An Adobe locale code, consisting of a 2-letter ISO-639 language code and an optional 2-letter ISO 3166 country code separated by an underscore. Case is signicant. For example, en _ US, en _ UK, ja _ JP, de _ DE, fr _ FR. If not supplied, ExtendScript uses the current platform locale. Do not specify a locale for a multilingual application, such as Bridge, that has all locale versions included in a single installation.
locale
74
Namespace speciers
When calling cross-DOM and exported functions from other applications, a namespace specier qualies the function call, directing it to the appropriate application.Namespace speciers consist of an application name, as used in an application specier, with an optional major version number. Use it as a prex to an exported function name, with the JavaScript dot notation. appname[majorVersion].functionName(args) For example:
To call the cross-DOM function quit in Photoshop CS2, use photoshop.quit(), and to call it in GoLive CS2, use golive.quit(). To call the exported function place, dened for Illustrator CS version 12, call illustrator12.
place(myFiles).
For information about the cross-DOM and exported functions, see the Bridge JavaScript Reference, available with Adobe Creative Suite 2.
A script in the startup directory is executed on startup by all applications. If you place a script here, it must contain code to check whether it is being run by the intended application. You can do this using the appName static property of the BridgeTalk class. For example:
if( BridgeTalk.appName == "bridge" ) { //continue executing script }
In addition, each application looks for application-specic scripts in a subfolder named with that applications specier and version, in the form: %APPDATA%\Adobe\StartupScripts\appname\version ~/Library/Application Support/Adobe/StartupScripts/appname/version/ The name and version in these folder names are specied in the form required for Application speciers. For example, in Windows, GoLive CS2 version 8.2 would look for scripts in the directory:
%APPDATA%\Adobe\StartupScripts\golive\8.2
The version portion of the Bridge-specic folder path is an exact version number. That is, scripts in the folder bridge/1.5 are executed only by Bridge version 1.5, and so on. If a script that is run by one application will communicate with another application, or add functionality that depends on another application, it must rst check whether that application and version is installed. You can do this using the BridgeTalk.getSpecifier static function. For example:
if( BridgeTalk.appName == "bridge" ) { // Check that PS CS2 is installed if( BridgeTalk.getSpecifier("photoshop",9)){ // add PS automate menu to Bridge UI } }
For interapplication communication details, see the Bridge JavaScript Reference, available with Creative Suite 2.
75
Create a new document Open a document Close a document Save a document Set the page size and document length Dene bleed and slug areas Specify page columns and margins
Change the pasteboard's appearance Use guides and grids Change measurement units and ruler origin Dene and apply document presets Set up master pages (master spreads) Set text-formatting defaults Add XMP metadata (information about a le) Create a document template Print a document Export a document as PDF Export pages of a document as EPS
Note: If you have not already worked through Chapter 3, Getting Started with InDesign Scripting, you might want to do so before continuing with this chapter, which assumes that you have already read that chapter and know how to create a script.
76
As you create a document, you can open the document in hidden mode rather than displaying it in a window:
--MakeDocumentWithParameters.as --MakeDocumentWithParameters.as --An InDesign CS2 AppleScript --Creates a new document without showing the document window. --The "showing window" parameter controls the visibility of the document. --Hidden doucments are not minimized, and will remain invisible until --you tell the document to create a new window. tell application "Adobe InDesign CS2" set myDocument to make document with properties {showing window:false} --To show the window: --tell myDocument --set myWindow to make window --end tell end tell
Opening a document
The following example script shows how to open an existing document. You can choose to prevent the document from displaying (hide it) by setting the showing window parameter of the open command to false (the default is true). You might want to do this to improve performance of a script. To show a hidden document, create a new window, as shown in the following script:
--OpenFile.as --An InDesign CS2 AppleScript --Opens the specified file. tell application "Adobe InDesign CS2" --You can use the "showing window" parameter to open files --without displaying them. This can speed up many scripting --operations, and makes it possible for a script to operate --on a file in the background. To display a document youve --opened this way, tell the document to create a new window. --Youll have to fill in your own file path. set myDocument to open "yukino:myTestDocument.indd" without showing window
77
--At this point, your script could change or get information --from the hidden document. tell myDocument to make window end tell
Closing a document
The close command closes a document:
--CloseDocument.as --An InDesign CS2 AppleScript --Closes a document. tell application "Adobe InDesign CS2" close document 1 --document 1 always refers to the front-most document. --Note that you can also use: --close active document end tell
Saving a document
In the InDesign user interface, you save a le by choosing Save from the File menu, and you save a le to another le name by choosing Save As. In InDesign scripting, the save command can do either operation:
--SaveDocument.as --An InDesign CS2 AppleScript --Saves the active document. --If the active document has been changed since it was last saved, save it. tell application "Adobe InDesign CS2" if modified of active document is true then tell active document to save end if end tell
78
The save command has two optional parameters: The rst (to) species the le to save to; the second (stationery) can be set to true to save the document as a template:
--SaveDocumentAs.as --An InDesign CS2 AppleScript --If the active document has not been saved (ever), save it. tell application "Adobe InDesign CS2" if saved of active document is false then --If you do not provide a file name, InDesign will display the Save dialog box. tell active document to save saving in "yukino:myTestDocument.indd" end if end tell
79
tell document preferences of myDocument set page height to "800pt" set page width to "600pt" set page orientation to landscape set pages per document to 16 end tell end tell
Note: The application object also has a document preferences object. You can set the application defaults for page height, page width, and other properties by changing the properties of this object.
If all the bleed distances are equal, as in the preceding example, you can alternatively use the document
bleed uniform size property:
--UniformBleed.as --An InDesign CS2 AppleScript --Shows how to use the uniform size property of the document bleed. tell application "Adobe InDesign CS2" --Create a new document. set myDocument to make document --The bleed properties belong to the document preferences object. tell document preferences of myDocument --Bleed set document bleed top offset to "3p" set document bleed uniform size to true end tell end tell
If all the slug distances are equal, you can instead use the document slug uniform size property:
--UniformSlug.as --An InDesign CS2 AppleScript --Shows how to use the uniform size property of the document slug. --Create a new document. tell application "Adobe InDesign CS2" --Create a new document.
80
set myDocument to make document --The bleed properties belong to the document preferences object. tell document preferences of myDocument --Slug set document slug uniform size to true set slug top offset to "3p" end tell end tell
In addition to setting the bleed and slug widths and heights, you can control the color used to draw the guides dening the bleed and slug. This property is not in the document preferences objectinstead, its in the pasteboard preferences object:
--BleedSlugGuideColors.as --An InDesign CS2 AppleScript --Shows how to set the colors used to display the bleed and slug areas. tell application "Adobe InDesign CS2" --Assumes you have a document open. tell pasteboard preferences of active document --Any of InDesigns guides can use the UIColors constants... set bleed guide color to cute teal set slug guide color to charcoal --...or you can specify a list of RGB values (with values from 0 to 255) set bleed guide color to {0, 198, 192} set slug guide color to {192, 192, 192} end tell end tell
To set the page margins for an individual page, use the margin preferences for that page, as shown in the following example:
--PageMarginsForOnePage.as --An InDesign CS2 AppleScript --Shows how to set the margins of a single page in a new document. tell application "Adobe InDesign CS2" set myDocument to make document tell view preferences of myDocument set horizontal measurement units to points set vertical measurement units to points end tell tell margin preferences of page 1 of myDocument
81
set top to 36 set left to 36 set bottom to 48 set right to 36 end tell end tell
InDesign does not allow you to create a page that is smaller than the sum of the relevant margins, that is, the width of the page must be greater than the sum of the current left and right page margins, and the height of the page must be greater than the sum of the top and bottom margins. If youre creating very small pages (for example, for individual newspaper advertisements) using the InDesign user interface, you can easily set the correct margin sizes as you create the document by entering new values in the document default page Margin elds in the New Document dialog box. From scripting, however, the solution is not as clearwhen you create a document, it uses the application default margin preferences. These margins are applied to all pages of the document, including master pages. Setting the document margin preferences aects only new pages and has no eect on existing pages. If you try to set the page height and page width to values smaller than the sum of the corresponding margins on any of the existing pages, InDesign does not change the page size. There are two solutions. The rst is to set the margins of the existing pages before you try to change the page size:
--PageMarginsForSmallPages.as --An InDesign CS2 AppleScript --Shows how to set the margins of a new document to create a very small page size. --If you dont set the margins first, InDesign will display an error message when --you try to create a page size when the height of the page is less than the sum --of the top and bottom margins, or when the width of the page is less than the sum --of the inside and outside margins. tell application "Adobe InDesign CS2" set myDocument to make document tell margin preferences of page 1 of myDocument set top to 0 set left to 0 set bottom to 0 set right to 0 end tell tell master spread 1 of myDocument tell margin preferences of pages set top to 0 set left to 0 set bottom to 0 set right to 0 end tell end tell --At this point, you can set your page size to a small width and height --(1x1 picas minimum). set page height of document preferences of myDocument to "1p" set page width of document preferences of myDocument to "6p" end tell
Alternatively, you can change the application default margin preferences before you create the document:
--ApplicationPageMargins.as --An InDesign CS2 AppleScript --Shows how to set the margins of a new document to create a very small page size. --If you dont set the margins first, InDesign will display an error message when --you try to create a page size when the height of the page is less than the sum --of the top and bottom margins, or when the width of the page is less than the sum --of the inside and outside margins. tell application "Adobe InDesign CS2" tell margin preferences --Save the current application default margin preferences. set myY1 to top
82
set myX1 to left set myY2 to bottom set myX2 to right --Set the application default margin preferences. set top to 0 set left to 0 set bottom to 0 set right to 0 end tell --At this point, you can create a new document. set myDocument to make document --At this point, you can set your page size to a small width and height --(1x1 picas minimum). set page height of document preferences of myDocument to "1p" set page width of document preferences of myDocument to "1p" --Reset the application default margin preferences to their former state. tell margin preferences set top to myY1 set left to myX1 set bottom to myY2 set right to myX2 end tell end tell
Dening guides
A guide in InDesign gives you an easy way to position objects on the pages of your document. Heres an example use of guides:
--Guides.as --An InDesign CS2 AppleScript --Creates a series of example guides.
83
tell application "Adobe InDesign CS2" set myDocument to make document set myPageWidth to page width of document preferences of myDocument set myPageHeight to page height of document preferences of myDocument tell page 1 of myDocument set myMarginPreferences to margin preferences --Place guides at the margins of the page. make guide with properties {orientation:vertical, location:left of myMarginPreferences} make guide with properties {orientation:vertical, location:(myPageWidth - (right of myMarginPreferences))} make guide with properties {orientation:horizontal, location:top of myMarginPreferences} make guide with properties {orientation:horizontal, location:(myPageHeight - (bottom of myMarginPreferences))} --Place a guide at the vertical center of the page. make guide with properties {orientation:vertical, location:(myPageWidth / 2)} --Place a guide at the horizontal center of the page. make guide with properties {orientation:horizontal, location:(myPageHeight / 2)} end tell end tell
Horizontal guides can be limited to a given page, or can extend across all pages in a spread. With InDesign scripting, you can control this using the fit to page property. (This property is ignored by vertical guides.) You can use scripting to change the layer, color, and visibility of guides, just as you can from the user interface:
--GuideOptions.as --An InDesign CS2 AppleScript --Shows how to set guide options. tell application "Adobe InDesign CS2" set myDocument to make document tell myDocument --Create a layer named "guide layer". set myLayer to make layer with properties {name:"guide layer"} --Add a series of guides to page 1. tell page 1 --Create a guide on the layer we created above. make guide with properties {orientation:horizontal, location:"12p", item layer:myLayer} make guide with properties {item layer:myLayer, orientation:horizontal, location:"14p"} --Make a locked guide. make guide with properties {locked:true, orientation:horizontal, location:"16p"} --Set the view threshold of a guide. make guide with properties {view threshold:100, orientation:horizontal, location:"18p"} --Set the guide color of a guide using a UIColors constant. make guide with properties {guide color:gray, orientation:horizontal, location:"20p"} --Set the guide color of a guide using an RGB array. make guide with properties {guide color:{192, 192, 192}, orientation:horizontal, location:"22p"} end tell end tell end tell
You can also create guides using the create guides command of spreads and master spreads:
--CreateGuidesCommand.as --An InDesign CS2 AppleScript --Add a series of guides using the create Guides command. tell application "Adobe InDesign CS2" set myDocument to make document tell spread 1 of myDocument --Parameters (all optional): row count, column count, row gutter, column gutter, --guide color, fit margins, remove existing, layer.
84
--Note that the createGuides method does not take an RGB array --for the guide color parameter. create guides number of rows 4 number of columns 4 row gutter "1p" column gutter "1p" guide color gray with fit margins and remove existing end tell end tell
85
If youre writing a script that needs to use a specic measurement system, you can change the measurement units at the beginning of the script and then restore the original measurement units at the end of the script, as shown in the following example:
--ResetMeasurementUnits.as --An InDesign CS2 AppleScript --Sets measurement units, performs some actions, and then --resets measurement units to their original values. --Assumes you have a document open. tell application "Adobe InDesign CS2" set myDocument to active document tell view preferences of myDocument set myOldXUnits to horizontal measurement units set myOldYUnits to vertical measurement units set horizontal measurement units to points set vertical measurement units to points end tell --At this point, you can perform any series of script actions that depend on --the measurement units youve set. At the end of the script, reset --the measurement units to their original state. tell view preferences of myDocument set horizontal measurement units to myOldXUnits set vertical measurement units to myOldYUnits end tell end tell
86
--DocumentPresetByExample.as --An InDesign CS2 AppleScript --Creates a new document preset based on the current document settings. tell application "Adobe InDesign CS2" if (count documents) > 0 then set myDocument to active document --If the document preset "myDocumentPreset" does not already exist, create it. try set myDocumentPreset to document preset "myDocumentPreset" on error set myDocumentPreset to make document preset with properties {name:"myDocumentPreset"} end try --Fill in the properties of the document preset with the corresponding --properties of the active document. tell myDocumentPreset --Note that the following gets the page margins from the margin preferences --of the document; to get the margin preferences from the active page, --replace "myDocument" with "active page of active window" in the --following line (assuming the active window is a layout window). set myMarginPreferences to margin preferences of myDocument set left to left of myMarginPreferences set right to right of myMarginPreferences set top to top of myMarginPreferences set bottom to bottom of myMarginPreferences set column count to column count of myMarginPreferences set column gutter to column gutter of myMarginPreferences set document bleed bottom offset to document bleed bottom offset of document preferences of myDocument set document bleed top offset to document bleed top offset of document preferences of myDocument set document bleed inside or left offset to document bleed inside or left offset of document preferences of myDocument set document bleed outside or right offset to document bleed outside or right offset of document preferences of myDocument set facing pages to facing pages of document preferences of myDocument set page height to page height of document preferences of myDocument set page width to page width of document preferences of myDocument set page orientation to page orientation of document preferences of myDocument set pages per document to pages per document of document preferences of myDocument set slug bottom offset to slug bottom offset of document preferences of myDocument set slug top offset to slug top offset of document preferences of myDocument set slug inside or left offset to slug inside or left offset of document preferences of myDocument set slug right or outside offset to slug right or outside offset of document preferences of myDocument end tell end if end tell
87
with properties {name:"myDocumentPreset"} end try --Fill in the properties of the document preset. tell myDocumentPreset set page height to "9i" set page width to "7i" set left to "4p" set right to "6p" set top to "4p" set bottom to "9p" set column count to 1 set document bleed bottom offset to "3p" set document bleed top offset to "3p" set document bleed inside or left offset to "3p" set document bleed outside or right offset to "3p" set facing pages to true set page orientation to portrait set pages per document to 1 set slug bottom offset to "18p" set slug top offset to "3p" set slug inside or left offset to "3p" set slug right or outside offset to "3p" end tell end tell
Using a preset
To create a new document using a document preset, use the document preset parameter as previously shown in the Creating a new document section.
88
tell page 1 set myTextFrame to make text frame with properties {geometric bounds:{"61p", "4p", "62p", "45p"}} tell myTextFrame set contents of insertion point 1 to section marker set contents of insertion point 1 to Em space set contents of insertion point 1 to auto page number set justification of paragraph 1 to left align end tell end tell --Set up the right page (recto). tell margin preferences of page 2 set column count to 3 set column gutter to "1p" set bottom to "6p" --"left" means inside, "right" means outside. set left to "6p" set right to "4p" set top to "4p" end tell --Add a simple footer with a section number and page number. tell page 2 set myTextFrame to make text frame with properties {geometric bounds:{"61p", "6p", "62p", "47p"}} tell myTextFrame set contents of insertion point 1 to auto page number set contents of insertion point 1 to Em space set contents of insertion point 1 to section marker set justification of paragraph 1 to right align end tell end tell end tell end tell
To apply a master spread to a document page, use the applied master property of the document page:
--ApplyMaster.as --An InDesign CS2 AppleScript --Applies a master spread to a page. --Assumes that the active document has a master page named "B-Master" --and at least three document pages. tell application "Adobe InDesign CS2" tell active document set applied master of page 2 to master spread "B-Master" end tell end tell
Use the same property to apply a master spread to a master spread page:
--ApplyMasterToMaster.as --An InDesign CS2 AppleScript --Applies a master spread to a master page. --Assumes that the active document has master spread named "B-Master" --that is not the same as the first master spread in the document. tell application "Adobe InDesign CS2" tell active document set applied master of page 2 of master spread 1 to master spread "B-Master" end tell end tell
89
90
set keep first lines to 2 set keep last lines to 2 set keep with next to 0 set kerning method to "Optical" set leading to 14 set left indent to 0 set ligatures to true set maximum glyph scaling to 100 set maximum letter spacing to 0 set maximum word spacing to 160 set minimum glyph scaling to 100 set minimum letter spacing to 0 set minimum word spacing to 80 set no break to false set OTF contextual alternate to true set OTF discretionary ligature to true set OTF figure style to proportional oldstyle set OTF fraction to true set OTF ordinal to false set OTF slashed zero to false set OTF swash to false set OTF titling to false set overprint fill to false set overprint stroke to false set point size to 11 set position to normal set right indent to 0 set rule above to false if rule above is true then set rule above color to myBlackSwatch set rule above gap color to myNoneSwatch set rule above gap overprint to false set rule above gap tint to 100 set rule above left indent to 0 set rule above line weight to 0.25 set rule above offset to 14 set rule above overprint to false set rule above right indent to 0 set rule above tint to 100 set rule above type to stroke style "Solid" set rule above width to column width end if set rule below to false if rule below is true then set rule below color to color myBlackSwatch set rule below gap color to myNoneSwatch set rule below gap overPrint to false set rule below gap tint to 100 set rule below left indent to 0 set rule below line weight to 0.25 set rule below offset to 14 set rule below overPrint to false set rule below right indent to 0 set rule below tint to 100 set rule below type to stroke style "Solid" set rule below width to column width end if set single word justification to left align set skew to 0 set space after to 0 set space before to 0 set start paragraph to anywhere set strike thru to false if strike thru is true then set strike through color to color myBlackSwatch set strike through gap color to myNoneSwatch set strike through gap overprint to false set strike through gap tint to 100
91
set strike through offset to 3 set strike through overprint to false set strike through tint to 100 set strike through type to stroke style "Solid" set strike through weight to 0.25 end if set stroke color to myNoneSwatch set stroke tint to 100 set stroke weight to 0 set tracking to 0 set underline to false if underline is true then set underline color to color myBlackSwatch set underline gap color to myNoneSwatch set underline gap overprint to false set underline gap tint to 100 set underline offset to 3 set underline overprint to false set underline tint to 100 set underline type to stroke style "Solid" set underline weight to 0.25 end if set vertical scale to 100 end tell end tell
to:
tell text defaults of active document
92
You can also add XMP information to a document using InDesign scripting. All XMP properties for a document are in the documents metadataPreferences object. Heres an example that lls in the standard XMP data for a document. This example also shows that XMP information is extensible. If you need to attach metadata to a document and the data does not fall into one of the categories provided by the metadata preferences object, you can create your own metadata container (email, in this example).
--MetadataExample.as --An InDesign CS2 AppleScript --Creates an example document and adds metadata to it. tell application "Adobe InDesign CS2" set myDocument to make document tell metadata preferences of myDocument set author to "Olav Martin Kvern" set copyright info URL to "http://www.adobe.com" set copyright notice to "This document is copyrighted." set copyright status to yes set description to "Example of xmp metadata scripting in InDesign CS" set document title to "XMP Example" set job name to "XMP_Example_2004" set keywords to {"animal", "mineral", "vegetable"} --The metadata preferences object also includes the read-only --creator, format, creationDate, modificationDate, and serverURL properties that --are automatically entered and maintained by InDesign. --Create a custom XMP container, "email" set myNewContainer to create container item namespace "http://ns.adobe.com/xap/1.0/" path "email" set property namespace "http://ns.adobe.com/xap/1.0/" path "email/*[1]" value "okvern@adobe.com" end tell end tell
93
--Slug set slug bottom offset to "18p" set slug top offset to "3p" set slug inside or left offset to "3p" set slug right or outside offset to "3p" end tell --Create a color. try set myColor to color "PageNumberRed" on error set myColor to make color with properties {name:"PageNumberRed", model:process, color value:{20, 100, 80, 10}} end try --Next, set up some default styles. --Create up a character style for the page numbers. try set myCharacterStyle to character style "page_number" on error set myCharacterStyle to make character style with properties {name:"page_number"} end try set fill color of myCharacterStyle to color "PageNumberRed" --Create up a pair of paragraph styles for the page footer text. --These styles have only basic formatting. try set myParagraphStyle to paragraph style "footer_left" on error set myParagraphStyle to make paragraph style with properties {name:"footer_left"} end try --Create up a pair of paragraph styles for the page footer text. try set myParagraphStyle to paragraph style "footer_right" on error set myParagraphStyle to make paragraph style with properties {name:"footer_right", based on:paragraph style "footer_left", justification:right align} end try --Create a layer for guides. try set myLayer to layer "GuideLayer" on error set myLayer to make layer with properties {name:"GuideLayer"} end try --Create a layer for the footer items. try set myLayer to layer "Footer" on error set myLayer to make layer with properties {name:"Footer"} end try --Create a layer for the slug items. try set myLayer to layer "Slug" on error set myLayer to make layer with properties {name:"Slug"} end try --Create a layer for the body text. try set myLayer to layer "BodyText" on error set myLayer to make layer with properties {name:"BodyText"} end try tell view preferences set ruler origin to page origin set horizontal measurement units to points set vertical measurement units to points end tell --Document baseline grid and document grid
94
tell grid preferences set baseline start to 56 set baseline division to 14 set baseline grid shown to false set horizontal gridline division to 14 set horizontal grid subdivision to 5 set vertical gridline division to 14 set vertical grid subdivision to 5 set document grid shown to false end tell --Document XMP information. tell metadata preferences set author to "Olav Martin Kvern" set copyright info URL to "http:--www.adobe.com" set copyright notice to "This document is not copyrighted." set copyright status to no set description to "Example 7 x 9 book layout" set document title to "Example" set job name to "7 x 9 book layout template" set keywords to {"7 x 9", "book", "template"} set myNewContainer to create container item namespace "http://ns.adobe.com/xap/1.0/" path "email" set property namespace "http://ns.adobe.com/xap/1.0/" path "email/*[1]" value "okvern@adobe.com" end tell --Set up the master spread. tell master spread 1 tell page 1 set myMarginPreferences to margin preferences set myBottomMargin to (page height of document preferences of myDocument - (bottom of myMarginPreferences) set myLeftMargin to right of myMarginPreferences set myRightMargin to (page width of document preferences of myDocument) - (left of myMarginPreferences) make guide with properties {orientation:vertical, location:myRightMargin, item layer:layer "GuideLayer" of myDocument} make guide with properties {orientation:vertical, location:myLeftMargin, item layer:layer "GuideLayer" of myDocument} make guide with properties {orientation:horizontal, location:top of myMarginPreferences, item layer:layer "GuideLayer" of myDocument, fit to page:false} make guide with properties {orientation:horizontal, location:myBottomMargin, item layer:layer "GuideLayer" of myDocument, fit to page:false} make guide with properties {orientation:horizontal, location:myBottomMargin + 14, item layer:layer "GuideLayer" of myDocument, fit to page:false} make guide with properties {orientation:horizontal, location:myBottomMargin + 28, item layer:layer "GuideLayer" of myDocument, fit to page:false} set myLeftFooter to make text frame with properties {item layer:layer "Footer" of myDocument, geometric bounds:{myBottomMargin + 14, right of myMarginPreferences, myBottomMargin + 28, myRightMargin}} set contents of insertion point 1 of parent story of myLeftFooter to section marker set contents of insertion point 1 of parent story of myLeftFooter to Em space set contents of insertion point 1 of parent story of myLeftFooter to auto page number set applied character style of character 1 of parent story of myLeftFooter to character style "page_number" of myDocument set applied paragraph style of paragraph 1 of parent story of myLeftFooter to paragraph style "footer_left" of myDocument --Slug information. tell metadata preferences of myDocument set myEmail to get property namespace "http://ns.adobe.com/xap/1.0/" path "email/*[1]"
95
set myDate to current date set myString to "Author:" & tab & author & tab & "Description:" & tab & description & return & "Creation Date:" & tab & myDate & tab & "Email Contact" & tab & myEmail end tell set myLeftSlug to make text frame with properties {item layer:layer "Slug" of myDocument, geometric bounds:{(page height of document preferences of myDocument) + 36, right of myMarginPreferences, (page height of document preferences of myDocument) + 144, myRightMargin}, contents:myString} tell parent story of myLeftSlug convert to table text 1 end tell --Body text master text frame. set myLeftFrame to make text frame with properties {item layer:layer "BodyText" of myDocument, geometric bounds:{top of myMarginPreferences, right of myMarginPreferences, myBottomMargin, myRightMargin}} end tell tell page 2 set myMarginPreferences to margin preferences set myLeftMargin to left of myMarginPreferences set myRightMargin to (page width of document preferences of myDocument) - (right of myMarginPreferences) make guide with properties {orientation:vertical, location:myLeftMargin, item layer:layer "GuideLayer" of myDocument} make guide with properties {orientation:vertical, location:myRightMargin, item layer:layer "GuideLayer" of myDocument} set myRightFooter to make text frame with properties {item layer:layer "Footer" of myDocument, geometric bounds:{myBottomMargin + 14, left of myMarginPreferences, myBottomMargin + 28, myRightMargin}} set contents of insertion point 1 of parent story of myRightFooter to auto page number set contents of insertion point 1 of parent story of myRightFooter to Em space set contents of insertion point 1 of parent story of myRightFooter to section marker set applied character style of character -1 of parent story of myRightFooter to character style "page_number" of myDocument set applied paragraph style of paragraph 1 of parent story of myRightFooter to paragraph style "footer_right" of myDocument --Slug information. set myRightSlug to make text frame with properties {item layer:layer "Slug" of myDocument, geometric bounds:{(page height of document preferences of myDocument) + 36, left of myMarginPreferences, (page height of document preferences of myDocument) + 144, myRightMargin}, contents:myString} tell parent story of myRightSlug convert to table text 1 end tell --Body text master text frame. set myRightFrame to make text frame with properties {item layer:layer "BodyText" of myDocument, geometric bounds:{top of myMarginPreferences, left of myMarginPreferences, myBottomMargin, myRightMargin}} end tell end tell --Add section marker text--this text will appear in the footer. set marker of section 1 of myDocument to "Section 1" --When you link the master page text frames, one of the frames sometimes --becomes selected. Deselect it. select nothing end tell end tell
96
Printing a document
The following script prints the active document using the current print preferences:
--PrintDocument.as --An InDesign CS2 AppleScript --Prints the active document using the current print settings. tell application "Adobe InDesign CS2" print active document end tell
97
set myY1Offset to document bleed top offset + 3 set myX2Offset to document bleed outside or right offset + 3 set myY2Offset to document bleed bottom offset + 3 end tell tell print preferences of active document --Properties corresponding to the controls in the General panel --of the Print dialog box. --activePrinterPreset is ignored in this example--well set our --own print preferences. --printer can be either a string (the name of the printer) or --postscript file. set printer to postscript file --Heres an example of setting the printer to a specific printer. --set printer to "AGFA-SelectSet 5000SF v2013.108" --If the printer property is the name of a printer, then the ppd property --is locked (and will return an error if you try to set it). try set PPD to "AGFA SelectSet 7000-X" end try --If the printer property is set to postscript file, the copies --property is unavailable. Attempting to set it will generate an error. --set copies to 1 --If the printer property is set to Printer.postscript file, or if the --selected printer does not support collation, then the collating --property is unavailable. Attempting to set it will generate an error. --set collating to false set reverse order to false --The setting of color output determines the settings available --to almost all other properties in the print preferences. try set color output to separations end try --pageRange can be either PageRange.allPages or a page range string. set page range to all pages set print spreads to false set print master pages to false --If the printer property is set to postScript file, then --the print file property contains the file path to the output file. --set printFile to "yukino:test.ps" set sequence to all --If trapping is on, setting the following properties will produce an error. try if trapping is off then set print blank pages to false set print guides grids to false set print nonprinting to false end if end try ---------------------------------------------------------------------------------Properties corresponding to the controls in the Setup panel of --the Print dialog box. -------------------------------------------------------------------------------set paper size to custom --Page width and height are ignored if paper Size is not custom. --set paper height to 1200 --set paper width to 1200 set print page orientation to portrait set page position to centered set paper gap to 0 set paper offset to 0 set paper transverse to false set scale height to 100 set scale width to 100 set scale mode to scale width height set scale proportional to true --If trapping is on (application built in or Adobe inRip), --attempting to set the following properties will produce an error. if trapping is off then
98
set thumbnails to false --The following properties is not needed because thumbnails is set to false. --set thumbnails per page to 4 set tile to false --The following properties are not needed because tile is set to false. --set tiling overlap to 12 --set tiling type to auto end if ---------------------------------------------------------------------------------Properties corresponding to the controls in the Marks and Bleed --panel of the Print dialog box. ---------------------------------------------------------------------------------Set the following property to true to print all printers marks. --set all Printer Marks to true; set use document bleed to print to false --If use document bleed to print is true then setting any of the -- bleed properties --will result in an error. set bleed bottom to myY2Offset set bleed top to myY1Offset set bleed inside to myX1Offset set bleed outside to myX2Offset --If any bleed area is greater than zero, then export the bleed marks. if bleed bottom is equal to 0 and bleed top is equal to 0 and bleed inside is equal to 0 and bleed outside is equal to 0 then set bleed marks to true else set bleed marks to false end if set color bars to true set crop marks to true set include slug to print to false set mark line weight to p125pt set mark offset to 6 --set mark Type to default set page information marks to true set registration marks to true ---------------------------------------------------------------------------------Properties corresponding to the controls in the Output panel --of the Print dialog box. -------------------------------------------------------------------------------set negative to true set color output to separations --Note the lowercase "i" in "Builtin" set trapping to application builtin set screening to "175 lpi/2400 dpi" set flip to none --If trapping is on, attempting to set the following properties --will generate an error. if trapping is off then set print black to true set print cyan to true set print magenta to true set print yellow to true end if --Only change the ink angle and frequency when you want to override the --screening set by the screening specified by the screening property. --set black angle to 45 --set black frequency to 175 --set cyan angle to 15 --set cyan frequency to 175 --set magenta angle to 75 --set magenta frequency to 175 --set yellow angle to 0 --set yellow frequency to 175 --The following properties are not needed (because colorOutput --is set to separations). --set composite angle to 45
99
--set composite frequency to 175 --set simulate overprint to false ---------------------------------------------------------------------------------Properties corresponding to the controls in the Graphics panel --of the Print dialog box. -------------------------------------------------------------------------------set send image data to all image data set font downloading to complete try set download PPD fonts to true end try try set data format to binary end try try set PostScript level to level 3 end try ---------------------------------------------------------------------------------Properties corresponding to the controls in the Color Management panel --of the Print dialog box. ---------------------------------------------------------------------------------If the use color management property of color settings is false, --attempting to set the following properties will return an error. try set source space to use document set intent to use color settings set CRD to use document set profile to PostScript CMS end try ---------------------------------------------------------------------------------Properties corresponding to the controls in the Advanced panel --of the Print dialog box. -------------------------------------------------------------------------------set OPI image replacement to false set omit bitmaps to false set omit EPS to false set omit PDF to false --The following line assumes that you have a flattener preset --named "high quality flattener". try set flattener preset name to "high quality flattener" end try set ignore spread overrides to false end tell end tell
100
--If the preset does not already exist, then create it of --print preferences of myDocument --otherwise, fill in the properties of the existing preset. tell application "Adobe InDesign CS2" try set myPreset to printer preset "myPreset" on error set myPreset to make printer preset with properties {name:"myPreset"} end try set myDocument to active document tell myPreset --Because many printing properties are dependent on other printing properties, --weve surrounded each property-setting line with try...end try statements---these will make it easier for you to experiment with print preset settings. try set printer to printer of print preferences of myDocument end try try set PPD to PPD of print preferences of myDocument end try try set copies to copies of print preferences of myDocument end try try set collating to collating of print preferences of myDocument end try try set reverse order to reverse order of print preferences of myDocument end try try set print spreads to print spreads of print preferences of myDocument end try try set print master pages to print master pages of print preferences of myDocument end try try set print file to printFile of print preferences of myDocument end try try set sequence to sequence of print preferences of myDocument end try try set print blank pages to print blank pages of print preferences of myDocument end try try set print guides grids to print guides grids of print preferences of myDocument end try try set print nonprinting to print nonprinting of print preferences of myDocument end try try set paper size to paper size of print preferences of myDocument end try try set paper height of myPreset to paper height of print preferences of myDocument end try try set paper width of myPreset to paper width of print preferences of myDocument end try try set print page orientation of myPreset to print page orientation of print preferences of myDocument end try try set page position of myPreset to page position of
101
print preferences of myDocument end try try set paper gap of myPreset to paper gap of print preferences of myDocument end try try set paper offset of myPreset to paper offset of print preferences of myDocument end try try set paper transverse of myPreset to paper transverse of print preferences of myDocument end try try set scale height of myPreset to scale height of print preferences of myDocument end try try set scale width of myPreset to scale width of print preferences of myDocument end try try set scale mode of myPreset to scale mode of print preferences of myDocument end try try set scale proportional of myPreset to scale proportional of print preferences of myDocument end try try set text as black of myPreset to text as black of print preferences of myDocument end try try set thumbnails of myPreset to thumbnails of print preferences of myDocument end try try set thumbnails per page of myPreset to thumbnails per page of print preferences of myDocument end try try set tile of myPreset to tile of print preferences of myDocument end try try set tiling type of myPreset to tiling type of print preferences of myDocument end try try set tiling overlap of myPreset to tiling overlap of print preferences of myDocument end try try set all printer marks of myPreset to all printer marks of print preferences of myDocument end try try set use document bleed to print of myPreset to use document bleed to print of print preferences of myDocument end try try set bleed bottom of myPreset to bleed bottom of print preferences of myDocument end try try set bleed top of myPreset to bleed top of print preferences of myDocument end try try set bleed inside of myPreset to bleed inside of print preferences of myDocument end try try
102
set bleed outside of myPreset to bleed outside of print preferences of myDocument end try try set bleed marks of myPreset to bleed marks of print preferences of myDocument end try try set color bars of myPreset to color bars of print preferences of myDocument end try try set crop marks of myPreset to crop marks of print preferences of myDocument end try try set include slug to print of myPreset to include slug to print of print preferences of myDocument end try try set mark line weight of myPreset to mark line weight of print preferences of myDocument end try try set mark offset of myPreset to mark offset of print preferences of myDocument end try try set mark type of myPreset to mark type of print preferences of myDocument end try try set page information marks of myPreset to page information marks of print preferences of myDocument end try try set registration marks of myPreset to registration marks of print preferences of myDocument end try try set negative of myPreset to negative of print preferences of myDocument end try try set color output of myPreset to color output of print preferences of myDocument end try try set trapping of myPreset to trapping of print preferences of myDocument end try try set screening of myPreset to screening of print preferences of myDocument end try try set flip of myPreset to flip of print preferences of myDocument end try try set print black of myPreset to print black of print preferences of myDocument end try try set print cyan of myPreset to print cyan of print preferences of myDocument end try try set print magenta of myPreset to print magenta of print preferences of myDocument end try try set print yellow of myPreset to print yellow of print preferences of myDocument end try try set black angle of myPreset to black angle of print preferences of myDocument end try try
103
set black frequency of myPreset to black frequency of print preferences of myDocument end try try set cyan angle of myPreset to cyan angle of print preferences of myDocument end try try set cyan frequency of myPreset to cyan frequency of print preferences of myDocument end try try set magenta angle of myPreset to magenta angle of print preferences of myDocument end try try set magenta frequency of myPreset to magenta frequency of print preferences of myDocument end try try set yellow angle of myPreset to yellow angle of print preferences of myDocument end try try set yellow frequency of myPreset to yellow frequency of print preferences of myDocument end try try set composite angle of myPreset to composite angle of print preferences of myDocument end try try set composite frequency of myPreset to composite frequency of print preferences of myDocument end try try set simulate overprint of myPreset to simulate overprint of print preferences of myDocument end try try set send image data of myPreset to send image data of print preferences of myDocument end try try set font downloading of myPreset to font downloading of print preferences of myDocument end try try set download PPD fonts of myPreset to download PPD fonts of print preferences of myDocument end try try set data format of myPreset to data format of print preferences of myDocument end try try set PostScript level of myPreset to PostScript level of print preferences of myDocument end try try set source space of myPreset to source space of print preferences of myDocument end try try set intent of myPreset to intent of print preferences of myDocument end try try set CRD of myPreset to CRD of print preferences of myDocument end try try
104
set profile of myPreset to profile of print preferences of myDocument end try try set OPI image replacement of myPreset to OPI image replacement of print preferences of myDocument end try try set omit bitmaps of myPreset to omit bitmaps of print preferences of myDocument end try try set omit EPS of myPreset to omit EPS of print preferences of myDocument end try try set omit PDF of myPreset to omit PDF of print preferences of myDocument end try try set flattener preset name of myPreset to flattener preset name of print preferences of myDocument end try try set ignore spread overrides of myPreset to ignore spread overrides of print preferences of myDocument end try display dialog ("Done!") end tell end tell
105
set myX1Offset to document bleed inside or left offset set myY1Offset to document bleed top offset set myX2Offset to document bleed outside or right offset set myY2Offset to document bleed bottom offset end tell tell PDF export preferences --Basic PDF output options. set page range to all pages set acrobat compatibility to acrobat 6 set export guides and grids to false set export layers to false set export nonprinting objects to false set export reader spreads to false set generate thumbnails to false try set ignore spread overrides to false end try set include bookmarks to true set include hyperlinks to true try set include ICC profiles to true end try set include slug with PDF to false set include structure to false set interactive elements to false --Setting subset fonts below to zero disallows font subsetting --set subset fonts below to some other value to use font subsetting. set subset fonts below to 0 --Bitmap compression/sampling/quality options. set color bitmap compression to zip set color bitmap quality to eight bit set color bitmap sampling to none --threshold to compress color is not needed in this example. --color bitmap sampling dpi is not needed when color bitmap sampling --is set to none. set grayscale bitmap compression to zip set grayscale bitmap quality to eight bit set grayscale bitmap sampling to none --threshold to compress gray is not needed in this example. --grayscale bitmap sampling dpi is not needed when grayscale bitmap --sampling is set to none. set monochrome bitmap compression to zip set monochrome bitmap sampling to none --threshold to compress monochrome is not needed in this example. --monochrome bitmap sampling dpi is not needed when monochrome bitmap --sampling is set to none. --Other compression options. set compression type to Compress None set compress text and line art to true set content to embed to Embed All set crop images to frames to true set optimize PDF to true --Printers marks and prepress options. set bleed bottom to myY2Offset set bleed top to myY1Offset set bleed inside to myX1Offset set bleed outside to myX2Offset --If any bleed area is greater than zero, then export the bleed marks. if bleed bottom is 0 and bleed top is 0 and bleed inside is 0 and bleed outside is 0 then set bleed marks to true else set bleed marks to false end if set color bars to true --Color tile size and gray tile size are not used --unless the compression method chosen is JPEG 2000. --set color tile size to 256
106
--set Gray tile size to 256 set crop marks to true set omit bitmaps to false set omit EPS to false set omit PDF to false set page information marks to true set page marks offset to "12 pt" set PDF color space to unchanged color space set PDF mark type to default set printer mark weight to p125pt set registration marks to true --simulate overprint is only available when the export standard --is PDF/X-1a or PDF/X-3 --set simulate overprint to false set use document bleed with PDF to true --Set viewPDF to true to open the PDF in Acrobat or Adobe Reader. set view PDF to false end tell --Now export the document. tell active document export format PDF type to "yukino:test.pdf" without showing options end tell end tell
107
set myFolder to class ktxt of (myFolder as record) if myFolder is not equal to "" then my myExportPages(myFolder) end if end myChooseFolder on myExportPages(myFolder) tell application "Adobe InDesign CS2" set myDocument to active document set myDocumentName to name of myDocument set myDialog to make dialog with properties {name:"File Naming Options"} tell myDialog tell (make dialog column) tell (make dialog row) make static text with properties {static label:"Base name:"} set myBaseNameField to make text editbox with properties {edit contents:myDocumentName, min width:160} end tell end tell end tell set myResult to show myDialog if myResult is true then --The name of the exported files will be the base name + the value --of the counter + ".pdf". set myBaseName to edit contents of myBaseNameField --Remove the dialog box from memory. destroy myDialog repeat with myCounter from 1 to (count pages in myDocument) set myPageName to name of page myCounter of myDocument set page range of PDF export preferences to name of page myCounter of myDocument --Generate a file path from the folder name, the base document name, --and the page name. --Replace any colons in the page name (e.g., "Sec1:1") so that --they dont cause --problems with file naming. set myPageName to my myReplace(myPageName, ":", "_") set myFilePath to myFolder & myBaseName & "_" & myPageName & ".pdf" tell myDocument --The export command will fail if you provide the file path --as Unicode text--thats why we had to convert the folder name --to plain text. export format PDF type to myFilePath end tell end repeat else destroy myDialog end if end tell end myExportPages on myReplace(myString, myFindString, myChangeString) set AppleScripts text item delimiters to myFindString set myTextList to every text item of (myString as text) set AppleScripts text item delimiters to myChangeString set myString to myTextList as string set AppleScripts text item delimiters to "" return myString end myReplace
108
109
end myChooseFolder on myExportPages(myFolder) tell application "Adobe InDesign CS2" set myDocument to active document set myDocumentName to name of myDocument set myDialog to make dialog with properties {name:"ExportPages"} tell myDialog tell (make dialog column) tell (make dialog row) make static text with properties {static label:"Base Name:"} set myBaseNameField to make text editbox with properties {edit contents:myDocumentName, min width:160} end tell end tell end tell set myResult to show myDialog if myResult is true then --The name of the exported files will be the base name + the --value of the counter + ".pdf". set myBaseName to edit contents of myBaseNameField --Remove the dialog box from memory. destroy myDialog repeat with myCounter from 1 to (count pages in myDocument) --Get the name of the page and assign it to the variable "myPageName" set myPageName to name of page myCounter of myDocument --Set the page range to the name of the specific page. set page range of EPS export preferences to myPageName --Generate a file path from the folder name, the base document name, --and the page name. --Replace any colons in the page name (e.g., "Sec1:1") so that --they dont cause --problems with file naming. set myPageName to my myReplace(myPageName, ":", "_") set myFilePath to myFolder & myBaseName & "_" & myPageName & ".eps" tell myDocument export format EPS type to myFilePath without showing options end tell end repeat else destroy myDialog end if end tell end myExportPages on myReplace(myString, myFindString, myChangeString) set AppleScripts text item delimiters to myFindString set myTextList to every text item of (myString as text) set AppleScripts text item delimiters to myChangeString set myString to myTextList as string set AppleScripts text item delimiters to "" return myString end myReplace
110
111
Create a new document Open a document Close a document Save a document Set the page size and document length Dene bleed and slug areas Specify page columns and margins
Change the pasteboard's appearance Use guides and grids Change measurement units and ruler origin Dene and apply document presets Set up master pages (master spreads) Set text-formatting defaults Add XMP metadata (information about a le) Create a document template Print a document Export a document as PDF Export pages of a document as EPS
Note: If you have not already worked through Chapter 3, Getting Started with InDesign Scripting, you might want to do so before continuing with this chapter, which assumes that you have already read that chapter and know how to create a script.
112
The document.add method can take two optional parameters, as shown in the following script:
//MakeDocumentWithParameters.jsx //An InDesign CS2 JavaScript //Shows how to use the parameters of the document.open method. //The first parameter (showingWindow) controls the visibility of the //document. Hidden documents are not minimized, and will not appear until //you add a new window to the document. The second parameter (documentPreset) //specifies the document preset to use. The following line assumes that //you have a document preset named "Flyer" on your system. var myDocument = app.documents.add(true, app.documentPresets.item("Flyer"));
Opening a document
The following example script shows how to open an existing document:
//OpenDocument.jsx //An InDesign CS2 JavaScript //Opens an existing document. Youll have to fill in your own file path. app.open(File("/c/myTestDocument.indd"));
You can choose to prevent the document from displaying (hide it) by setting the showingWindow parameter of the open method to false (the default is true). You might want to do this to improve performance of a script. To show a hidden document, create a new window, as shown in the following script:
//OpenDocumentInBackground.jsx //An InDesign CS2 JavaScript //Opens an existing document in the background, then shows the document. //Youll have to fill in your own file path. var myDocument = app.open(File("/c/myTestDocument.indd"), false); //At this point, you could do things with the document without showing the //document window. In some cases, scripts will run faster when the document //window is not visible. //When you want to show the hidden document, create a new window. var myLayoutWindow = myDocument.windows.add();
Closing a document
The close method closes a document:
//CloseDocument.jsx //An InDesign CS2 JavaScript //Closes the active document. app.activeDocument.close(); //Note that you could also use: //app.documents.item(0).close();
113
Saving a document
In the InDesign user interface, you save a le by choosing Save from the File menu, and you save a le to another le name by choosing Save As. In InDesign scripting, the save method can do either operation:
//SaveDocument.jsx //An InDesign CS2 JavaScript //If the active document has been changed since it was last saved, save it. if(app.activeDocument.modified == true){ app.activeDocument.save(); }
The save method has two optional parameters: the rst (To) species the le to save to; the second (Stationery) can be set to true to save the document as a template.
//SaveDocumentAs.jsx //An InDesign CS2 JavaScript //If the active document has not been saved (ever), save it. if(app.activeDocument.saved == false){ //If you do not provide a file name, InDesign will display the Save dialog box. app.activeDocument.save(new File("/c/myTestDocument.indd")); }
114
//If the file name contains the extension ".indd", change it to ".indt". if(myFileName.indexOf(".indd")!=-1){ var myRegularExpression = /.indd/gi myFileName = myFileName.replace(myRegularExpression, ".indt"); } } //If the document has not been saved, then give it a default file name/file path. else{ myFileName = "/c/myTestDocument.indt"; } app.activeDocument.save(File(myFileName), true);
Note: The application object also has a document preferences object. You can set the application defaults for page height, page width, and other properties by changing the properties of this object.
115
If all the bleed distances are equal, as in the preceding example, you can alternatively use the documentBleedUniformSize property:
//UniformBleed.jsx //An InDesign CS2 JavaScript //Create a new document. myDocument = app.documents.add(); //The bleed properties belong to the documentPreferences object. with(myDocument.documentPreferences){ //Bleed documentBleedUniformSize = true; documentBleedTopOffset = "3p"; }
If all the slug distances are equal, you can instead use the documentSlugUniformSize property:
//UniformSlug.jsx //An InDesign CS2 JavaScript //Create a new document. myDocument = app.documents.add(); //The slug properties belong to the documentPreferences object. with(myDocument.documentPreferences){ //Slug: documentSlugUniformSize = true; slugTopOffset = "3p"; }
In addition to setting the bleed and slug widths and heights, you can control the color used to draw the guides dening the bleed and slug. This property is not in the document preferences objectinstead, its in the pasteboardPreferences object:
//BleedSlugGuideColors.jsx //An InDesign CS2 JavaScript //Set the colors used to display the bleed and slug guides. with(app.activeDocument.pasteboardPreferences){ //Any of InDesigns guides can use the UIColors constants... bleedGuideColor = UIColors.cuteTeal; slugGuideColor = UIColors.charcoal; //...or you can specify an array of RGB values (with values from 0 to 255) //bleedGuideColor = [0, 198, 192]; //slugGuideColor = [192, 192, 192]; }
116
s.facingPages == true, //"left" means inside; "right" means outside. left = "6p" right = "4p" top = "4p" }
InDesign does not allow you to create a page that is smaller than the sum of the relevant margins, that is, the width of the page must be greater than the sum of the current left and right page margins, and the height of the page must be greater than the sum of the top and bottom margins. If youre creating very small pages (for example, for individual newspaper advertisements) using the InDesign user interface, you can easily set the correct margin sizes as you create the document by entering new values in the document default page Margin elds in the New Document dialog box. From scripting, however, the solution is not as clearwhen you create a document, it uses the application default margin preferences. These margins are applied to all pages of the document, including master pages. Setting the document margin preferences aects only new pages and has no eect on existing pages. If you try to set the page height and page width to values smaller than the sum of the corresponding margins on any of the existing pages, InDesign does not change the page size. There are two solutions. The rst is to set the margins of existing pages before trying to change the page size:
//PageMargins.jsx //An InDesign CS2 JavaSCript //Creates a new document and sets up page margins. var myDocument = app.documents.add(); myDocument.marginPreferences.top = 0; myDocument.marginPreferences.left = 0; myDocument.marginPreferences.bottom = 0; myDocument.marginPreferences.right = 0; //The following assumes that your default document contains a single page. myDocument.pages.item(0).marginPreferences.top = 0; myDocument.pages.item(0).marginPreferences.left = 0; myDocument.pages.item(0).marginPreferences.bottom = 0; myDocument.pages.item(0).marginPreferences.right = 0; //The following assumes that your default master spread contains two pages. myDocument.masterSpreads.item(0).pages.item(0).marginPreferences.top = 0; myDocument.masterSpreads.item(0).pages.item(0).marginPreferences.left = 0; myDocument.masterSpreads.item(0).pages.item(0).marginPreferences.bottom = 0; myDocument.masterSpreads.item(0).pages.item(0).marginPreferences.right = 0; myDocument.masterSpreads.item(0).pages.item(1).marginPreferences.top = 0; myDocument.masterSpreads.item(0).pages.item(1).marginPreferences.left = 0; myDocument.masterSpreads.item(0).pages.item(1).marginPreferences.bottom = 0; myDocument.masterSpreads.item(0).pages.item(1).marginPreferences.right = 0; myDocument.documentPreferences.pageHeight = "1p"; myDocument.documentPreferences.pageWidth = "6p";
Alternatively, you can change the application default margin preferences before you create the document:
//ApplicationPageMargins.jsx //An InDesign CS2 JavaScript //Sets the application default page margins. All new documents will be //created using these settings; existing documents will be unaffected. with (app.marginPreferences){ //Save the current application default margin preferences. var myY1 = top; var myX1 = left; var myY2 = bottom; var myX2 = right; //Set the application default margin preferences. top = 0; left = 0; bottom = 0; right = 0; }
117
//Create a new example document to demonstrate the change. var myDocument = app.documents.add(); myDocument.documentPreferences.pageHeight = "1p"; myDocument.documentPreferences.pageWidth = "6p"; //Reset the application default margin preferences to their former state. with (app.marginPreferences){ top = myY1; left = myX1 ; bottom = myY2; right = myX2; }
Dening guides
A guide in InDesign gives you an easy way to position objects on the pages of your document. Heres an example use of guides:
//Guides.jsx //An InDesign CS2 JavaScript //Create a new document, add guides, and set guide properties. var myDocument = app.documents.add(); var myPageWidth = myDocument.documentPreferences.pageWidth; var myPageHeight = myDocument.documentPreferences.pageHeight; with(myDocument.pages.item(0)){ //Place guides at the margins of the page. guides.add(undefined, {orientation:HorizontalOrVertical.vertical, location:marginPreferences. left}); guides.add(undefined, {orientation:HorizontalOrVertical.vertical, location:(myPageWidth marginPreferences.right)}); guides.add(undefined, {orientation:HorizontalOrVertical.horizontal, location:marginPreferences. top});
118
guides.add(undefined, {orientation:HorizontalOrVertical.horizontal, location:(myPageHeight marginPreferences.bottom)}); //Place a guide at the vertical center of the page. guides.add(undefined, {orientation:HorizontalOrVertical.vertical, location:(myPageWidth/2)}); //Place a guide at the horizontal center of the page. guides.add(undefined, {orientation:HorizontalOrVertical.horizontal, location:(myPageHeight/2)}); }
Horizontal guides can be limited to a given page, or can extend across all pages in a spread. With InDesign scripting, you can control this using the fitToPage property. (This property is ignored by vertical guides.)
//SpreadAndPageGuides.jsx //An InDesign CS2 JavaScript //Demonstrate the difference between spread guides and page guides. var myDocument = app.documents.add(); myDocument.documentPreferences.facingPages = true; myDocument.documentPreferences.pagesPerDocument = 3; with(myDocument.spreads.item(1)){ //Note the difference between these two guides on pages 2 and 3. guides.add(undefined, {orientation:HorizontalOrVertical.horizontal, location:"6p", fitToPage: true}); guides.add(undefined, {orientation:HorizontalOrVertical.horizontal, location:"9p", fitToPage: false}); }
You can use scripting to change the layer, color, and visibility of guides, just as you can from the user interface:
//GuideOptions.jsx //An InDesign CS2 JavaScript //Shows how to set guide options. var myGuide; var myDocument = app.documents.add(); //Create a layer named "guide layer". var myLayer = myDocument.layers.add({name:"guide layer"}); //Add a series of guides to page 1. with(myDocument.pages.item(0)){ //Create a guide on the layer we created above. myGuide = guides.add(myLayer, {orientation:HorizontalOrVertical.horizontal, location:"12p"}); //Another way to make a guide on a specific layer. myGuide = guides.add(undefined, {itemLayer:myLayer, orientation:HorizontalOrVertical.horizontal, location:"14p"}); //Make a locked guide. myGuide = guides.add(myLayer,{locked:true, orientation:HorizontalOrVertical.horizontal, location:"16p"}); //Set the view threshold of a guide. myGuide = guides.add(myLayer,{viewThreshold:100, orientation:HorizontalOrVertical.horizontal, location:"18p"}); //Set the guide color of a guide using a UIColors constant. myGuide = guides.add(myLayer,{guideColor:UIColors.gray, orientation:HorizontalOrVertical. horizontal, location:"20p"}); //Set the guide color of a guide using an RGB array. myGuide = guides.add(myLayer,{guideColor:[192, 192, 192], orientation:HorizontalOrVertical. horizontal, location:"22p"}); }
You can also create guides using the createGuides method of spreads and master spreads:
//CreateGuides.jsx //An InDesign CS2 JavaScript //Add a series of guides using the createGuides method. var myDocument = app.documents.add(); with (myDocument.spreads.item(0)){ //Parameters (all optional): row count, column count, row gutter, //column gutter,guide color, fit margins, remove existing, layer. //Note that the createGuides method does not take an RGB array //for the guide color parameter. createGuides(4, 4, "1p", "1p", UIColors.gray, true, true, myDocument.layers.item(0)); }
119
120
//Measurement unit choices are: //* MeasurementUnits.picas //* MeasurementUnits.points //* MeasurementUnits.inches //* MeasurementUnits.inchesDecimal //* MeasurementUnits.millimeters //* MeasurementUnits.centimeters //* MeasurementUnits.ciceros // //Set horizontal and vertical measurement units to points. horizontalMeasurementUnits = MeasurementUnits.points; verticalMeasurementUnits = MeasurementUnits.points; }
If youre writing a script that needs to use a specic measurement system, you can change the measurement units at the beginning of the script and then restore the original measurement units at the end of the script, as shown in the following example:
//ResetMeasurementUnits.jsx //An InDesign CS2 JavaScript //Changes, then resets the active documents measurement units. //Assumes you have a document open. var myDocument = app.activeDocument with (myDocument.viewPreferences){ var myOldXUnits = horizontalMeasurementUnits; var myOldYUnits = verticalMeasurementUnits; horizontalMeasurementUnits = MeasurementUnits.points; verticalMeasurementUnits = MeasurementUnits.points; } //At this point, you can perform any series of script actions //that depend on the measurement units youve set. At the end of //the script, reset the measurement units to their original state. with (myDocument.viewPreferences){ try{ horizontalMeasurementUnits = myOldXUnits; verticalMeasurementUnits = myOldYUnits; } catch(myError){ alert("Could not reset custom measurement units."); } }
121
try { var myPresetName = myDocumentPreset.name; } catch (myError){ myDocumentPreset = app.documentPresets.add({name:"myDocumentPreset"}); } //Set the application default measurement units to match the document //measurement units. app.viewPreferences.horizontalMeasurementUnits = myDocument.viewPreferences.horizontalMeasurement Units; app.viewPreferences.verticalMeasurementUnits = myDocument.viewPreferences.verticalMeasurementUnit s; //Fill in the properties of the document preset with the corresponding //properties of the active document. with(myDocumentPreset){ //Note that the following gets the page margins from the margin preferences //of the document; to get the margin preferences from the active page, //replace "app.activeDocument" with "app.activeWindow.activePage" in the //following line (assuming the active window is a layout window). var myMarginPreferences = app.activeDocument.marginPreferences; left = myMarginPreferences.left; right = myMarginPreferences.right; top = myMarginPreferences.top; bottom = myMarginPreferences.bottom; columnCount = myMarginPreferences.columnCount; columnGutter = myMarginPreferences.columnGutter; documentBleedBottom = app.activeDocument.documentPreferences.documentBleedBottomOffset; documentBleedTop = app.activeDocument.documentPreferences.documentBleedTopOffset; documentBleedLeft = app.activeDocument.documentPreferences.documentBleedInsideOrLeftOffset; documentBleedRight = app.activeDocument.documentPreferences.documentBleedOutsideOrRightOffset; facingPages = app.activeDocument.documentPreferences.facingPages; pageHeight = app.activeDocument.documentPreferences.pageHeight; pageWidth = app.activeDocument.documentPreferences.pageWidth; pageOrientation = app.activeDocument.documentPreferences.pageOrientation; pagesPerDocument = app.activeDocument.documentPreferences.pagesPerDocument; slugBottomOffset = app.activeDocument.documentPreferences.slugBottomOffset; slugTopOffset = app.activeDocument.documentPreferences.slugTopOffset; slugInsideOrLeftOffset = app.activeDocument.documentPreferences.slugInsideOrLeftOffset; slugRightOrOutsideOffset = app.activeDocument.documentPreferences.slugRightOrOutsideOffset; } }
122
columnCount = 1; documentBleedBottom = "3p"; documentBleedTop = "3p"; documentBleedLeft = "3p"; documentBleedRight = "3p"; facingPages = true; pageOrientation = PageOrientation.portrait; pagesPerDocument = 1; slugBottomOffset = "18p"; slugTopOffset = "3p"; slugInsideOrLeftOffset = "3p"; slugRightOrOutsideOffset = "3p"; }
Using a preset
To create a new document using a document preset, use the document preset parameter as previously shown in the Creating a new document section.
123
//Set up the right page (recto). with(pages.item(1)){ with(marginPreferences){ columnCount = 3; columnGutter = "1p"; bottom = "6p" //"left" means inside; "right" means outside. left = "6p" right = "4p" top = "4p" } //Add a simple footer with a section number and page number. with(textFrames.add()){ geometricBounds = ["61p", "6p", "62p", "47p"]; insertionPoints.item(0).contents = SpecialCharacters.autoPageNumber; insertionPoints.item(0).contents = SpecialCharacters.emSpace; insertionPoints.item(0).contents = SpecialCharacters.sectionMarker; paragraphs.item(0).justification = Justification.rightAlign; } } }
To apply a master spread to a document page, use the appliedMaster property of the document page.
//ApplyMaster.jsx //An InDesign CS2 JavaScript //Applies a master spread to a page. //Assumes that the active document has a master page named "B-Master" //and at least three pages--page 3 is pages.item(2) because JavaScript arrays are zero-based. app.activeDocument.pages.item(2).appliedMaster = app.activeDocument.masterSpreads.item("B-Master");
Use the same property to apply a master spread to a master spread page:
//ApplyMasterToMaster.jsx //An InDesign CS2 JavaScript //Applies a master spread to a master page. //Assumes that the active document has master spread named "B-Master" //that is not the same as the first master spread in the document. app.activeDocument.masterSpreads.item(0).pages.item(0).appliedMaster = app.activeDocument. masterSpreads.item("B-Master");
124
try{ fontStyle = "Regular"; } catch(e){} try{ appliedLanguage = "English: USA"; } catch(e){} autoLeading = 100; balanceRaggedLines = false; baselineShift = 0; capitalization = Capitalization.normal; composer = "Adobe Paragraph Composer"; desiredGlyphScaling = 100; desiredLetterSpacing = 0; desiredWordSpacing = 100; dropCapCharacters = 0; if(dropCapCharacters != 0){ dropCapLines = 3; //Assumes that the application has a default character style named "myDropCap" dropCapStyle = app.characterStyles.item("myDropCap"); } fillColor = app.colors.item("Black"); fillTint = 100; firstLineIndent = "14pt"; gridAlignFirstLineOnly = false; horizontalScale = 100; hyphenateAfterFirst = 3; hyphenateBeforeLast = 4; hyphenateCapitalizedWords = false; hyphenateLadderLimit = 1; hyphenateWordsLongerThan = 5; hyphenation = true; hyphenationZone = "3p"; hyphenWeight = 9; justification = Justification.leftAlign; keepAllLinesTogether = false; keepLinesTogether = true; keepFirstLines = 2; keepLastLines = 2; keepWithNext = 0; kerningMethod = "Optical"; kerningValue = 0; leading = 14; leftIndent = 0; ligatures = true; maximumGlyphScaling = 100; maximumLetterSpacing = 0; maximumWordSpacing = 160; minimumGlyphScaling = 100; minimumLetterSpacing = 0; minimumWordSpacing = 80; noBreak = false; otfContextualAlternate = true; otfDiscretionaryLigature = true; otfFigureStyle = OTFFigureStyle.proportionalOldstyle; otfFraction = true; otfHistorical = true; otfOrdinal = false; otfSlashedZero = true; otfSwash = false; otfTitling = false; overprintFill = false; overprintStroke = false; pointSize = 11; position = Position.normal; rightIndent = 0; ruleAbove = false;
125
if(ruleAbove == true){ ruleAboveColor = app.colors.item("Black"); ruleAboveGapColor = app.swatches.item("None"); ruleAboveGapOverprint = false; ruleAboveGapTint = 100; ruleAboveLeftIndent = 0; ruleAboveLineWeight = .25; ruleAboveOffset = 14; ruleAboveOverprint = false; ruleAboveRightIndent = 0; ruleAboveTint = 100; ruleAboveType = app.strokeStyles.item("Solid"); ruleAboveWidth = RuleWidth.columnWidth; } ruleBelow = false; if(ruleBelow == true){ ruleBelowColor = app.colors.item("Black"); ruleBelowGapColor = app.swatches.item("None"); ruleBelowGapOverprint = false; ruleBelowGapTint = 100; ruleBelowLeftIndent = 0; ruleBelowLineWeight = .25; ruleBelowOffset = 0; ruleBelowOverprint = false; ruleBelowRightIndent = 0; ruleBelowTint = 100; ruleBelowType = app.strokeStyles.item("Solid"); ruleBelowWidth = RuleWidth.columnWidth; } singleWordJustification = SingleWordJustification.leftAlign; skew = 0; spaceAfter = 0; spaceBefore = 0; startParagraph = StartParagraph.anywhere; strikeThru = false; if(strikeThru == true){ strikeThroughColor = app.colors.item("Black"); strikeThroughGapColor = app.swatches.item("None"); strikeThroughGapOverprint = false; strikeThroughGapTint = 100; strikeThroughOffset = 3; strikeThroughOverprint = false; strikeThroughTint = 100; strikeThroughType = app.strokeStyles.item("Solid"); strikeThroughWeight = .25; } strokeColor = app.swatches.item("None"); strokeTint = 100; strokeWeight = 0; tracking = 0; underline = false; if(underline == true){ underlineColor = app.colors.item("Black"); underlineGapColor = app.swatches.item("None"); underlineGapOverprint = false; underlineGapTint = 100; underlineOffset = 3; underlineOverprint = false; underlineTint = 100; underlineType = app.strokeStyles.item("Solid"); underlineWeight = .25 } verticalScale = 100; }
126
to:
with(app.activeDocument.textDefaults){
127
128
//Create up a pair of paragraph styles for the page footer text. //These styles have only basic formatting. try{ myDocument.paragraphStyles.item("footer_left").name; } catch (myError){ myDocument.paragraphStyles.add({name:"footer_left", pointSize:11, leading:14}); } //Create up a pair of paragraph styles for the page footer text. try{ myDocument.paragraphStyles.item("footer_right").name; } catch (myError){ myDocument.paragraphStyles.add({name:"footer_right", basedOn:myDocument.paragraphStyles. item("footer_left"), justification:Justification.rightAlign, pointSize:11, leading:14}); } //Create a layer for guides. try{ myDocument.layers.item("GuideLayer").name; } catch (myError){ myDocument.layers.add({name:"GuideLayer"}); } //Create a layer for the footer items. try{ myDocument.layers.item("Footer").name; } catch (myError){ myDocument.layers.add({name:"Footer"}); } //Create a layer for the slug items. try{ myDocument.layers.item("Slug").name; } catch (myError){ myDocument.layers.add({name:"Slug"}); } //Create a layer for the body text. try{ myDocument.layers.item("BodyText").name; } catch (myError){ myDocument.layers.add({name:"BodyText"}); } with(myDocument.viewPreferences){ rulerOrigin = RulerOrigin.pageOrigin; horizontalMeasurementUnits = MeasurementUnits.points; verticalMeasurementUnits = MeasurementUnits.points; } //Document baseline grid and document grid with(myDocument.gridPreferences){ baselineStart = 56; baselineDivision = 14; baselineShown = false; horizontalGridlineDivision = 14; horizontalGridSubdivision = 5 verticalGridlineDivision = 14; verticalGridSubdivision = 5 documentGridShown = false; } //Document XMP information. with (myDocument.metadataPreferences){ author = "Olav Martin Kvern"; copyrightInfoURL = "http://www.adobe.com"; copyrightNotice = "This document is not copyrighted."; copyrightStatus = CopyrightStatus.no; description = "Example 7 x 9 book layout";
129
documentTitle = "Example"; jobName = "7 x 9 book layout template"; keywords = ["7 x 9", "book", "template"]; var myNewContainer = createContainerItem("http://ns.adobe.com/xap/1.0/", "email"); setProperty("http://ns.adobe.com/xap/1.0/", "email/*[1]", "okvern@adobe.com"); } //Set up the master spread. with(myDocument.masterSpreads.item(0)){ with(pages.item(0)){ //Left and right are reversed for left-hand pages (becoming "inside" and "outside"-//this is also true in the InDesign user interface). var myBottomMargin = myDocument.documentPreferences.pageHeight - marginPreferences.bottom; var myRightMargin = myDocument.documentPreferences.pageWidth - marginPreferences.left; guides.add(myDocument.layers.item("GuideLayer"), {orientation:HorizontalOrVertical. vertical,location:marginPreferences.right}); guides.add(myDocument.layers.item("GuideLayer"), {orientation:HorizontalOrVertical.vertical, location:myRightMargin}); guides.add(myDocument.layers.item("GuideLayer"), {orientation:HorizontalOrVertical.horizontal, location:marginPreferences.top, fitToPage:false}); guides.add(myDocument.layers.item("GuideLayer"), {orientation:HorizontalOrVertical.horizontal, location:myBottomMargin, fitToPage:false}); guides.add(myDocument.layers.item("GuideLayer"), {orientation:HorizontalOrVertical.horizontal, location:myBottomMargin + 14, fitToPage:false}); guides.add(myDocument.layers.item("GuideLayer"), {orientation:HorizontalOrVertical.horizontal, location:myBottomMargin + 28, fitToPage:false}); var myLeftFooter = textFrames.add(myDocument.layers.item("Footer"), undefined, undefined, {geom etricBounds:[myBottomMargin+14, marginPreferences.right, myBottomMargin+28, myRightMargin]}) myLeftFooter.parentStory.insertionPoints.item(0).contents = SpecialCharacters.sectionMarker; myLeftFooter.parentStory.insertionPoints.item(0).contents = SpecialCharacters.emSpace; myLeftFooter.parentStory.insertionPoints.item(0).contents = SpecialCharacters.autoPageNumber; myLeftFooter.parentStory.characters.item(0).appliedCharacterStyle = myDocument.characterStyles. item("page_number"); myLeftFooter.parentStory.paragraphs.item(0).applyStyle(myDocument.paragraphStyles.item("footer_ left", false)); //Slug information. with(myDocument.metadataPreferences){ var myString = "Author:\t" + author + "\tDescription:\t" + description + "\rCreation Date:\ t" + new Date + "\tEmail Contact\t" + getProperty("http://ns.adobe.com/xap/1.0/", "email/*[1]"); } var myLeftSlug = textFrames.add(myDocument.layers.item("Slug"), undefined, undefined, {geom etricBounds:[myDocument.documentPreferences.pageHeight+36, marginPreferences.right, myDocument. documentPreferences.pageHeight + 144, myRightMargin], contents:myString}); myLeftSlug.parentStory.tables.add(); //Body text master text frame. var myLeftFrame = textFrames.add(myDocument.layers.item("BodyText"), undefined, undefined, {geometricBounds:[marginPreferences.top, marginPreferences.right, myBottomMargin, myRightMargin]}); } with(pages.item(1)){ var myBottomMargin = myDocument.documentPreferences.pageHeight - marginPreferences.bottom; var myRightMargin = myDocument.documentPreferences.pageWidth - marginPreferences.right; guides.add(myDocument.layers.item("GuideLayer"), {orientation:HorizontalOrVertical. vertical,location:marginPreferences.left}); guides.add(myDocument.layers.item("GuideLayer"), {orientation:HorizontalOrVertical.vertical, location:myRightMargin}); var myRightFooter = textFrames.add(myDocument.layers.item("Footer"), undefined, undefined, {geometricBounds:[myBottomMargin+14, marginPreferences.left, myBottomMargin+28, myRightMargin]}) myRightFooter.parentStory.insertionPoints.item(0).contents = SpecialCharacters.autoPageNumber; myRightFooter.parentStory.insertionPoints.item(0).contents = SpecialCharacters.emSpace; myRightFooter.parentStory.insertionPoints.item(0).contents = SpecialCharacters.sectionMarker; myRightFooter.parentStory.characters.item(-1).appliedCharacterStyle = myDocument. characterStyles.item("page_number"); myRightFooter.parentStory.paragraphs.item(0).applyStyle(myDocument.paragraphStyles. item("footer_right", false)); //Slug information. var myRightSlug = textFrames.add(myDocument.layers.item("Slug"), undefined, undefined, {geo metricBounds:[myDocument.documentPreferences.pageHeight+36, marginPreferences.left, myDocument. documentPreferences.pageHeight + 144, myRightMargin], contents:myString});
130
myRightSlug.parentStory.tables.add(); //Body text master text frame. var myRightFrame = textFrames.add(myDocument.layers.item("BodyText"), undefined, undefined, {geometricBounds:[marginPreferences.top, marginPreferences.left, myBottomMargin, myRightMargin], previousTextFrame:myLeftFrame}); } } //Add section marker text--this text will appear in the footer. myDocument.sections.item(0).marker = "Section 1"; //When you link the master page text frames, one of the frames sometimes becomes selected. Deselect it. app.select(NothingEnum.nothing, undefined);
Printing a document
The following script prints the active document using the current print preferences:
//PrintDocument.jsx //An InDesign CS2 JavaScript //Prints the active document. app.activeDocument.print();
131
reverseOrder = false; //pageRange can be either PageRange.allPages or a page range string. pageRange = PageRange.allPages; printSpreads = false; printMasterPages = false; //If the printer property is set to Printer.postScript file, then //the printFile property contains the file path to the output file. //printFile = "/c/test.ps"; sequence = Sequences.all; //-------------------------------------------------------------------------------//Properties corresponding to the controls in the Output panel of the //Print dialog box. //-------------------------------------------------------------------------------negative = true; colorOutput = ColorOutputModes.separations; //Note the lowercase "i" in "Builtin" trapping = Trapping.applicationBuiltin; screening = "175 lpi/2400 dpi"; flip = Flip.none; //If trapping is on, attempting to set the following properties will //generate an error. if(trapping == Trapping.off){ printBlack = true; printCyan = true; printMagenta = true; printYellow = true; } //Only change the ink angle and frequency when you want to override the //screening set by the screening specified by the screening property. //blackAngle = 45; //blackFrequency = 175; //cyanAngle = 15; //cyanFrequency = 175; //magentaAngle = 75; //magentaFreqency = 175; //yellowAngle = 0; //yellowFrequency = 175; //The following properties are not needed (because colorOutput is //set to separations). //compositeAngle = 45; //compositeFrequency = 175; //simulateOverprint = false; //If trapping is on, setting the following properties will produce an error. if(trapping == Trapping.off){ printBlankPages = false; printGuidesGrids = false; printNonprinting = false; } //-------------------------------------------------------------------------------//Properties corresponding to the controls in the Setup panel of the //Print dialog box. //-------------------------------------------------------------------------------paperSize = PaperSizes.custom; //Page width and height are ignored if paperSize is not PaperSizes.custom. //paperHeight = 1200; //paperWidth = 1200; printPageOrientation = PrintPageOrientation.portrait; pagePosition = PagePositions.centered; paperGap = 0; paperOffset = 0; paperTransverse = false; scaleHeight = 100; scaleWidth = 100; scaleMode = ScaleModes.scaleWidthHeight; scaleProportional = true; //If trapping is on, attempting to set the following properties will //produce an error. if(trapping == Trapping.off){
132
textAsBlack = false; thumbnails = false; //The following properties is not needed because thumbnails is set to false. //thumbnailsPerPage = 4; tile = false; //The following properties are not needed because tile is set to false. //tilingOverlap = 12; //tilingType = TilingTypes.auto; }
//-------------------------------------------------------------------------------//Properties corresponding to the controls in the Marks and Bleed panel of //the Print dialog box. //-------------------------------------------------------------------------------//Set the following property to true to print all printers marks. //allPrinterMarks = true; useDocumentBleedToPrint = false; //If useDocumentBleedToPrint = false then setting any of the bleed properties //will result in an error. //Get the bleed amounts from the documents bleed and add a bit. bleedBottom = app.activeDocument.documentPreferences.documentBleedBottomOffset+3; bleedTop = app.activeDocument.documentPreferences.documentBleedTopOffset+3; bleedInside = app.activeDocument.documentPreferences.documentBleedInsideOrLeftOffset+3; bleedOutside = app.activeDocument.documentPreferences.documentBleedOutsideOrRightOffset+3; //If any bleed area is greater than zero, then export the bleed marks. if(bleedBottom == 0 && bleedTop == 0 && bleedInside == 0 && bleedOutside == 0){ bleedMarks = true; } else{ bleedMarks = false; } colorBars = true; cropMarks = true; includeSlugToPrint = false; markLineWeight = MarkLineWeight.p125pt markOffset = 6; //markType = MarkTypes.default; pageInformationMarks = true; registrationMarks = true;
//-------------------------------------------------------------------------------//Properties corresponding to the controls in the Graphics panel of the //Print dialog box. //-------------------------------------------------------------------------------sendImageData = ImageDataTypes.allImageData; fontDownloading = FontDownloading.complete; downloadPPDFOnts = true; try{ dataFormat = DataFormat.binary; } catch(e){} try{ postScriptLevel = PostScriptLevels.level3; } catch(e){} //-------------------------------------------------------------------------------//Properties corresponding to the controls in the Color Management panel of //the Print dialog box. //-------------------------------------------------------------------------------//If the useColorManagement property of app.colorSettings is false, //attempting to set the following properties will return an error. try{ sourceSpace = SourceSpaces.useDocument; intent = RenderingIntent.useColorSettings; crd = ColorRenderingDictionary.useDocument;
133
profile = Profile.postscriptCMS; } catch(e){} //-------------------------------------------------------------------------------//Properties corresponding to the controls in the Advanced panel of the //Print dialog box. //-------------------------------------------------------------------------------opiImageReplacement = false; omitBitmaps = false; omitEPS = false; omitPDF = false; //The following line assumes that you have a flattener preset named "high quality flattener". try{ flattenerPresetName = "high quality flattener"; } catch(e){} ignoreSpreadOverrides = false; }
134
catch(e){} try{ myPreset.collating = collating; } catch(e){} try{ myPreset.reverseOrder = reverseOrder; } catch(e){} try{ myPreset.pageRange = pageRange; } catch(e){} try{ myPreset.printSpreads = printSpreads; } catch(e){} try{ myPreset.printMasterPages = printMasterPages; } catch(e){} try{ myPreset.printFile = printFile; } catch(e){} try{ myPreset.sequence = sequence; } catch(e){} try{ myPreset.printBlankPages = printBlankPages; } catch(e){} try{ myPreset.printGuidesGrids = printGuidesGrids; } catch(e){} try{ myPreset.printNonprinting = printNonprinting; } catch(e){} try{ myPreset.paperSize = paperSize; } catch(e){} try{ myPreset.paperHeight = paperHeight; } catch(e){} try{ myPreset.paperWidth = paperWidth; } catch(e){} try{ myPreset.printPageOrientation = printPageOrientation; } catch(e){} try{ myPreset.pagePosition = pagePosition; } catch(e){} try{ myPreset.paperGap = paperGap; } catch(e){} try{ myPreset.paperOffset = paperOffset; }
135
catch(e){} try{ myPreset.paperTransverse = paperTransverse; } catch(e){} try{ myPreset.scaleHeight = scaleHeight; } catch(e){} try{ myPreset.scaleWidth = scaleWidth; } catch(e){} try{ myPreset.scaleMode = scaleMode; } catch(e){} try{ myPreset.scaleProportional = scaleProportional; } catch(e){} try{ myPreset.textAsBlack = textAsBlack; } catch(e){} try{ myPreset.thumbnails = thumbnails; } catch(e){} try{ myPreset.thumbnailsPerPage = thumbnailsPerPage; } catch(e){} try{ myPreset.tile = tile; } catch(e){} try{ myPreset.tilingType = tilingType; } catch(e){} try{ myPreset.tilingOverlap = tilingOverlap; } catch(e){} try{ myPreset.allPrinterMarks = allPrinterMarks; } catch(e){} try{ myPreset.useDocumentBleedToPrint = useDocumentBleedToPrint; } catch(e){} try{ myPreset.bleedBottom = bleedBottom; } catch(e){} try{ myPreset.bleedTop = bleedTop; } catch(e){} try{ myPreset.bleedInside = bleedInside; } catch(e){} try{ myPreset.bleedOutside = bleedOutside; }
136
catch(e){} try{ myPreset.bleedMarks = bleedMarks; } catch(e){} try{ myPreset.colorBars = colorBars; } catch(e){} try{ myPreset.cropMarks = cropMarks; } catch(e){} try{ myPreset.includeSlugToPrint = includeSlugToPrint; } catch(e){} try{ myPreset.markLineWeight = markLineWeight; } catch(e){} try{ myPreset.markOffset = markOffset; } catch(e){} try{ myPreset.markType = markType; } catch(e){} try{ myPreset.pageInformationMarks = pageInformationMarks; } catch(e){} try{ myPreset.registrationMarks = registrationMarks; } catch(e){} try{ myPreset.negative = negative; } catch(e){} try{ myPreset.colorOutput = colorOutput ; } catch(e){} try{ myPreset.trapping = trapping; } catch(e){} try{ myPreset.screening = screening; } catch(e){} try{ myPreset.flip = flip; } catch(e){} try{ myPreset.printBlack = printBlack; } catch(e){} try{ myPreset.printCyan = printCyan; } catch(e){} try{ myPreset.printMagenta = printMagenta; }
137
catch(e){} try{ myPreset.printYellow = printYellow; } catch(e){} try{ myPreset.blackAngle = blackAngle; } catch(e){} try{ myPreset.blackFrequency = blackFrequency; } catch(e){} try{ myPreset.cyanAngle = cyanAngle; } catch(e){} try{ myPreset.cyanFrequency = cyanFrequency; } catch(e){} try{ myPreset.magentaAngle = magentaAngle; } catch(e){} try{ myPreset.magentaFreqency = magentaFreqency; } catch(e){} try{ myPreset.yellowAngle = yellowAngle; } catch(e){} try{ myPreset.yellowFrequency = yellowFrequency; } catch(e){} try{ myPreset.compositeAngle = compositeAngle; } catch(e){} try{ myPreset.compositeFrequency = compositeFrequency; } catch(e){} try{ myPreset.simulateOverprint = simulateOverprint; } catch(e){} try{ myPreset.sendImageData = sendImageData; } catch(e){} try{ myPreset.fontDownloading = fontDownloading; } catch(e){} try{ myPreset.downloadPPDFOnts = downloadPPDFOnts; } catch(e){} try{ myPreset.dataFormat = dataFormat; } catch(e){} try{ myPreset.postScriptLevel = postscriptLevel; }
138
catch(e){} try{ myPreset.sourceSpace = sourceSpace; } catch(e){} try{ myPreset.intent = intent; } catch(e){} try{ myPreset.crd = crd; } catch(e){} try{ myPreset.profile = profile; } catch(e){} try{ myPreset.opiImageReplacement = opiImageReplacement; } catch(e){} try{ myPreset.omitBitmaps = omitBitmaps; } catch(e){} try{ myPreset.omitEPS = omitEPS; } catch(e){} try{ myPreset.omitPDF = omitPDF; } catch(e){} try{ myPreset.flattenerPresetName = flattenerPresetName ; } catch(e){} try{ myPreset.ignoreSpreadOverrides = ignoreSpreadOverrides; } catch(e){} alert("Done!"); }
139
The next example shows an example set of PDF export preferences (this set is not completeno security features are changed).
//ExportPDFWithOptions.jsx //An InDesign CS2 JavaScript //Sets PDF export options, then exports the active document as PDF. with(app.pdfExportPreferences){ //Basic PDF output options. pageRange = PageRange.allPages; acrobatCompatibility = AcrobatCompatibility.acrobat6;
140
exportGuidesAndGrids = false; exportLayers = false; exportNonPrintingObjects = false; exportReaderSpreads = false; generateThumbnails = false; try{ ignoreSpreadOverrides = false; } catch(e){} includeBookmarks = true; includeHyperlinks = true; includeICCProfiles = true; includeSlugWithPDF = false; includeStructure = false; interactiveElements = false; //Setting subsetFontsBelow to zero disallows font subsetting; //set subsetFontsBelow to some other value to use font subsetting. subsetFontsBelow = 0; // //Bitmap compression/sampling/quality options. colorBitmapCompression = BitmapCompression.zip; colorBitmapQuality = CompressionQuality.eightBit; colorBitmapSampling = Sampling.none; //thresholdToCompressColor is not needed in this example. //colorBitmapSamplingDPI is not needed when colorBitmapSampling is set to none. grayscaleBitmapCompression = BitmapCompression.zip; grayscaleBitmapQuality = CompressionQuality.eightBit; grayscaleBitmapSampling = Sampling.none; //thresholdToCompressGray is not needed in this example. //grayscaleBitmapSamplingDPI is not needed when grayscaleBitmapSampling is //set to none. monochromeBitmapCompression = BitmapCompression.zip; monochromeBitmapSampling = Sampling.none; //thresholdToCompressMonochrome is not needed in this example. //monochromeBitmapSamplingDPI is not needed when monochromeBitmapSampling is //set to none. // //Other compression options. compressionType = PDFCompressionType.compressNone; compressTextAndLineArt = true; contentToEmbed = PDFContentToEmbed.embedAll; cropImagesToFrames = true; optimizePDF = true; // //Printers marks and prepress options. //Get the bleed amounts from the documents bleed. bleedBottom = app.activeDocument.documentPreferences.documentBleedBottomOffset; bleedTop = app.activeDocument.documentPreferences.documentBleedTopOffset; bleedInside = app.activeDocument.documentPreferences.documentBleedInsideOrLeftOffset; bleedOutside = app.activeDocument.documentPreferences.documentBleedOutsideOrRightOffset; //If any bleed area is greater than zero, then export the bleed marks. if(bleedBottom == 0 && bleedTop == 0 && bleedInside == 0 && bleedOutside == 0){ bleedMarks = true; } else{ bleedMarks = false; } colorBars = true; colorTileSize = 128; grayTileSize = 128; cropMarks = true; omitBitmaps = false; omitEPS = false; omitPDF = false; pageInformationMarks = true; pageMarksOffset = 12; pdfColorSpace = PDFColorSpace.unchangedColorSpace; //Default mark type.
141
pdfMarkType = 1147563124; printerMarkWeight = PDFMarkWeight.p125pt; registrationMarks = true; try{ simulateOverprint = false; } catch(e){} useDocumentBleedWithPDF = true; //Set viewPDF to true to open the PDF in Acrobat or Adobe Reader. viewPDF = false; } //Now export the document. Youll have to fill in your own file path. app.activeDocument.exportFile(ExportFormat.pdfType, File(/c/myTestDocument.pdf), false);
142
app.epsExportPreferences.pageRange = "1-3, 6, 9"; var myFile = new File("/c/myTestFile.eps"); app.activeDocument.exportFile(ExportFormat.epsType, myFile, false);
143
Create a new document Open a document Close a document Save a document Set the page size and document length Dene bleed and slug areas Specify page columns and margins
Change the pasteboard's appearance Use guides and grids Change measurement units and ruler origin Dene and apply document presets Set up master pages (master spreads) Set text-formatting defaults Add XMP metadata (information about a le) Create a document template Print a document Export a document as PDF Export pages of a document as EPS
Note: If you have not already worked through Chapter 3, Getting Started with InDesign Scripting, you might want to do so before continuing with this chapter, which assumes that you have already read that chapter and know how to create a script.
144
The Document.Add method can take two optional parameters, as shown in the following script:
Rem Rem Rem Rem Rem Rem Rem Rem Rem Set Set Rem Rem Rem MakeDocumentWithParameters.vbs An InDesign CS2 VBScript Creates a new document. The first parameter (ShowingWindow) controls the visibility of the document. Hidden documents are not minimized, and will not appear until you create a new window. The second parameter (DocumentPreset) specifies the document preset to use. The following line assumes that you have defined a document preset named "Flyer". myInDesign = CreateObject("InDesign.Application.CS2") myDocument = myInDesign.Documents.Add(True, myInDesign.DocumentPresets.Item("Flyer")) If you set the ShowingWindow parameter to False, you can show the document by creating a new window. Set myLayoutWindow = myDocument.Windows.Add
Opening a document
The following example script shows how to open an existing document:
Rem Rem Rem Set Set OpenDocument.vbs An InDesign CS2 VBScript Opens an existing document. Youll have to fill in your own file path. myInDesign = CreateObject("InDesign.Application.CS2") myDocument = myInDesign.Open("c:\myTestDocument.indd")
You can choose to prevent the document from displaying (hide it) by setting the ShowingWindow parameter of the Open method to false (the default is true). You might want to do this to improve performance of a script. To show a hidden document, create a new window, as shown in the following script:
Rem Rem Rem Rem Set Set Rem Rem Rem Rem Set OpenDocumentInBackground.vbs An InDesign CS2 VBScript Opens an existing document in the background, then shows the document. Youll have to fill in your own file path. myInDesign = CreateObject("InDesign.Application.CS2") myDocument = myInDesign.Open("c:\myTestDocument.indd", False) At this point, you can do things with the document without showing the document window. In some cases, scripts will run faster when the document window is not visible. When you want to show the hidden document, create a new window. myLayoutWindow = myDocument.Windows.Add
145
Closing a document
The Close method closes a document:
Rem CloseDocument.vbs Rem An InDesign CS2 VBScript Rem Closes the active document. Set myInDesign = CreateObject("InDesign.Application.CS2") myInDesign.ActiveDocument.Close Rem Note that you could also use: Rem myInDesign.Documents.Item(1).Close
For the last line, note that document 1 always refers to the front-most document. The Close method can take up to two optional parameters:
Rem CloseWithParameters.vbs Rem An InDesign CS2 VBScript Rem Use idSaveOptions.idYes to save the document,idSaveOptions.idNo Rem to close the document without saving, or idSaveOptions.idAsk to Rem display a prompt. If you use idSaveOptions.idYes, youll need to Rem provide a reference to a file to save to in the second parameter (SavingIn). Set myInDesign = CreateObject("InDesign.Application.CS2") Rem If the file has not been saved, display a prompt. If myInDesign.ActiveDocument.Saved <> True Then myInDesign.ActiveDocument.Close idSaveOptions.idAsk Rem Or, to save to a specific file name: Rem myFile = "c:\myTestDocument.indd" Rem myInDesign.ActiveDocument.Close idSaveOptions.idYes, myFile Else Rem If the file has already been saved, save it. myInDesign.ActiveDocument.Close idSaveOptions.idYes End If
Saving a document
In the InDesign user interface, you save a le by choosing Save from the File menu, and you save a le to another le name by choosing Save As. In InDesign scripting, the Save method can do either operation:
Rem SaveDocument.vbs Rem An InDesign CS2 VBScript Rem If the active document has been changed since it was last saved, save it. Set myInDesign = CreateObject("InDesign.Application.CS2") If myInDesign.ActiveDocument.Modified = True Then myInDesign.ActiveDocument.Save End If
The Save method has two optional parameters: The rst (To) species the le to save to; the second (Stationery) can be set to true to save the document as a template:
Rem Rem Rem Set SaveDocumentAs.vbs An InDesign C2S VBScript If the active document has not been saved (ever), save it. myInDesign = CreateObject("InDesign.Application.CS2")
146
If myDocument.Saved = False Then Rem If you do not provide a file name, Rem InDesign displays the Save dialog box. myInDesign.ActiveDocument.Save "c:\myTestDocument.indd" End If
Note: The Application object also has a DocumentPreferences object. You can set the application defaults for page height, page width, and other properties by changing the properties of this object.
147
you might want to omit slug information for the nal printing of a document. The following script sets up the bleed and slug for a new document:
Rem BleedAndSlug.vbs Rem An InDesign CS2 VBScript Rem Create a new document. Set myInDesign = CreateObject("InDesign.Application.CS2") Set myDocument = myInDesign.Documents.Add Rem The bleed and slug properties belong to the documentPreferences object. With myDocument.DocumentPreferences Rem Bleed .DocumentBleedBottomOffset = "3p" .DocumentBleedTopOffset = "3p" .DocumentBleedInsideOrLeftOffset = "3p" .DocumentBleedOutsideOrRightOffset = "3p" Rem Slug .SlugBottomOffset = "18p" .SlugTopOffset = "3p" .SlugInsideOrLeftOffset = "3p" .SlugRightOrOutsideOffset = "3p" End With
If all the bleed distances are equal, as in the preceding example, you can alternatively use the DocumentBleedUniformSize property:
Rem UniformBleed.vbs Rem An InDesign CS2 VBScript Rem Create a new document. Set myInDesign = CreateObject("InDesign.Application.CS2") Set myDocument = myInDesign.Documents.Add Rem The bleed properties belong to the documentPreferences object. With myDocument.DocumentPreferences Rem Bleed .DocumentBleedTopOffset = "3p" .DocumentBleedUniformSize = True End With
If all the slug distances are equal, you can instead use the DocumentSlugUniformSize property:
Rem UniformSlug.vbs Rem An InDesign CS2 VBScript Rem Create a new document. Set myInDesign = CreateObject("InDesign.Application.CS2") Set myDocument = myInDesign.Documents.Add Rem The slug properties belong to the documentPreferences object. With myDocument.DocumentPreferences Rem Slug: .SlugTopOffset = "3p" .DocumentSlugUniformSize = True End With
In addition to setting the bleed and slug widths and heights, you can control the color used to draw the guides dening the bleed and slug. This property is not in the DocumentPreferences objectinstead, its in the PasteboardPreferences object:
Rem BleedSlugGuideColors.vbs Rem An InDesign CS2 VBScript Rem Set the colors used to display the bleed and slug guides. Set myInDesign = CreateObject("InDesign.Application.CS2") With myInDesign.ActiveDocument.PasteboardPreferences Rem Any of InDesigns guides can use the UIColors constants... .BleedGuideColor = idUIColors.idCuteTeal .SlugGuideColor = idUIColors.idCharcoal Rem ...or you can specify an array of RGB values (with values from 0 to 255) Rem .BleedGuideColor = Array(0, 198, 192) Rem .SlugGuideColor = Array(192, 192, 192) End With
148
InDesign does not allow you to create a page that is smaller than the sum of the relevant margins, that is, the width of the page must be greater than the sum of the current left and right page margins, and the height of the page must be greater than the sum of the top and bottom margins. If youre creating very small pages (for example, for individual newspaper advertisements) using the InDesign user interface, you can easily set the correct margin sizes as you create the document by entering new values in the document default page Margin elds in the New Document dialog box. From scripting, however, the solution is not as clearwhen you create a document, it uses the application default margin preferences. These margins are applied to all pages of the document, including master pages. Setting the document margin preferences aects only new pages and has no eect on existing pages. If you try to set the page height and page width to values smaller than the sum of the corresponding margins on any of the existing pages, InDesign does not change the page size. There are two solutions. The rst is to set the margins of existing pages before trying to change the page size:
Rem PageMarginsForSmallPages.vbs Rem An InDesign CS2 VBScript Rem Creates a new document and sets up page margins. Set myInDesign = CreateObject("InDesign.Application.CS2") Set myDocument = myInDesign.Documents.Add myDocument.ViewPreferences.HorizontalMeasurementUnits = idMeasurementUnits.idPoints myDocument.ViewPreferences.VerticalMeasurementUnits = idMeasurementUnits.idPoints With myDocument.MarginPreferences .Top = 0 .Left = 0 .Bottom = 0 .Right = 0 .ColumnCount = 1 .ColumnGutter = 0 End With Rem The following assumes that your default document contains a single page. With myDocument.Pages.Item(1).MarginPreferences .Top = 0 .Left = 0 .Bottom = 0 .Right = 0 .ColumnCount = 1 .ColumnGutter = 0 End With
149
Rem The following assumes that your default master spread contains two pages. With myDocument.MasterSpreads.Item(1).Pages.Item(1).MarginPreferences .Top = 0 .Left = 0 .Bottom = 0 .Right = 0 .ColumnCount = 1 .ColumnGutter = 0 End With With myDocument.MasterSpreads.Item(1).Pages.Item(2).MarginPreferences .Top = 0 .Left = 0 .Bottom = 0 .Right = 0 .ColumnCount = 1 .ColumnGutter = 0 End With myDocument.DocumentPreferences.PageHeight = "1p" myDocument.DocumentPreferences.PageWidth = 6p
Alternatively, you can change the application default margin preferences before you create the document:
Rem ApplicationPageMargins.vbs Rem An InDesign CS2 VBScript Rem Sets the application default page margins. All new documents Rem will be created using these settings. Existing documents Rem will be unaffected. Set myInDesign = CreateObject("InDesign.Application.CS2") With myInDesign.MarginPreferences Rem Save the current application default margin preferences. myY1 = .Top myX1 = .Left myY2 = .Bottom myX2 = .Right Rem Set the application default margin preferences. .Top = 0 .Left = 0 .Bottom = 0 .Right = 0 End With Rem Create a new example document to demonstrate the change. Set myDocument = myInDesign.Documents.Add myDocument.DocumentPreferences.PageHeight = "1p" myDocument.DocumentPreferences.PageWidth = "6p" Rem Reset the application default margin preferences to their former state. With myInDesign.MarginPreferences .Top = myY1 .Left = myX1 .Bottom = myY2 .Right = myX2 End With
150
Rem You can use either a number or a measurement string to set the space above/below. .MinimumSpaceAboveAndBelow = "12p" Rem You can set the preview background color (which youll only see Rem in Preview mode) to any of the predefined UIColor constants... .PreviewBackgroundColor = idUIColors.idGrassGreen Rem ...or you can specify an array of RGB values (with values from 0 to 255) Rem .PreviewBackgroundColor = Array(192, 192, 192) End With
Dening guides
A guide in InDesign gives you an easy way to position objects on the pages of your document. Heres an example use of guides:
Rem Guides.vbs Rem An InDesign CS2 VBScript Rem Create a new document, add guides, and set guide properties. Set myInDesign = CreateObject("InDesign.Application.CS2") Set myDocument = myInDesign.Documents.Add myPageWidth = myDocument.DocumentPreferences.PageWidth myPageHeight = myDocument.DocumentPreferences.PageHeight With myDocument.Pages.Item(1) Set myMarginPreferences = .MarginPreferences Rem Place guides at the margins of the page. With .Guides.Add .Orientation = idHorizontalOrVertical.idVertical .Location = myMarginPreferences.Left End With With .Guides.Add .Orientation = idHorizontalOrVertical.idVertical .Location = (myPageWidth - myMarginPreferences.Right) End With With .Guides.Add .Orientation = idHorizontalOrVertical.idHorizontal .Location = myMarginPreferences.Top End With With .Guides.Add .Orientation = idHorizontalOrVertical.idHorizontal .Location = (myPageHeight - myMarginPreferences.Bottom) End With Rem Place a guide at the vertical center of the page. With .Guides.Add .Orientation = idHorizontalOrVertical.idVertical .Location = (myPageWidth / 2) End With Rem Place a guide at the horizontal center of the page. With .Guides.Add .Orientation = idHorizontalOrVertical.idHorizontal .Location = (myPageHeight / 2) End With End With
Horizontal guides can be limited to a given page, or can extend across all pages in a spread. With InDesign scripting, you can control this using the FitToPage property. (This property is ignored by vertical guides.)
Rem Rem Rem Set SpreadAndPageGuides.vbs An InDesign CS2 VBScript Demonstrates the difference between spread guides and page guides. myInDesign = CreateObject("InDesign.Application.CS2")
151
Set myDocument = myInDesign.Documents.Add myDocument.DocumentPreferences.FacingPages = True myDocument.DocumentPreferences.PagesPerDocument = 3 With myDocument.Spreads.Item(2) Rem Note the difference between these two guides on pages 2 and 3. With .Guides.Add .Orientation = idHorizontalOrVertical.idHorizontal .Location = "6p" .FitToPage = True End With With .Guides.Add .Orientation = idHorizontalOrVertical.idHorizontal .Location = "9p" .FitToPage = False End With End With
You can use scripting to change the layer, color, and visibility of guides, just as you can from the user interface.
Rem GuideOptions.vbs Rem An InDesign CS2 VBScript Rem Shows how to set guide options. Set myInDesign = CreateObject("InDesign.Application.CS2") Set myDocument = myInDesign.Documents.Add Rem Create a layer named "guide layer". Set myLayer = myDocument.Layers.Add myLayer.Name = "guide layer" Rem Add a series of guides to page 1. With myDocument.Pages.Item(1) Rem Create a guide on the layer we created above. With .Guides.Add(myLayer) .Orientation = idHorizontalOrVertical.idHorizontal .Location = "12p" End With Rem Another way to make a guide on a specific layer. With .Guides.Add() .ItemLayer = myLayer .Orientation = idHorizontalOrVertical.idHorizontal .Location = "14p" End With Rem Make a locked guide. With .Guides.Add() .ItemLayer = myLayer .Orientation = idHorizontalOrVertical.idHorizontal .Location = "16p" .Locked = True End With Rem Set the view threshold of a guide. With .Guides.Add() .ItemLayer = myLayer .Orientation = idHorizontalOrVertical.idHorizontal .Location = "18p" .ViewThreshold = 100 End With Rem Set the guide color of a guide using a UIColors constant. With .Guides.Add() .ItemLayer = myLayer .Orientation = idHorizontalOrVertical.idHorizontal .Location = "18p" .GuideColor = idUIColors.idGray End With
152
Rem Set the guide color of a guide using an RGB array. With .Guides.Add() .ItemLayer = myLayer .Orientation = idHorizontalOrVertical.idHorizontal .Location = "22p" .GuideColor = Array(192, 192, 192) End With End With
You can also create guides using the CreateGuides method of spreads and master spreads.
Rem CreateGuides.vbs Rem An InDesign CS2 VBScript Rem Add a series of guides using the createGuides method. Set myInDesign = CreateObject("InDesign.Application.CS2") Set myDocument = myInDesign.Documents.Add Rem Parameters (all optional): row count, column count, row gutter, Rem column gutter,guide color, fit margins, remove existing, layer. Rem Note that the createGuides method does not take an RGB array Rem for the guide color parameter. myDocument.Spreads.Item(1).CreateGuides 4, 4, "1p", "1p", idUIColors.idGray, True, True, myDocument.Layers.Item(0)
153
With myDocument.GuidePreferences .GuidesInBack = True .GuidesLocked = False .GuidesShown = True .GuidesSnapto = True End With With myDocument.GridPreferences .DocumentGridShown = False .DocumentGridSnapto = True Rem Objects "snap" to the baseline grid when Rem GuidePreferences.GuideSnapTo is set to true. .BaselineGridShown = True End With
If youre writing a script that needs to use a specic measurement system, you can change the measurement units at the beginning of the script and then restore the original measurement units at the end of the script, as shown in the following example:
Rem ResetMeasurementUnits.vbs Rem An InDesign CS2 VBScript Rem Changes, then resets the active documents measurement units. Rem Assumes you have a document open. Set myInDesign = CreateObject("InDesign.Application.CS2") Set myDocument = myInDesign.ActiveDocument With myDocument.ViewPreferences myOldXUnits = .HorizontalMeasurementUnits myOldYUnits = .VerticalMeasurementUnits .HorizontalMeasurementUnits = idMeasurementUnits.idPoints .VerticalMeasurementUnits = idMeasurementUnits.idPoints End With
154
Rem At this point, you can perform any series of script actions that Rem depend on the measurement units youve set. At the end of the Rem script, reset the units to their original state. With myDocument.ViewPreferences .HorizontalMeasurementUnits = myOldXUnits .VerticalMeasurementUnits = myOldYUnits End With
155
.PagesPerDocument = myDocument.DocumentPreferences.PagesPerDocument .SlugBottomOffset = myDocument.DocumentPreferences.SlugBottomOffset .SlugTopOffset = myDocument.DocumentPreferences.SlugTopOffset .SlugInsideOrLeftOffset = myDocument.DocumentPreferences.SlugInsideOrLeftOffset .SlugRightOrOutsideOffset = myDocument.DocumentPreferences.SlugRightOrOutsideOffset End With End If
Using a preset
To create a new document using a Document Preset, use the DocumentPreset parameter as previously shown in the Creating a new document section.
156
Rem Set up the first master spread in a new document. Set myDocument = myInDesign.Documents.Add Rem Set up the document. With myDocument.DocumentPreferences .PageHeight = "11i" .PageWidth = "8.5i" .FacingPages = True .PageOrientation = idPageOrientation.idPortrait End With Rem Set the documents ruler origin to page origin. This is very important Rem --if you dont do this, getting objects to the correct position on the Rem page is much more difficult. myDocument.ViewPreferences.RulerOrigin = idRulerOrigin.idPageOrigin With myDocument.MasterSpreads.Item(1) Rem Set up the left page (verso). With .Pages.Item(1) With .MarginPreferences .ColumnCount = 3 .ColumnGutter = "1p" .Bottom = "6p" Rem "left" means inside "right" means outside. .Left = "6p" .Right = "4p" .Top = "4p" End With Rem Add a simple footer with a section number and page number. With .TextFrames.Add .GeometricBounds = Array("61p", "4p", "62p", "45p") .InsertionPoints.Item(1).Contents = idSpecialCharacters.idSectionMarker .InsertionPoints.Item(1).Contents = idSpecialCharacters.idEmSpace .InsertionPoints.Item(1).Contents = idSpecialCharacters.idAutoPageNumber .Paragraphs.Item(1).Justification = idJustification.idLeftAlign End With End With Rem Set up the right page (recto). With .Pages.Item(2) With .MarginPreferences .ColumnCount = 3 .ColumnGutter = "1p" .Bottom = "6p" Rem "left" means inside "right" means outside. .Left = "6p" .Right = "4p" .Top = "4p" End With Rem Add a simple footer with a section number and page number. With .TextFrames.Add .GeometricBounds = Array("61p", "6p", "62p", "47p") .InsertionPoints.Item(1).Contents = idSpecialCharacters.idAutoPageNumber .InsertionPoints.Item(1).Contents = idSpecialCharacters.idEmSpace .InsertionPoints.Item(1).Contents = idSpecialCharacters.idSectionMarker .Paragraphs.Item(1).Justification = idJustification.idRightAlign End With End With End With
To apply a master spread to a document page, use the AppliedMaster property of the document page:
Rem ApplyMaster.vbs Rem An InDesign CS2 VBScript Rem Applies a master spread to a page. Set myInDesign = CreateObject("InDesign.Application.CS2") Rem Assumes that the active document has a master page named "B-Master" Rem and at least two pages. myInDesign.ActiveDocument.Pages.Item(2).AppliedMaster = myInDesign.ActiveDocument.MasterSpreads. Item("B-Master")
157
Use the same property to apply a master spread to a master spread page:
Rem ApplyMasterToMaster.vbs Rem An InDesign CS2 VBScript Rem Applies a master page to a master page. Rem Assumes that the default master spread name is "A-Master". Set myInDesign = CreateObject("InDesign.Application.CS2") Set myDocument = myInDesign.Documents.Add Rem Create a new master spread. Set myBMaster = myDocument.MasterSpreads.Add myBMaster.NamePrefix = "B" myBMaster.BaseName = "Master" Rem Apply master spread "A" to the first page of the new master spread. myInDesign.ActiveDocument.MasterSpreads.Item("B-Master").Pages.Item(1).AppliedMaster = myInDesign. ActiveDocument.MasterSpreads.Item("A-Master")
158
.FirstLineIndent = "14pt" .GradientFillAngle .GradientFillLength .GridAlignFirstLineOnly = False .HorizontalScale = 100 .HyphenateAfterFirst = 3 .HyphenateBeforeLast = 4 .HyphenateCapitalizedWords = False .HyphenateLadderLimit = 1 .HyphenateWordsLongerThan = 5 .Hyphenation = True .HyphenationZone = "3p" .HyphenWeight = 9 .Justification = idJustification.idLeftAlign .KeepAllLinesTogether = False .KeepLinesTogether = True .KeepFirstLines = 2 .KeepLastLines = 2 .KeepWithNext = 0 .KerningMethod = "Optical" .Leading = 14 .LeftIndent = 0 .Ligatures = True .MaximumGlyphScaling = 100 .MaximumLetterSpacing = 0 .MaximumWordSpacing = 160 .MinimumGlyphScaling = 100 .MinimumLetterSpacing = 0 .MinimumWordSpacing = 80 .NoBreak = False .OTFContextualAlternate = True .OTFDiscretionaryLigature = True .OTFFigureStyle = idOTFFigureStyle.idProportionalOldstyle .OTFFraction = True .OTFHistorical = True .OTFOrdinal = False .OTFSlashedZero = True .OTFSwash = False .OTFTitling = False .OverprintFill = False .OverprintStroke = False .PointSize = 11 .Position = idPosition.idNormal .RightIndent = 0 .RuleAbove = False Rem If RuleAbove is false, attempting to set some of the Rem rule above properties will generate an error. Though Rem weve set RuleAbove to false, weve included the properties Rem to provide a more complete example. If .RuleAbove = True Then .RuleAboveColor = myInDesign.Colors.Item("Black") .RuleAboveGapColor = myInDesign.Swatches.Item("None") .RuleAboveGapOverprint = False .RuleAboveGapTint = 100 .RuleAboveLeftIndent = 0 .RuleAboveLineWeight = 0.25 .RuleAboveOffset = 14 .RuleAboveOverprint = False .RuleAboveRightIndent = 0 .RuleAboveTint = 100 .RuleAboveType = myInDesign.StrokeStyles.Item("Solid") .RuleAboveWidth = idRuleWidth.idColumnWidth End If .RuleBelow = False Rem If RuleBelow is false, attempting to set some of the Rem rule below properties will generate an error. Though Rem weve set RuleBelow to false, weve included the properties Rem to provide a more complete example.
159
If .RuleBelow = True Then .RuleBelowColor = myInDesign.Colors.Item("Black") .RuleBelowGapColor = myInDesign.Swatches.Item("None") .RuleBelowGapOverPrint = False .RuleBelowGapTint = 100 .RuleBelowLeftIndent = 0 .RuleBelowLineWeight = 0.25 .RuleBelowOffset = 0 .RuleBelowOverPrint = False .RuleBelowRightIndent = 0 .RuleBelowTint = 100 .RuleBelowType = myInDesign.StrokeStyles.Item("Solid") .RuleBelowWidth = idRuleWidth.idColumnWidth End If .SingleWordJustification = idSingleWordJustification.idLeftAlign .Skew = 0 .SpaceAfter = 0 .SpaceBefore = 0 .StartParagraph = idStartParagraph.idAnywhere .StrikeThru = False Rem If StrikeThru is false, attempting to set some of the Rem strikethrough properties will generate an error. Though Rem weve set StrikeThru to false, weve included the properties Rem to provide a more complete example. If .StrikeThru = True Then .StrikeThroughColor = myInDesign.Colors.Item("Black") .StrikeThroughGapColor = myInDesign.Swatches.Item("None") .StrikeThroughGapOverprint = False .StrikeThroughGapTint = 100 .StrikeThroughOffset = 3 .StrikeThroughOverprint = False .StrikeThroughTint = 100 .StrikeThroughType = myInDesign.StrokeStyles.Item("Solid") .StrikeThroughWeight = 0.25 End If .StrokeColor = myInDesign.Swatches.Item("None") .StrokeTint = 100 .StrokeWeight = 0 .Tracking = 0 .Underline = False Rem If Underline is false, attempting to set some of the Rem underline properties will generate an error. Though Rem weve set Underline to false, weve included the properties Rem to provide a more complete example. If .Underline = True Then .UnderlineColor = myInDesign.Colors.Item("Black") .UnderlineGapColor = myInDesign.Swatches.Item("None") .UnderlineGapOverprint = False .UnderlineGapTint = 100 .UnderlineOffset = 3 .UnderlineOverprint = False .UnderlineTint = 100 .UnderlineType = myInDesign.StrokeStyles.Item("Solid") .UnderlineWeight = 0.25 End If .VerticalScale = 100 End With
to:
with myInDesign.ActiveDocument.TextDefaults
160
161
Rem Creates a document template, including master pages, layers, Rem a color, paragraph and character styles, guides, and XMP information. Set myInDesign = CreateObject("InDesign.Application.CS2") Rem Set the application measurement unit defaults to points. myInDesign.ViewPreferences.HorizontalMeasurementUnits = idMeasurementUnits.idPoints myInDesign.ViewPreferences.VerticalMeasurementUnits = idMeasurementUnits.idPoints Rem Set the application default margin preferences. With myInDesign.MarginPreferences Rem Save the current application default margin preferences. myY1 = .Top myX1 = .Left myY2 = .Bottom myX2 = .Right Rem Set the application default margin preferences. Rem Document baseline grid will be based on 14 points, and Rem all margins are set in increments of 14 points. .Top = 14 * 4 .Left = 14 * 4 .Bottom = 74 .Right = 14 * 5 End With Rem Make a new document. Set myDocument = myInDesign.Documents.Add myDocument.DocumentPreferences.PageWidth = "7i" myDocument.DocumentPreferences.PageHeight = "9i" myDocument.DocumentPreferences.PageOrientation = idPageOrientation.idPortrait Rem At this point, we can reset the application default margins Rem to their original state. With myInDesign.MarginPreferences .Top = myY1 .Left = myX1 .Bottom = myY2 .Right = myX2 End With Rem Set up the bleed and slug areas. With myDocument.DocumentPreferences Rem Bleed .DocumentBleedBottomOffset = "3p" .DocumentBleedTopOffset = "3p" .DocumentBleedInsideOrLeftOffset = "3p" .DocumentBleedOutsideOrRightOffset = "3p" Rem Slug .SlugBottomOffset = "18p" .SlugTopOffset = "3p" .SlugInsideOrLeftOffset = "3p" .SlugRightOrOutsideOffset = "3p" End With Rem Create a color. Err.Clear On Error Resume Next Rem If the color does not already exist, InDesign will generate an error. Set myColor = myDocument.Colors.Item("PageNumberRed") If Err.Number <> 0 Then Set myColor = myDocument.Colors.Add myColor.Name = "PageNumberRed" myColor.colorModel = idColorModel.idProcess myColor.ColorValue = Array(20, 100, 80, 10) Err.Clear End If Rem restore normal error handling On Error GoTo 0 Rem Next, set up some default styles. Rem Create up a character style for the page numbers. Err.Clear On Error Resume Next Rem If the character style does not already exist, InDesign will generate an error. Set myCharacterStyle = myDocument.CharacterStyles.Item("page_number") If Err.Number <> 0 Then
162
Set myCharacterStyle = myDocument.CharacterStyles.Add myCharacterStyle.Name = "page_number" Err.Clear End If Rem restore normal error handling On Error GoTo 0 myDocument.CharacterStyles.Item("page_number").FillColor = myDocument.Colors.Item("PageNumberRed") Rem Create up a pair of paragraph styles for the page footer text. Rem These styles have only basic formatting. Err.Clear On Error Resume Next Rem If the paragraph style does not already exist, InDesign will generate an error. Set myParagraphStyle = myDocument.ParagraphStyles.Item("footer_left") If Err.Number <> 0 Then Set myParagraphStyle = myDocument.ParagraphStyles.Add myParagraphStyle.Name = "footer_left" myParagraphStyle.PointSize = 11 myParagraphStyle.Leading = 14 Err.Clear End If Rem restore normal error handling On Error GoTo 0 Err.Clear On Error Resume Next Rem If the paragraph style does not already exist, InDesign will generate an error. Set myParagraphStyle = myDocument.ParagraphStyles.Item("footer_right") If Err.Number <> 0 Then Set myParagraphStyle = myDocument.ParagraphStyles.Add myParagraphStyle.Name = "footer_right" myParagraphStyle.BasedOn = myDocument.ParagraphStyles.Item("footer_left") myParagraphStyle.Justification = idJustification.idRightAlign myParagraphStyle.PointSize = 11 myParagraphStyle.Leading = 14 Err.Clear End If Rem restore normal error handling On Error GoTo 0 Rem Create a layer for guides. Err.Clear On Error Resume Next Set myLayer = myDocument.Layers.Item("GuideLayer") If Err.Number <> 0 Then Set myLayer = myDocument.Layers.Add myLayer.Name = "GuideLayer" Err.Clear End If Rem restore normal error handling On Error GoTo 0 Rem Create a layer for the footer items. Err.Clear On Error Resume Next Set myLayer = myDocument.Layers.Item("Footer") If Err.Number <> 0 Then Set myLayer = myDocument.Layers.Add myLayer.Name = "Footer" Err.Clear End If Rem restore normal error handling On Error GoTo 0 Rem Create a layer for the slug items. Err.Clear On Error Resume Next Set myLayer = myDocument.Layers.Item("Slug") If Err.Number <> 0 Then Set myLayer = myDocument.Layers.Add myLayer.Name = "Slug" Err.Clear End If
163
Rem restore normal error handling On Error GoTo 0 Rem Create a layer for the body text. Err.Clear On Error Resume Next Set myLayer = myDocument.Layers.Item("BodyText") If Err.Number <> 0 Then Set myLayer = myDocument.Layers.Add myLayer.Name = "BodyText" Err.Clear End If Rem restore normal error handling On Error GoTo 0 With myDocument.ViewPreferences .RulerOrigin = idRulerOrigin.idPageOrigin .HorizontalMeasurementUnits = idMeasurementUnits.idPoints .VerticalMeasurementUnits = idMeasurementUnits.idPoints End With Rem Document baseline grid and document grid With myDocument.GridPreferences .BaselineStart = 56 .BaselineDivision = 14 .BaselineGridShown = False .HorizontalGridlineDivision = 14 .HorizontalGridSubdivision = 5 .VerticalGridlineDivision = 14 .VerticalGridSubdivision = 5 .DocumentGridShown = False End With Rem Document XMP information. With myDocument.MetadataPreferences .Author = "Olav Martin Kvern" .CopyrightInfoURL = "http:rem www.adobe.com" .CopyrightNotice = "This document is not copyrighted." .CopyrightStatus = idCopyrightStatus.idNo .Description = "Example 7 x 9 book layout" .DocumentTitle = "Example" .JobName = "7 x 9 book layout template" .Keywords = Array("7 x 9", "book", "template") .CreateContainerItem "http://ns.adobe.com/xap/1.0/", "email" .SetProperty "http://ns.adobe.com/xap/1.0/", "email/*[1]", "okvern@adobe.com" End With Rem Set up the master spread. With myDocument.MasterSpreads.Item(1) With .Pages.Item(1) Rem Left and right are reversed for left-hand pages (becoming "inside" and "outside"-Rem this is also true in the InDesign user interface). myTopMargin = .MarginPreferences.Top myBottomMargin = myDocument.DocumentPreferences.PageHeight - .MarginPreferences.Bottom myRightMargin = myDocument.DocumentPreferences.PageWidth - .MarginPreferences.Left myLeftMargin = .MarginPreferences.Right With .Guides.Add .ItemLayer = myDocument.Layers.Item("GuideLayer") .Orientation = idHorizontalOrVertical.idVertical .Location = myLeftMargin End With With .Guides.Add .ItemLayer = myDocument.Layers.Item("GuideLayer") .Orientation = idHorizontalOrVertical.idVertical .Location = myRightMargin End With With .Guides.Add .ItemLayer = myDocument.Layers.Item("GuideLayer") .Orientation = idHorizontalOrVertical.idHorizontal .Location = myTopMargin .FitToPage = False End With With .Guides.Add
164
.ItemLayer = myDocument.Layers.Item("GuideLayer") .Orientation = idHorizontalOrVertical.idHorizontal .Location = myBottomMargin .FitToPage = False End With With .Guides.Add .ItemLayer = myDocument.Layers.Item("GuideLayer") .Orientation = idHorizontalOrVertical.idHorizontal .Location = myBottomMargin + 14 .FitToPage = False End With With .Guides.Add .ItemLayer = myDocument.Layers.Item("GuideLayer") .Orientation = idHorizontalOrVertical.idHorizontal .Location = myBottomMargin + 28 .FitToPage = False End With Set myLeftFooter = .TextFrames.Add myLeftFooter.ItemLayer = myDocument.Layers.Item("Footer") myLeftFooter.GeometricBounds = Array(myBottomMargin + 14, .MarginPreferences.Right, myBottomMargin + 28, myRightMargin) myLeftFooter.ParentStory.InsertionPoints.Item(1).Contents = idSpecialCharacters. idSectionMarker myLeftFooter.ParentStory.InsertionPoints.Item(1).Contents = idSpecialCharacters.idEmSpace myLeftFooter.ParentStory.InsertionPoints.Item(1).Contents = idSpecialCharacters. idAutoPageNumber myLeftFooter.ParentStory.Characters.Item(1).AppliedCharacterStyle = myDocument. CharacterStyles.Item("page_number") myLeftFooter.ParentStory.Paragraphs.Item(1).ApplyStyle myDocument.ParagraphStyles. Item("footer_left"), False Rem Slug information. myDate = Date With myDocument.MetadataPreferences myString = "Author:" & vbTab & .Author & vbTab & "Description:" & vbTab & .Description & vbCrLf & _ "Creation Date:" & vbTab & myDate & vbTab & "Email Contact" & vbTab & .GetProperty("http://ns.adobe.com/xap/1.0/", "email/*[1]") End With Set myLeftSlug = .TextFrames.Add myLeftSlug.ItemLayer = myDocument.Layers.Item("Slug") myLeftSlug.GeometricBounds = Array(myDocument.DocumentPreferences.PageHeight + 36, .MarginPreferences.Right, myDocument.DocumentPreferences.PageHeight + 144, myRightMargin) myLeftSlug.Contents = myString myLeftSlug.ParentStory.Texts.Item(1).ConvertToTable Rem Body text master text frame. Set myLeftFrame = .TextFrames.Add myLeftFrame.ItemLayer = myDocument.Layers.Item("BodyText") myLeftFrame.GeometricBounds = Array(.MarginPreferences.Top, .MarginPreferences.Right, myBottomMargin, myRightMargin) End With With .Pages.Item(2) myTopMargin = .MarginPreferences.Top myBottomMargin = myDocument.DocumentPreferences.PageHeight - .MarginPreferences.Bottom myRightMargin = myDocument.DocumentPreferences.PageWidth - .MarginPreferences.Right myLeftMargin = .MarginPreferences.Left With .Guides.Add .ItemLayer = myDocument.Layers.Item("GuideLayer") .Orientation = idHorizontalOrVertical.idVertical .Location = myLeftMargin End With With .Guides.Add .ItemLayer = myDocument.Layers.Item("GuideLayer") .Orientation = idHorizontalOrVertical.idVertical .Location = myRightMargin End With Set myRightFooter = .TextFrames.Add myRightFooter.ItemLayer = myDocument.Layers.Item("Footer") myRightFooter.GeometricBounds = Array(myBottomMargin + 14, .MarginPreferences.Left,
165
myBottomMargin + 28, myRightMargin) myRightFooter.ParentStory.InsertionPoints.Item(1).Contents = idSpecialCharacters. idAutoPageNumber myRightFooter.ParentStory.InsertionPoints.Item(1).Contents = idSpecialCharacters.idEmSpace myRightFooter.ParentStory.InsertionPoints.Item(1).Contents = idSpecialCharacters. idSectionMarker myRightFooter.ParentStory.Characters.Item(-1).AppliedCharacterStyle = myDocument. CharacterStyles.Item("page_number") myRightFooter.ParentStory.Paragraphs.Item(1).ApplyStyle myDocument.ParagraphStyles. Item("footer_right"), False Rem Slug information. Set myRightSlug = .TextFrames.Add myRightSlug.ItemLayer = myDocument.Layers.Item("Slug") myRightSlug.GeometricBounds = Array(myDocument.DocumentPreferences.PageHeight + 36, myLeftMargin, myDocument.DocumentPreferences.PageHeight + 144, myRightMargin) myRightSlug.Contents = myString myRightSlug.ParentStory.Texts.Item(1).ConvertToTable Rem Body text master text frame. Set myRightFrame = .TextFrames.Add myRightFrame.ItemLayer = myDocument.Layers.Item("BodyText") myRightFrame.GeometricBounds = Array(.MarginPreferences.Top, .MarginPreferences.Left, myBottomMargin, myRightMargin) myRightFrame.PreviousTextFrame = myLeftFrame End With End With Rem Add section marker text--this text will appear in the footer. myDocument.Sections.Item(1).Marker = "Section 1" Rem When you link the master page text frames, one of the frames Rem sometimes becomes selected. Deselect it. myInDesign.Select idNothingEnum.idNothing
Printing a document
The following script prints the active document using the current print preferences:
Rem PrintDocument.vbs Rem An InDesign CS2 VBScript Rem Prints the active document. Set myInDesign = CreateObject("InDesign.Application.CS2") Rem The PrintOut method has two optional parameters: Rem PrintDialog--if true, display the Print dialog box Rem Using--the printer preset to use. The following line Rem prints the document using the default settings and Rem without displaying the Print dialog box. myInDesign.ActiveDocument.PrintOut False
166
myTextFrame.Contents = idSpecialCharacters.idAutoPageNumber myTextFrame.Paragraphs.Item(1).Justification = idJustification.idCenterAlign myTextFrame.Paragraphs.Item(1).PointSize = 72 myTextFrame.TextFramePreferences.VerticalJustification = idVerticalJustification.idCenterAlign Set myTextFrame = myMasterSpread.Pages.Item(2).TextFrames.Add myTextFrame.GeometricBounds = Array(0, 0, myPageHeight, myPageWidth) myTextFrame.Contents = idSpecialCharacters.idAutoPageNumber myTextFrame.Paragraphs.Item(1).Justification = idJustification.idCenterAlign myTextFrame.Paragraphs.Item(1).PointSize = 72 myTextFrame.TextFramePreferences.VerticalJustification = idVerticalJustification.idCenterAlign For myCounter = 1 To myDocument.Pages.Count myDocument.Pages.Item(myCounter).AppliedMaster = myDocument.MasterSpreads.Item("A-Master") Next Rem End of example document setup. Rem The page range can be either idPageRange.idAllPages or a page range string. Rem A page number entered in the page range must correspond to a page Rem name in the document (i.e., not the page index). If the page name is Rem not found, InDesign will display an error message. myInDesign.ActiveDocument.PrintPreferences.PageRange = "1-3, 6, 9" myInDesign.ActiveDocument.PrintOut False
167
Rem -------------------------------------------------------------------------------.PaperSize = idPaperSizes.idCustom Rem Page width and height are ignored if paperSize is not PaperSizes.custom. Rem .PaperHeight = 1200 Rem .PaperWidth = 1200 .PrintPageOrientation = idPrintPageOrientation.idPortrait .PagePosition = idPagePositions.idCentered .PaperGap = 0 .PaperOffset = 0 .PaperTransverse = False .ScaleHeight = 100 .ScaleWidth = 100 .ScaleMode = idScaleModes.idScaleWidthHeight .ScaleProportional = True Rem If trapping is set to either idTrapping.idApplicationBuiltIn or idTrapping.idAdobeInRIP, Rem then setting the following properties will produce an error. If (.ColorOutput = idColorOutputModes.idInRIPSeparations) Or _ (.ColorOutput = idColorOutputModes.idSeparations) Then If .Trapping = idTrapping.idOff Then .TextAsBlack = False .Thumbnails = False Rem The following properties is not needed because thumbnails is set to false. Rem thumbnailsPerPage = 4 .Tile = False Rem The following properties are not needed because tile is set to false. Rem .TilingOverlap = 12 Rem .TilingType = TilingTypes.auto End If End If Rem -------------------------------------------------------------------------------Rem Properties corresponding to the controls in the Marks and Bleed panel of the Print dialog. Rem -------------------------------------------------------------------------------Rem Set the following property to true to print all printers marks. Rem allPrinterMarks = true .UseDocumentBleedToPrint = False Rem If useDocumentBleedToPrint = false then setting any of the bleed properties Rem will result in an error. Rem Get the bleed amounts from the documents bleed and add a bit. .BleedBottom = myInDesign.ActiveDocument.DocumentPreferences.DocumentBleedBottomOffset + 3 .BleedTop = myInDesign.ActiveDocument.DocumentPreferences.DocumentBleedTopOffset + 3 .BleedInside = myInDesign.ActiveDocument.DocumentPreferences.DocumentBleedInsideOrLeftOffset + 3 .BleedOutside = myInDesign.ActiveDocument.DocumentPreferences.DocumentBleedOutsideOrRightOffset + 3 Rem If any bleed area is greater than zero, then print the bleed marks. If ((.BleedBottom = 0) And (.BleedTop = 0) And (.BleedInside = 0) And (.BleedOutside = 0)) Then .BleedMarks = True Else .BleedMarks = False End If .ColorBars = True .CropMarks = True .IncludeSlugToPrint = False .MarkLineWeight = idMarkLineWeight.idP125pt .MarkOffset = 6 Rem .MarkType = MarkTypes.default .PageInformationMarks = True .RegistrationMarks = True Rem -------------------------------------------------------------------------------Rem Properties corresponding to the controls in the Output panel of the Print dialog box. Rem -------------------------------------------------------------------------------.Negative = True .ColorOutput = idColorOutputModes.idSeparations Rem Note the lowercase "i" in "Builtin" .Trapping = idTrapping.idApplicationBuiltin .Screening = "175 lpi/2400 dpi" .Flip = idFlip.idNone Rem The following options are only applicable if trapping is set to
168
Rem idTrapping.idAdobeInRIP. If .Trapping = idTrapping.idAdobeInRIP Then .PrintBlack = True .PrintCyan = True .PrintMagenta = True .PrintYellow = True End If Rem Only change the ink angle and frequency when you want to override the Rem screening set by the screening specified by the screening property. Rem .BlackAngle = 45 Rem .BlackFrequency = 175 Rem .CyanAngle = 15 Rem .CyanFrequency = 175 Rem .MagentaAngle = 75 Rem .MagentaFreqency = 175 Rem .YellowAngle = 0 Rem .YellowFrequency = 175 Rem The following properties are not needed (because colorOutput is set to separations). Rem .CompositeAngle = 45 Rem .CompositeFrequency = 175 Rem .SimulateOverprint = false Rem -------------------------------------------------------------------------------Rem Properties corresponding to the controls in the Graphics panel of the Print dialog. Rem -------------------------------------------------------------------------------.SendImageData = idImageDataTypes.idAllImageData .FontDownloading = idFontDownloading.idComplete Err.Clear On Error Resume Next .DownloadPPDFonts = True .DataFormat = idDataFormat.idBinary .PostScriptLevel = idPostScriptLevels.idLevel3 If Err.Number <> 0 Then Err.Clear End If On Error GoTo 0 Rem -------------------------------------------------------------------------------Rem Properties corresponding to the controls in the Color Management panel of the Print dialog. Rem -------------------------------------------------------------------------------Rem If the UseColorManagement property of myInDesign.ColorSettings is false, Rem attempting to set the following properties will return an error. Err.Clear On Error Resume Next .SourceSpace = SourceSpaces.useDocument .Intent = RenderingIntent.useColorSettings .CRD = ColorRenderingDictionary.useDocument .Profile = Profile.postscriptCMS If Err.Number <> 0 Then Err.Clear End If On Error GoTo 0 Rem -------------------------------------------------------------------------------Rem Properties corresponding to the controls in the Advanced panel of the Print dialog. Rem -------------------------------------------------------------------------------.OPIImageReplacement = False .OmitBitmaps = False .OmitEPS = False .OmitPDF = False Rem The following line assumes that you have a flattener preset named "high quality flattener". Err.Clear On Error Resume Next .FlattenerPresetName = "high quality flattener" If Err.Number <> 0 Then Err.Clear End If On Error GoTo 0 .IgnoreSpreadOverrides = False End With
169
170
myPreset.CropMarks = .CropMarks myPreset.IncludeSlugToPrint = .IncludeSlugToPrint myPreset.MarkLineWeight = .MarkLineWeight myPreset.MarkOffset = .MarkOffset myPreset.MarkType = .MarkType myPreset.PageInformationMarks = .PageInformationMarks myPreset.RegistrationMarks = .RegistrationMarks myPreset.Negative = .Negative myPreset.Trapping = .Trapping myPreset.Screening = .Screening myPreset.Flip = .Flip myPreset.PrintBlack = .PrintBlack myPreset.PrintCyan = .PrintCyan myPreset.PrintMagenta = .PrintMagenta myPreset.PrintYellow = .PrintYellow myPreset.BlackAngle = .BlackAngle myPreset.BlackFrequency = .BlackFrequency myPreset.CyanAngle = .CyanAngle myPreset.CyanFrequency = .CyanFrequency myPreset.MagentaAngle = .MagentaAngle myPreset.magentaFreqency = .magentaFreqency myPreset.YellowAngle = .YellowAngle myPreset.YellowFrequency = .YellowFrequency myPreset.CompositeAngle = .CompositeAngle myPreset.CompositeFrequency = .CompositeFrequency myPreset.SimulateOverprint = .SimulateOverprint myPreset.SendImageData = .SendImageData myPreset.FontDownloading = .FontDownloading myPreset.DownloadPPDFonts = .DownloadPPDFonts myPreset.DataFormat = .DataFormat myPreset.PostScriptLevel = .PostScriptLevel myPreset.SourceSpace = .SourceSpace myPreset.Intent = .Intent myPreset.CRD = .CRD myPreset.Profile = .Profile myPreset.OPIImageReplacement = .OPIImageReplacement myPreset.OmitBitmaps = .OmitBitmaps myPreset.OmitEPS = .OmitEPS myPreset.OmitPDF = .OmitPDF myPreset.FlattenerPresetName = .FlattenerPresetName myPreset.IgnoreSpreadOverrides = .IgnoreSpreadOverrides MsgBox "Done!" If Err.Number <> 0 Then Err.Clear End If On Error GoTo 0 End With
171
Rem ShowingOptions: boolean (setting this option to true displays the PDF Export dialog box) Rem Using: PDF export preset (or a string that is the name of a PDF export preset) Rem The default PDF export preset names are surrounded by squar breackets (e.g., "[Screen]"). myInDesign.ActiveDocument.Export idExportFormat.idPDFType, "c:\myTestDocument.pdf", False, myInDesign.PDFExportPresets.Item("[Press]")
172
.BleedMarks = False End If .ColorBars = True Rem ColorTileSize and GrayTileSize are only used when Rem the export format is set to JPEG2000. Rem .ColorTileSize = 256 Rem .GrayTileSize = 256 .CropMarks = True .OmitBitmaps = False .OmitEPS = False .OmitPDF = False .PageInformationMarks = True .PageMarksOffset = 12 .PDFColorSpace = idPDFColorSpace.idUnchangedColorSpace .PDFMarkType = idMarkTypes.idDefault .PrinterMarkWeight = idPDFMarkWeight.idP125pt .RegistrationMarks = True On Error Resume Next .SimulateOverprint = False On Error GoTo 0 .UseDocumentBleedWithPDF = True Rem Set viewPDF to true to open the PDF in Acrobat or Adobe Reader. .ViewPDF = False End With Rem Now export the document. Youll have to fill in your own file path. myInDesign.ActiveDocument.Export idExportFormat.idPDFType, "c:\myTestDocument.pdf", False
173
End If Function myExportPages(myInDesign, myDocument, myFolderName) myDocumentName = myDocument.Name Set myDialog = myInDesign.Dialogs.Add With myDialog .Name = "ExportPages" With .DialogColumns.Add With .DialogRows.Add With .StaticTexts.Add .StaticLabel = "Base Name:" End With Set myBaseNameField = .TextEditboxes.Add myBaseNameField.EditContents = myDocumentName myBaseNameField.MinWidth = 160 End With End With End With myResult = myDialog.Show If myResult = True Then myBaseName = myBaseNameField.EditContents Rem Remove the dialog box from memory. myDialog.Destroy For myCounter = 1 To myDocument.Pages.Count myPageName = myDocument.Pages.Item(myCounter).Name myInDesign.PDFExportPreferences.PageRange = myPageName Rem Generate a file path from the folder name, the base document name, Rem and the page name. Rem Replace the colons in the page name (e.g., "Sec1:1") wtih underscores. myPageName = Replace(myPageName, ":", "_") myFilePath = myFolderName & "\" & myBaseName & "_" & myPageName & ".pdf" myDocument.Export idExportFormat.idPDFType, myFilePath, False Next Else myDialog.Destroy End If End Function
174
Rem An InDesign CS2 VBScript. Rem Exports a range of pages as EPS files. Set myInDesign = CreateObject("InDesign.Application.CS2") Rem Enter the name of the page you want to export in the following line. Rem Note that the page name is not necessarily the index of the page in the Rem document (e.g., the first page of a document whose page numbering starts Rem with page 21 will be "21", not 1). myInDesign.EPSExportPreferences.PageRange = "1-3, 6, 9" Rem Fill in your own file path. myFile = "c:\myTestFile.eps" myInDesign.ActiveDocument.Export idExportFormat.idEPSType, myFile, False
175
176