If this guide is distributed with software that includes an end user agreement, this guide, as well as the software
described in it, is furnished under license and may be used or copied only in accordance with the terms of such license.
Except as permitted by any such license, no part of this guide may be reproduced, stored in a retrieval system, or
transmitted, in any form or by any means, electronic, mechanical, recording, or otherwise, without the prior written
permission of Adobe Systems Incorporated. Please note that the content in this guide is protected under copyright law
even if it is not distributed with software that includes an end user license agreement.
The content of this guide is furnished for informational use only, is subject to change without notice, and should not be
construed as a commitment by Adobe Systems Incorporated. Adobe Systems Incorporated assumes no responsibility or
liability for any errors or inaccuracies that may appear in the informational content contained in this guide.
Please remember that existing artwork or images that you may want to include in your project may be protected under
copyright law. The unauthorized incorporation of such material into your new work could be a violation of the rights of
the copyright owner. Please be sure to obtain any permission required from the copyright owner.
Any references to company names in sample templates are for demonstration purposes only and are not intended to
refer to any actual organization.
Adobe, the Adobe logo, Creative Suite, and InDesign are either registered trademarks or trademarks of Adobe Systems
Incorporated in the United States and/or other countries. Microsoft and Windows are either registered trademarks or
trademarks of Microsoft Corporation in the United States and/or other countries. Mac OS is a trademark of Apple
Computer, Incorporated, registered in the United States and other countries. All other trademarks are the property of
their respective owners.
Adobe Systems Incorporated, 345 Park Avenue, San Jose, California 95110, USA. Notice to U.S. Government End Users.
The Software and Documentation are “Commercial Items,” as that term is defined at 48 C.F.R. §2.101, consisting of
“Commercial Computer Software” and “Commercial Computer Software Documentation,” as such terms are used in 48
C.F.R. §12.212 or 48 C.F.R. §227.7202, as applicable. Consistent with 48 C.F.R. §12.212 or 48 C.F.R. §§227.7202-1 through
227.7202-4, as applicable, the Commercial Computer Software and Commercial Computer Software Documentation are
being licensed to U.S. Government end users (a) only as Commercial Items and (b) with only those rights as are granted
to all other end users pursuant to the terms and conditions herein. Unpublished-rights reserved under the copyright
laws of the United States. Adobe Systems Incorporated, 345 Park Avenue, San Jose, CA 95110-2704, USA. For U.S.
Government End Users, Adobe agrees to comply with all applicable equal opportunity laws including, if appropriate, the
provisions of Executive Order 11246, as amended, Section 402 of the Vietnam Era Veterans Readjustment Assistance Act
of 1974 (38 USC 4212), and Section 503 of the Rehabilitation Act of 1973, as amended, and the regulations at 41 CFR
Parts 60-1 through 60-60, 60-250, and 60-741. The affirmative action clause and regulations contained in the preceding
sentence shall be incorporated by reference.
XWork with the Adobe® InDesign® scripting environment.
XUse advanced scripting features.
XPerform basic document tasks like setting up master spreads, printing, and exporting.
XWork with page items (rectangles, ellipses, graphic lines, polygons, text frames, and groups).
XWork with text and type in an InDesign document, including finding and changing text.
XCreate dialog boxes and other user-interface items.
XCustomize and add menus and create menu actions.
XRespond to user-interface events.
XWork with XML, from creating XML elements and importing XML to adding XML elements to a layout.
XApply XML rules, a new scripting feature that makes working with XML in InDesign faster and easier.
We assume that you have already read the Adobe InDesign CS5 Scripting Tutorial and know how to create,
install, and run scripts. If you need to know how to connect with your scripting environment or view the
InDesign scripting object model from your script editor, that information can be found in the Adobe InDesign CS5 Scripting Tutorial.
How to Use the Scripts in this Document
For the most part, the scripts shown in this document are not complete scripts. They are only fragments of
scripts, and are intended to show only the specific part of a script relevant to the point being discussed in
the text. You can copy the script lines shown in this document and paste them into your script editor, but
you should not expect them to run without further editing. Note, in addition, that scripts copied out of this
document may contain line breaks and other characters (due to the document layout) that will prevent
them from executing properly.
A zip archive of all of the scripts shown in this document is available at the InDesign scripting home page,
at: http://www.adobe.com/products/indesign/scripting/index.html
expanded the archive, move the folders corresponding to the scripting language(s) of your choice into the
Scripts Panel folder inside the Scripts folder in your InDesign folder. At that point, you can run the scripts
from the Scripts panel inside InDesign.
About the Structure of the Scripts
. After you have downloaded and
The script examples are all written using a common template that includes the functions “main,”
“mySetup,” “mySnippet,” and “myTeardown.” We did this to simplify automated testing and
publication—there is no reason for you to construct your scripts this way. Most of the time, the part of the
script you will be interested in will be inside the “mySnippet” function.
9
CHAPTER 1: IntroductionFor More Information 10
For More Information
For more information on InDesign scripting, you also can visit the InDesign Scripting User to User forum, at
http://www.adobeforums.com
newest scripts. The forum contains hundreds of sample scripts.
Other JavaScript development options
You can use the ExtendScript Toolkit to create JavaScript scripts explicitly for InDesign, or you can use the
Creative Suite Extension Builder (CS Extension Builder) to develop CS extensions in ActionScript. CS
extensions are Flash-based (SWF) and can potentially work in a variety of Creative Suite applications.
In CS5, the applications have an extensibility infrastructure that allows developers to extend the
capabilities of the applications; the infrastructure is based on Flash/Flex technology, and each CS5
extension is delivered as a compiled Flash (SWF) file. CS5 includes the Extension Manager to enable
installation of CS5 extensions.
An example of a CS5 extension that ships with the point products is Adobe Kuler. Kuler has a consistent
user interface across the different suite applications, but has different logic in each, adapted to the host
application.
. In the forum, scripters can ask questions, post answers, and share their
The user interface for an extension is written in ActionScript, using the Flex framework. A C5S extension is
typically accessed through its own menu item in the application’s Extensions menu. CS Extension Builder
allows you to design the user interface interactively using the Design view of FlashBuilder. It also allows
you to develop all of the application logic for your CS5 extension in ActionScript; you can develop and
debug your extension in the familiar FlashBuilder environment.
To develop your application logic, we recommend using the Creative Suite ActionScript Wrapper Library
CSAWLib), which exposes the scripting DOM of each host application as an ActionScript library. This is
(
tightly integrated with the CS Extension Builder environment, which includes wizards to help you build
your extension’s basic structure, and run and debug your code against suite applications such as Adobe
InDesign, Photoshop and Illustrator.
The methods, properties, and behavior of the scripting DOM is as described in the JavaScript Scripting Reference for the host application. For details of how to use CS Extension Builder and the wrapper libraries,
see the Creative Suite SDK documentation, which is accessible from within the Flash Builder or Eclipse
Help system when you have installed CS Extension Builder.
2
Scripting Features
This chapter covers scripting techniques related to InDesign’s scripting environment. Almost every other
object in the InDesign scripting model controls a feature that can change a document or the application
defaults. By contrast, the features in this chapter control how scripts operate.
This document discusses the following:
XThe scriptPreferences object and its properties.
XGetting a reference to the executing script.
XRunning scripts in prior versions of the scripting object model.
XUsing the doScript method to run scripts.
XWorking with script labels.
XRunning scripts at InDesign start-up.
XControlling the ExtendScript engine in which scripts execute.
We assume you already read Adobe InDesign CS5 Scripting Tutorial and know how to write, install, and run
InDesign scripts in the scripting language of your choice.
Script Preferences
The scriptPreferences object provides objects and properties related to the way InDesign runs scripts.
The following table provides more detail on each property of the scriptPreferences object:
PropertyDescription
enableRedraw
scriptsFolder
scriptsList
Turns screen redraw on or off while a script is running from the Scripts panel.
The path to the scripts folder.
A list of the available scripts. This property is an array of arrays, in the
following form:
[[fileName, filePath], ...]
Where fileName is the name of the script file and filePath is the full path to
the script. You can use this feature to check for the existence of a script in the
installed set of scripts.
11
CHAPTER 2: Scripting FeaturesGetting the Current Script 12
PropertyDescription
userInteractionLevel
This property controls the alerts and dialogs InDesign presents to the user.
When you set this property to
InDesign does not display any alerts or dialogs. Set it to
UserInteractionLevels.interactWithAlerts to enable alerts but
disable dialogs. Set it to
alerts and dialogs. The ability to turn off alert displays is very useful when
you are opening documents via script; often, InDesign displays an alert for
missing fonts or linked graphics files. To avoid this alert, set the
user-interaction level to
opening the document, then restore user interaction (set the property to
interactWithAll) before completing script execution.
version
The version of the scripting environment in use. For more information, see
“Script Versioning” on page 12
version of the application.
Getting the Current Script
You can get a reference to the current script using the activeScript property of the application object.
You can use this property to help you locate files and folders relative to the script, as shown in the
following example (from the ActiveScript tutorial script):
var myScript = app.activeScript;
alert("The current script is: " + myScript);
var myParentFolder = File(myScript).parent;
alert("The folder containing the active script is: " + myParentFolder);
UserInteractionLevels.neverInteract,
interactWithAll to restore the normal display of
UserInteractionLevels.neverInteract before
. Note this property is not the same as the
When you debug scripts using a script editor, the activeScript property returns an error. Only scripts run
from the Scripts palette appear in the
When you debug scripts from the ExtendScript Toolkit, using the
To avoid this error and create a way of debugging scripts that use the
following error handler (from the GetScriptPath tutorial script):
function myGetScriptPath() {
try{
return app.activeScript;
}
catch(myError){
return File(myError.fileName);
}
}
Script Versioning
InDesign CS5 can run scripts using earlier versions of the InDesign scripting object model. To run an older
script in a newer version of InDesign, you must consider the following:
XTargeting — Scripts must be targeted to the version of the application in which they are being run
(i.e., the current version). The mechanics of targeting are language specific.
activeScript property.
activeScript property returns an error.
activeScript property, use the
CHAPTER 2: Scripting FeaturesUsing the doScript Method 13
X
Compilation — This involves mapping the names in the script to the underlying script ids, which are
what the application understands. The mechanics of compilation are language specific.
XInterpretation — This involves matching the ids to the appropriate request handler within the
application. InDesign CS5 correctly interprets a script written for an earlier version of the scripting
object model. To do this, run the script from a folder in the Scripts panel folder named
Scripts (for InDesign CS3 scripts) or Version 2.0 Scripts (for InDesign CS2 scripts), or explicitly set
Version 5.0
the application's script preferences to the old object model within the script (as shown below). Put the
previous version scripts in the folder, and run them from the Scripts panel.
Targ et in g
Targeting for JavaScripts is implicit when the script is launched from the Scripts panel. If the script is
launched externally (from the ESTK), use the
//target CS5
#target "InDesign-6.0"
//target the latest version of InDesign
#target "InDesign"
target directive:
Compilation
JavaScripts are not pre-compiled. For compilation, the application uses the same version of the DOM that
is set for interpretation.
Interpretation
The InDesign application object contains a scriptPreferences object, which allows a script to get/set
the version of the scripting object model to use for interpreting scripts. The version defaults to the current
version of the application and persists.
The following examples show how to set the version to the CS3 (5.0) version of the scripting object model.
//Set to 5.0 scripting object model
app.scriptPreferences.version = 5.0;
Using the doScript Method
The doScript method gives a script a way to execute another script. The script can be a string of valid
scripting code or a file on disk. The script can be in the same scripting language as the current script or
another scripting language. The available languages vary by platform: on Mac OS
AppleScript or JavaScript; on Windows
The
doScript method has many possible uses:
XRunning a script in another language that provides a feature missing in your main scripting language.
For example, VBScript lacks the ability to display a file or folder browser, which JavaScript has.
AppleScript can be very slow to compute trigonometric functions (sine and cosine), but JavaScript
performs these calculations rapidly. JavaScript does not have a way to query Microsoft
contents of a specific spreadsheet cell, but both AppleScript and VBScript have this capability. In all
these examples, the
to overcome a limitation of the language used for the body of the script.
doScript method can execute a snippet of scripting code in another language,
®
, VBScript or JavaScript.
®
, you can run
®
Excel for the
CHAPTER 2: Scripting FeaturesUsing the doScript Method 14
X
Creating a script “on the fly.” Your script can create a script (as a string) during its execution, which it
can then execute using the
doScript method. This is a great way to create a custom dialog or panel
based on the contents of the selection or the attributes of objects the script creates.
XEmbedding scripts in objects. Scripts can use the doScript method to run scripts that were saved as
strings in the
label property of objects. Using this technique, an object can contain a script that
controls its layout properties or updates its content according to certain parameters. Scripts also can
be embedded in XML elements as an attribute of the element or as the contents of an element. See
“Running Scripts at Startup” on page 18
.
Sending parameters to doScript
To send a parameter to a script executed by doScript, use the following form (from the
DoScriptParameters tutorial script):
var myParameters = ["Hello from DoScript", "Your message here."];
var myJavaScript = "alert(\"First argument: \" + arguments[0] + \"\\rSecond argument:
\" + arguments[1]);";
app.doScript(myJavaScript, ScriptLanguage.javascript, myParameters);
if(File.fs == "Windows"){
var myAppleScript = "tell application \"Adobe InDesign CS5\\rdisplay
dialog(\"First argument\" & item 1 of arguments & return & \"Second argument: \"
& item 2 of arguments & return & end tell";
app.doScript(myAppleScript, ScriptLanguage.applescriptLanguage, myParameters);
}
Returning values from doScript
The following script fragment shows how to return a value from a script executed by doScript. This
example uses a JavaScript that is executed as a string, but the same method works for script files. This
example returns a single value, but you can return multiple values by returning an array (for the complete
script, refer to the DoScriptReturnValues script).
CHAPTER 2: Scripting FeaturesUsing the doScript Method 15
//To send parameters to a script run using app.doScript(), the doScript
//statement must not appear inside a function. If it does, the parameters
//will not be passed to the script.
var myDocument = app.documents.add();
var myPage = myDocument.pages.item(0);
var myTextFrame = myPage.textFrames.add();
myTextFrame.geometricBounds = ["72pt", "72pt", "288pt", "288pt"];
myTextFrame.contents = "Example text frame.";
var myDestinationPage = myDocument.pages.add(LocationOptions.after, myPage);
var myPageIndex = myDestinationPage.name;
var myID = myTextFrame.id;
var myJavaScript = "var myDestinationPage = arguments[1];\r" ;
myJavaScript += "myID = arguments[0];\r";
myJavaScript += "var myX = arguments[2];\r";
myJavaScript += "var myY = arguments[3]\r;"
myJavaScript += "var myPageItem =
app.documents.item(0).pages.item(0).pageItems.itemByID(myID);\r";
myJavaScript +=
"myPageItem.duplicate(app.documents.item(0).pages.item(myDestinationPage));\r"
//Create an array for the parameters we want to pass to the JavaScript.
var myArguments = [myID, myPageIndex, 0, 0];
var myDuplicate = app.doScript(myJavaScript, ScriptLanguage.javascript, myArguments);
//myDuplicate now contains a reference to the duplicated text frame.
//Change the text in the duplicated text frame.
myDuplicate.contents = "Duplicated text frame.";
Another way to get values from another script is to use the scriptArgs (short for “script arguments”)
object of the application. The following script fragment shows how to do this (for the complete script, see
DoScriptScriptArgs):
var nameA = "ScriptArgumentA";
var nameB = "ScriptArgumentB";
var nAc = nameA + ": ";
var nBc = nameB + ": ";
//Create a string to be run as a JavaScript.
var p1 = "app.scriptArgs.setValue(\"" + nameA + "\", ";
var p2 = "\"This is the first script argument value.\");\r";
var p3 = "app.scriptArgs.setValue(\"" + nameB + "\", ";
var p4 = "\"This is the second script argument value.\")";
var p5, p6; //Used later.
var myJavaScript = p1 + p2 + p3 + p4;
var myScriptArgumentA = app.scriptArgs.getValue(nameA);
var myScriptArgumentB = app.scriptArgs.getValue(nameB);
alert(nameA + ": " + myScriptArgumentA + "\r" + nameB + ": " + myScriptArgumentB);
if(File.fs == "Windows") {
//Create a string to be run as a VBScript.
p1 = "Set myInDesign = CreateObject(\"InDesign.Application.CS5\")\r";
p2 = "myInDesign.ScriptArgs.SetValue \"" + nameA + "\", ";
p3 = "\"This is the first script argument value.\"\r";
p4 = "myInDesign.ScriptArgs.SetValue \"" + nameB + "\", ";
p5 = "\"This is the second script argument value.\"";
var myVBScript = p1 + p2 + p3 + p4 + p5;
app.doScript(myVBScript, ScriptLanguage.visualBasic);
} else {
CHAPTER 2: Scripting FeaturesControlling Undo with doScript 16
//Create a string to be run as a AppleScript.
p1 = "tell application \"Adobe InDesign CS5\"\r";
p2 = "tell script args" +"\r";
p3 = "set value name\"" + nameA +"\" value ";
p4 = "\"This is the firest AppleScript script argument value.\"" +"\r";
p5 = "set value name\"" + nameB +"\" value ";
p6 = "\"This is the second AppleScript script argument value.\"" +"\r";
p7 = "end tell" + "\r"
p8 = "end tell" + "\r"
var myAppleScript = p1 + p2 + p3 + p4 + p5 + p6 + p7 + p8;
app.doScript(myAppleScript, ScriptLanguage.applescriptLanguage);
}
var myScriptArgumentA = app.scriptArgs.getValue(nameA);
var myScriptArgumentB = app.scriptArgs.getValue(nameB);
alert(nAc + myScriptArgumentA + nBc + myScriptArgumentB);
Controlling Undo with doScript
InDesign gives you the ability to undo almost every action, but this comes at a price: for almost every
action you make, InDesign writes to disk. For normal work you using the tools presented by the user
interface, this does not present any problem. For scripts, which can perform thousands of actions in the
time a human being can blink, the constant disk access can be a serious drag on performance.
doScript method offers a way around this performance bottleneck by providing two parameters that
The
control the way that scripts are executed relative to InDesign’s Undo behavior. These parameters are
shown in the following examples:
//Given a script "myJavaScript" and an array of parameters "myParameters"...
app.doScript(myJavaScript, ScriptLanguage.javascript, myParameters,
UndoModes.fastEntireScript, "Script Action");
//UndoModes can be:
//UndoModes.autoUnto: Add no events to the Undo queue.
//UndoModes.entireScript: Put a single event in the Undo queue.
//UndoModes.fastEntireScript: Put a single event in the Undo queue.
//UndoModes.scriptRequest: Undo each script action as a separate event.
//The last parameter is the text that appears in the Undo menu item.
Working with Script Labels
Many objects in InDesign scripting have a label property, including page items (rectangles, ovals, groups,
polygons, text frames, and graphic lines), table cells, documents, stories, and pages. This property can
store a very large amount of text.
The label of page items can be viewed, entered, or edited using the Script Label panel (choose Window >
Utilities > Script Label to display this panel), shown below. You also can add a label to an object using
scripting, and you can read the script label via scripting. For many objects, like stories, pages, and
paragraph styles, you cannot set or view the label using the Script Label panel.
CHAPTER 2: Scripting FeaturesWorking with Script Labels 17
The label property can contain any form of text data, such as tab- or comma-delimited text, HTML, or
XML. Because scripts also are text, they can be stored in the
label property.
Page items can be referred to by their
layers) can be referred to by their
label, just like named items (such as paragraph styles, colors, or
name. The following script fragment demonstrates this special case of the
label property (for the complete script, see ScriptLabel):
var myDocument = app.documents.add();
var myPage = myDocument.pages.item(0);
var myX1, myX2, myY1, myY2, myRectangle;
var myPageWidth = myDocument.documentPreferences.pageWidth;
var myPageHeight = myDocument.documentPreferences.pageHeight;
//<fragment>
//Create 10 random page items.
for(var i = 0; i < 10; i++)
{
}
alert("Found " + count + " page items with the label.");
//This function gets a random number in the range myStart to myEnd.
function myGetRandom(myStart, myEnd, myInteger)
{
var myRandom;
var myRange = myEnd - myStart;
if(myInteger == true)
{
In addition, all objects that support the label property also support custom labels. A script can set a
custom label using the
insertLabel method, and extract the custom label using the extractLabel
method, as shown in the following script fragment (from the CustomLabel tutorial script):
CHAPTER 2: Scripting FeaturesRunning Scripts at Startup 18
var myDocument = app.documents.add();
myDocument.viewPreferences.horizontalMeasurementUnits = MeasurementUnits.points;
myDocument.viewPreferences.verticalMeasurementUnits = MeasurementUnits.points;
var myPage = myDocument.pages.item(0);
var myRectangle = myPage.rectangles.add({geometricBounds:[72, 72, 144, 144]});
//Insert a custom label using insertLabel. The first parameter is the
//name of the label, the second is the text to add to the label.
myRectangle.insertLabel("CustomLabel", "This is some text stored in a custom label.");
//Extract the text from the label and display it in an alert.
var myString = myRectangle.extractLabel("CustomLabel");
alert("Custom label contained: " + myString);
Running Scripts at Startup
To run a script when InDesign starts, put the script in the Startup Scripts folder in the Scripts folder (for
more information, see “Installing Scripts” in Adobe InDesign CS5 Scripting Tutorial).
N
OTE: Scripts run in the session ExtendScript engine when InDesign starts can create objects and
functions that will be available to other scripts for the duration of the session. For more information, see
“Session and Main Script Execution” on page 18
.
Session and Main Script Execution
InDesign has two ways to run a JavaScript, session and main. These names correspond to the
ExtendScript “engine” used to run the script.
By default, when you run an InDesign JavaScript, the script is interpreted and executed by the “main”
ExtendScript engine, which is destroyed when the script completes execution. Script objects created by
the script do not persist.
Scripts run in the session engine can create objects that persist until you close InDesign. You can refer to
these objects from other scripts run in the
InDesign JavaScript, add the following line to the start of your script.
#targetengine "session"
You can create your own persistent ExtendScript interpretation and execution environment. To do this, use
#targetenging statement and provide your own ExtendScript engine name, as shown in the
the
following script fragment:
#targetengine "adobe"
session engine. To set the session engine as the target of an
3
Documents
The work you do in InDesign revolves around documents—creating them, saving them, printing or
exporting them, and populating them with page items, colors, styles, and text. Almost every
document-related task can be automated using InDesign scripting.
XApply different sizes to different pages (multiple pages sizes).
XPrint a document.
XExport a document as Adobe PDF.
XExport pages of a document as EPS.
We assume that you have already read Adobe InDesign CS5 Scripting Tutorial and know how to create,
install, and run a script.
19
CHAPTER 3: DocumentsBasic Document Operations 20
Basic Document Operations
Opening, closing, and saving documents are some of the most basic document tasks. This section shows
how to do them using scripting.
Creating a new document
The following script shows how to make a new document using scripting. (For the complete script, see
MakeDocument.)
var myDocument = app.documents.add();
To create a document using a document preset, the add method includes an optional parameter you can
use to specify a document preset, as shown in the following script. (For the complete script, see
MakeDocumentWithPreset.)
//Creates a new document using the specified document preset.
//Replace "myDocumentPreset" in the following line with the name
//of the document preset you want to use.
var myDocument = app.documents.add(true,
app.documentPresets.item("myDocumentPreset"));
You can create a document without displaying it in a window, as shown in the following script fragment
(from the MakeDocumentWithParameters tutorial script):
//Creates a new document without showing the document window.
//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.
var myDocument = app.documents.add(false);
//To show the window:
var myWindow = myDocument.windows.add();
Some script operations are much faster when the document window is hidden.
Opening a document
The following script shows how to open an existing document. (For the complete script, see
OpenDocument.)
app.open(File("/c/myTestDocument.indd"));
You can choose to prevent the document from displaying (that is, hide it) by setting the showing window
parameter of the
performance of a script. To show a hidden document, create a new window, as shown in the following
script fragment (from the OpenDocumentInBackground tutorial script):
//Opens an existing document in the background, then shows the document.
//You'll 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();
open method to false (the default is true). You might want to do this to improve
CHAPTER 3: DocumentsBasic Document Operations 21
Saving a document
In the InDesign user interface, you save a file by choosing File > Save, and you save a file to another file
name by choosing File > Save As. In InDesign scripting, the
shown in the following script fragment (from the SaveDocument tutorial script):
//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 first (to) specifies the file to save to; the second
stationery) can be set to true to save the document as a template, as shown in the following script
(
fragment (from the SaveDocumentAs tutorial script):
//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 displays the Save dialog box.
app.activeDocument.save(new File("/c/myTestDocument.indd"));
}
You can save a document as a template, as shown in the following script fragment (from the
SaveAsTemplate tutorial script):
save method can do either operation, as
//Save the active document as a template.
var myFileName;
if(app.activeDocument.saved == true){
//Convert the file name to a string.
myFileName = app.activeDocument.fullName + "";
//If the file name contains the extension ".indd", change it to ".indt".
if(myFileName.indexOf(".indd")!=-1){
}
//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);
Closing a document
The close method closes a document, as shown in the following script fragment (from the
CloseDocument tutorial script):
app.activeDocument.close();
//Note that you could also use:
//app.documents.item(0).close();
The close method can take up to two optional parameters, as shown in the following script fragment
(from the CloseWithParameters tutorial script):
CHAPTER 3: DocumentsBasic Page Layout 22
//Use SaveOptions.yes to save the document,SaveOptions.no to close the
//document without saving, or SaveOptions.ask to display a prompt. If
//you use SaveOptions.yes, you'll need to provide a reference to a file
//to save to in the second parameter (SavingIn).
//Note that the file path is provided using the JavaScript URI form
//rather than the platform-specific form.
//
//If the file has not been saved, display a prompt.
if(app.activeDocument.saved != true){
app.activeDocument.close(SaveOptions.ask);
//Or, to save to a specific file name:
//var myFile = File("/c/myTestDocument.indd");
//app.activeDocument.close(SaveOptions.yes, myFile);
}
else{
//If the file has already been saved, save it.
app.activeDocument.close(SaveOptions.yes);
}
You can close all open documents without saving them, as shown in the following script fragment (from
the CloseAll tutorial script):
Each document has a default page size, assigned number of pages, bleed and slug working areas, and
columns and margins to define the area into which material is placed. Again, all these parameters are
accessible to scripting, as shown in the examples in this section.
Defining page size and document length
When you create a new document using the InDesign user interface, you can specify the default page size,
number of pages, page orientation, and whether the document uses facing pages. To create a document
using InDesign scripting, use the
creating a document, you can use the
the following script fragment (from the DocumentPreferences tutorial script):
var myDocument = app.documents.add();
with(myDocument.documentPreferences){
NOTE: The app 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. You can also set
individual page sizes; see “Adjusting Page Sizes and Layout”
documents.add method, which does not specify these settings. After
documentPreferences object to control the settings, as shown in
.
CHAPTER 3: DocumentsBasic Page Layout 23
Defining bleed and slug areas
Within InDesign, a bleed or a slug is an area outside the page margins that can be printed or included in an
exported PDF. Typically, these areas are used for objects that extend beyond the page edges (bleed) and
job/document information (slug). The two areas can be printed and exported independently; for example,
you might want to omit slug information for the final printing of a document. The following script shows
how to set up the bleed and slug for a new document. (For the complete script, see BleedAndSlug.)
myDocument = app.documents.add();
//The bleed and slug properties belong to the documentPreferences object.
with(myDocument.documentPreferences){
Alternately, if all the bleed distances are equal, as in the preceding example, you can use the
documentBleedUniformSize property, as shown in the following script fragment (from the
UniformBleed tutorial script):
//Create a new document.
myDocument = app.documents.add();
//The bleed properties belong to the documentPreferences object.
with(myDocument.documentPreferences){
If all the slug distances are equal, you can use the documentSlugUniformSize property, as shown in the
following script fragment (from the UniformSlug tutorial script):
//Create a new document.
myDocument = app.documents.add();
//The slug properties belong to the documentPreferences object.
with(myDocument.documentPreferences){
In addition to setting the bleed and slug widths and heights, you can control the color used to draw the
guides defining the bleed and slug. This property is not in the
pasteboardPreferences object, as shown in the following script fragment (from the
in the
documentPreferences object; instead, it is
BleedSlugGuideColors tutorial script):
CHAPTER 3: DocumentsBasic Page Layout 24
with(app.activeDocument.pasteboardPreferences){
//Any of InDesign's 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];
}
Setting page margins and columns
Each page in a document can have its own margin and column settings. With InDesign scripting, these
properties are part of the
new document, then sets the margins and columns for all pages in the master spread. (For the complete
script, see PageMargins.)
myDocument = app.documents.add();
with (myDocument.pages.item(0).marginPreferences){
columnCount = 3;
//columnGutter can be a number or a measurement string.
columnGutter = "1p";
bottom = "6p"
//When document.documentPreferences.facingPages == true,
//"left" means inside; "right" means outside.
left = "6p"
right = "4p"
top = "4p"
}
marginPreferences object for each page. This following sample script creates a
To set the page margins for an individual page, use the margin preferences for that page, as shown in the
following script fragment (from the PageMarginsForOnePage tutorial script):
myDocument = app.documents.add();
with (myDocument.pages.item(0).marginPreferences){
columnCount = 3;
//columnGutter can be a number or a measurement string.
columnGutter = "1p";
bottom = "6p"
//When document.documentPreferences.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 left and right page margins, and the height of
the page must be greater than the sum of the top and bottom margins. If you are 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 fields in the New Document dialog box.
From scripting, however, the solution is not as clear: when you create a document, it uses the application’s
default-margin preferences. These margins are applied to all pages of the document, including master
pages. Setting the document margin preferences affects only new pages and has no effect 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 existing pages, InDesign does not change the page size.
CHAPTER 3: DocumentsBasic Page Layout 25
There are two solutions. The first is to set the margins of the existing pages before you try to change the
page size, as shown in the following script fragment (from the PageMarginsForSmallPages tutorial script):
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";
Alternately, you can change the application’s default-margin preferences before you create the document,
as shown in the following script fragment (from the ApplicationPageMargins tutorial script):
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;
}
//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;
}
Changing the appearance of the pasteboard
The pasteboard is the area that surrounds InDesign pages and spreads. You can use it for temporary
storage of page items or for job-tracking information. You can change the size of the pasteboard and its
color using scripting. The
mode, as shown in the following script fragment (from the PasteboardPreferences tutorial script):
previewBackgroundColor property sets the color of the pasteboard in Preview
//You can use either a number or a measurement string
//to set the space above/below.
minimumSpaceAboveAndBelow = "12p";
//You can set the preview background color to any of
//the predefined UIColor enumerations...
previewBackgroundColor = UIColors.gray;
//...or you can specify an array of RGB values
//(with values from 0 to 255)
//previewBackgroundColor = [192, 192, 192];
}
Guides and grids
Guides and grids make it easy to position objects on your document pages. These are very useful items to
add when you are creating templates for others to use.
Defining guides
Guides in InDesign give you an easy way to position objects on the pages of your document. The following
script fragment shows how to use guides. (For the complete script, see Guides.)
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, <lb>
location:marginPreferences.left});
guides.add(undefined, {orientation:HorizontalOrVertical.vertical, <lb>
location:(myPageWidth - marginPreferences.right)});
guides.add(undefined, {orientation:HorizontalOrVertical.horizontal, <lb>
location:marginPreferences.top});
guides.add(undefined, {orientation:HorizontalOrVertical.horizontal, <lb>
location:(myPageHeight - marginPreferences.bottom)});
//Place a guide at the vertical center of the page.
guides.add(undefined, {orientation:HorizontalOrVertical.vertical, <lb>
location:(myPageWidth/2)});
//Place a guide at the horizontal center of the page.
guides.add(undefined, {orientation:HorizontalOrVertical.horizontal, <lb>
location:(myPageHeight/2)});
}
Horizontal guides can be limited to a given page or extend across all pages in a spread. From InDesign
scripting, you can control this using the
fitToPage 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, as shown in the following script fragment (from the GuideOptions tutorial script):
CHAPTER 3: DocumentsBasic Page Layout 27
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, <lb>
location:marginPreferences.left});
guides.add(undefined, {orientation:HorizontalOrVertical.vertical, <lb>
location:(myPageWidth - marginPreferences.right)});
guides.add(undefined, {orientation:HorizontalOrVertical.horizontal, <lb>
location:marginPreferences.top});
guides.add(undefined, {orientation:HorizontalOrVertical.horizontal, <lb>
location:(myPageHeight - marginPreferences.bottom)});
//Place a guide at the vertical center of the page.
guides.add(undefined, {orientation:HorizontalOrVertical.vertical, <lb>
location:(myPageWidth/2)});
//Place a guide at the horizontal center of the page.
guides.add(undefined, {orientation:HorizontalOrVertical.horizontal, <lb>
location:(myPageHeight/2)});
}
You also can create guides using the createGuides method on spreads and master spreads, as shown in
the following script fragment (from the CreateGuides tutorial script):
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));
}
Setting grid preferences
To control the properties of the document and baseline grid, you set the properties of the
gridPreferences object, as shown in the following script fragment (from the DocumentAndBaselineGrid
tutorial script):
var myDocument = app.documents.add();
//Set the document measurement units to points.
myDocument.viewPreferences.horizontalMeasurementUnits = MeasurementUnits.points;
myDocument.viewPreferences.verticalMeasurementUnits = MeasurementUnits.points;
//Set up grid preferences.
with(myDocument.gridPreferences){
documentGridShown = false;
documentGridSnapTo = true;
//Objects "snap" to the baseline grid when
//guidePreferences.guideSnapTo is set to true.
baselineGridShown = true;
}
Changing measurement units and ruler
Thus far, the sample scripts used measurement strings, strings that force InDesign to use a specific
measurement unit (for example, “8.5i” for 8.5 inches). They do this because you might be using a different
measurement system when you run the script.
To specify the measurement system used in a script, use the document’s
viewPreferences object, as
shown in the following script fragment (from the ViewPreferences tutorial script):
var myDocument = app.activeDocument;
with(myDocument.viewPreferences){
//Measurement unit choices are:
//* MeasurementUnits.agates
//* 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 you are writing a script that needs to use a specific measurement system, you can change the
measurement units at the beginning of the script, then restore the original measurement units at the end
of the script. This is shown in the following script fragment (from the ResetMeasurementUnits tutorial
script):
CHAPTER 3: DocumentsBasic Page Layout 29
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 you've set. At the end of
//the script, reset the measurement units to their original state.
with (myDocument.viewPreferences){
alert("Could not reset custom measurement units.");
}
}
Defining and applying document presets
InDesign document presets enable you to store and apply common document set-up information (page
size, page margins, columns, and bleed and slug areas). When you create a new document, you can base
the document on a document preset.
Creating a preset by copying values
To create a document preset using an existing document’s settings as an example, open a document that
has the document set-up properties you want to use in the document preset, then run the following script
(from the DocumentPresetByExample tutorial script):
var myDocumentPreset;
if(app.documents.length > 0){
var myDocument = app.activeDocument;
//If the document preset "myDocumentPreset" does not already
//exist, create it.
myDocumentPreset = app.documentPresets.item("myDocumentPreset");
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.horizontalMeasurementUnits;
app.viewPreferences.verticalMeasurementUnits =
myDocument.viewPreferences.verticalMeasurementUnits;
//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
CHAPTER 3: DocumentsBasic Page Layout 30
//active window is a layout window).
var myMarginPreferences = app.activeDocument.marginPreferences;
To create a document preset using explicit values, run the following script (from the DocumentPreset
tutorial script):
var myDocumentPreset;
//If the document preset "myDocumentPreset" does not already exist, create it.
myDocumentPreset = app.documentPresets.item("myDocumentPreset");
try {