2012 Adobe Systems Incorporated. All rights reserved.
Adobe® InDesign® CS6 Scripting Guide: AppleScript
Document Update Status
(for entire document; see each chapter for chapter-specific update status)
CS6UpdatedThroughout document, changed CS5 to CS6 and version 7.0 to 8.0.
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.
Work with the Adobe® InDesign® scripting environment.
Use advanced scripting features.
Perform basic document tasks like setting up master spreads, printing, and exporting.
Work with page items (rectangles, ellipses, graphic lines, polygons, text frames, and groups).
Work with text and type in an InDesign document, including finding and changing text.
Create dialog boxes and other user-interface items.
Customize and add menus and create menu actions.
Respond to user-interface events.
Work with XML, from creating XML elements and importing XML to adding XML elements to a layout.
Apply 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 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 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.
. After you have downloaded and
9
CHAPTER 1: IntroductionAbout the Structure of the Scripts 10
About the Structure of the Scripts
The script examples are all written using a common template that includes the handlers “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” handler.
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.
. In the forum, script writers can ask questions, post answers, and share their
2
Chapter Update Status
CS6Updated“Script Versioning” on page 12 and its three subsections have been updated, corrected, and clarified.
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:
The script preferences object and its properties.
Getting a reference to the executing script.
Running scripts in prior versions of the scripting object model.
Using the do script method to run scripts.
Working with script labels.
Running scripts at InDesign start-up.
We assume that you have already read Adobe InDesign 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 script preferences object:
PropertyDescription
enable redraw
scripts folder
scripts list
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
user interaction
level
This property controls the alerts and dialogs InDesign presents to the user.
When you set this property to
any alerts or dialogs. Set it to
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
then restore user interaction (set the property to
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 active script 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):
tell application "Adobe InDesign CS6"
set myScript to active script
display dialog ("The current script is: " & myScript)
tell application "Finder"
set myFile to file myScript
set myParentFolder to container of myFile
end tell
display dialog ("The folder containing the active script is: " & myParentFolder)
end tell
never interact, InDesign does not display
interact with alerts to enable alerts but
interact with all to restore the normal display of
never interact before opening the document,
interact with all) before
. Note this property is not the same as the
When you debug scripts using a script editor, the active script property returns an error. Only scripts
run from the Scripts palette appear in the
Script Versioning
InDesign 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:
Targeting — Scripts must be targeted to the version of InDesign in which they are being run (i.e., the
current version). The mechanics of targeting are language specific as described in “Targeting” on
page 13.
Compilation — This involves mapping the names in the script to the underlying script IDs, which are
what InDesign understands. The mechanics of compilation are language specific as described in
“Compilation” on page 13
Interpretation — This involves matching the IDs to the appropriate request handler within InDesign
so that InDesign correctly interprets a script written for an earlier version of the scripting object model.
To do this, either explicitly set the application’s script preferences to the old object model within the
active script property.
.
CHAPTER 2: Scripting FeaturesScript Versioning 13
script (as shown in “Interpretation” on page 13) or run the script from a folder in the Scripts panel
folder as follows:
FolderFor InDesign version of scripts
Version 8.0 Scripts
Version 7.0 Scripts
Version 6.0 Scripts
Version 5.0 Scripts
Version 2.0 Scripts
Targ eting
A script must always target the version of InDesign under which it is running (the current version), either
explicitly or implicitly. Targeting is implicit when the script is launched from the Scripts panel.
Otherwise, explicit targeting for AppleScripts is done using the tell statement:
Typically, AppleScripts are compiled using the targeted application’s dictionary. This behavior may be
overridden by means of the
InDesign dictionary for compilation purposes. For example, to use a CS5 script (version 7.0) within CS6
(version 8.0):
CS6
CS5 and CS5.5
CS4
CS3
CS2
using terms from statement, which substitutes a different version of the
--publish the InDesign CS5 dictionary (version 7.0 DOM)
publish terminology version 7.0
end tell
Interpretation
The InDesign application object contains a script preferences 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.
Scripting Support folder in your application’s
CHAPTER 2: Scripting FeaturesUsing the do script Method 14
For example, to change the version of the scripting object model to CS5 (7.0):
--Set to 7.0 scripting object model
set version of script preferences to 7.0
Using the do script 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
do script method has many possible uses:
Running a script in another language that provides a feature missing in your main scripting language.
, VBScript or JavaScript.
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
do script method can execute a snippet of scripting code in another language,
to overcome a limitation of the language used for the body of the script.
®
, you can run
®
Excel for the
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
do script 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.
Embedding 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 do script
To send a parameter to a script executed by doscript, use the following form (from the
DoScriptParameters tutorial script):
tell application "Adobe InDesign CS6"
--Create a list of parameters.
set myParameters to {"Hello from do script", "Your message here."}
--Create a JavaScript as a string.
set myJavaScript to "alert(\"First argument: \" + arguments[0] +
\"\\rSecond argument: \" + arguments[1])"
--Run the JavaScript using the do script command.
do script myJavaScript language javascript with arguments myParameters
--Create an AppleScript as a string.
set myAppleScript to "tell application \"Adobe InDesign CS6\"" & return
set myAppleScript to myAppleScript & "display dialog (\"First argument: \" &
item 1 of arguments & return & \"Second argument: \" & item 2 of arguments)" & return
set myAppleScript to myAppleScript & "end tell"
--Run the AppleScript using the do script command.
do script myAppleScript language applescript language with arguments myParameters
end tell
.
CHAPTER 2: Scripting FeaturesUsing the do script Method 15
Returning values from do script
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).
set myDocument to document 1
set myPage to page 1 of myDocument
set myTextFrame to text frame 1 of myPage
tell myDocument
set myDestinationPage to make page
end tell
set myPageIndex to name of myDestinationPage
set myID to id of myTextFrame
set myJavaScript to "var myDestinationPage = arguments[1];" & return
set myJavaScript to myJavaScript & "myID = arguments[0];" & return
set myJavaScript to myJavaScript & "var myX = arguments[2];" & return
set myJavaScript to myJavaScript & "var myY = arguments[3];" & return
set myJavaScript to myJavaScript & "var myPageItem =
app.documents.item(0).pages.item(0).pageItems.itemByID(myID);" & return
set myJavaScript to myJavaScript &
"myPageItem.duplicate(app.documents.item(0).pages.item(myDestinationPage));" & return
--Create an array for the parameters we want to pass to the JavaScript.
set myArguments to {myID, myPageIndex, 0, 0}
set myDuplicate to do script myJavaScript language javascript with arguments
myArguments
--myDuplicate now contains a reference to the duplicated text frame.
--Change the text in the duplicated text frame.
set contents of myDuplicate to "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):
tell application "Adobe InDesign CS6"
--Create a string to be run as an AppleScript.
set myAppleScript to "tell application \"Adobe InDesign CS6\"" & return
set myAppleScript to myAppleScript & "tell script args" & return
set myAppleScript to myAppleScript & "set value name \"ScriptArgumentA\"
value \"This is the first AppleScript script argument value.\"" & return
set myAppleScript to myAppleScript & "set value name \"ScriptArgumentB\"
value \"This is the second AppleScript script argument value.\"" & return
set myAppleScript to myAppleScript & "end tell" & return
set myAppleScript to myAppleScript & "end tell"
--Run the AppleScript string.
do script myAppleScript language applescript language
--Retrieve the script argument values set by the script.
tell script args
set myScriptArgumentA to get value name "ScriptArgumentA"
set myScriptArgumentB to get value name "ScriptArgumentB"
end tell
--Display the script argument values in a dialog box.
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.
do script command offers a way around this performance bottleneck by providing two parameters
The
that control the way that scripts are executed relative to InDesign’s Undo behavior. These parameters are
shown in the following examples:
--Given a script "myAppleScript" and an array of parameters "myParameters"...
tell application "Adobe InDesign CS6"
do script myJavaScript language javascript with arguments myArguments undo mode fast
entire script undo name "Script Action"
end tell
--undo modes can be:
--auto unto: Add no events to the Undo queue.
--entire script: Put a single event in the Undo queue.
--fast entire script: Put a single event in the Undo queue.
--script request: 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):
set myDocument to make document
set myPage to page 1 of myDocument
set myPageWidth to page width of document preferences of myDocument
set myPageHeight to page height of document preferences of myDocument
--Create 10 random page items.
repeat with i from 1 to 10
set myX1 to my myGetRandom(0, myPageWidth, false)
set myY1 to my myGetRandom(0, myPageHeight, false)
set myX2 to my myGetRandom(0, myPageWidth, false)
set myY2 to my myGetRandom(0, myPageHeight, false)
tell myPage
set myRectangle to make rectangle with properties {geometric bounds:{myY1, myX1,
myY2, myX2}}
end tell
if my myGetRandom(0, 1, true) = 1 then
set label of myRectangle to "myScriptLabel"
end if
end repeat
set myCount to 0
repeat with i from 1 to count of page items of myPage
if label of page item i of myPage is "myScriptLabel" then
set myCount to myCount + 1
end if
end repeat
display dialog ("Found " & myCount & " page items with the label.")
--This function gets a random number in the range myStart to myEnd.
on myGetRandom(myStart, myEnd, myInteger)
set myRange to myEnd - myStart
if myInteger = true then
set myRandom to myStart + (random number from myStart to myEnd)
else
set myRandom to myStart + (random number from myStart to myEnd) as integer
end if
return myRandom
end myGetRandom
In addition, all objects that support the label property also support custom labels. A script can set a
custom label using the
insert label method, and extract the custom label using the extract label
method, as shown in the following script fragment (from the CustomLabel tutorial script):
CHAPTER 2: Scripting FeaturesRunning Scripts at Startup 18
tell application "Adobe InDesign CS6"
set myDocument to make document
tell view preferences of myDocument
set horizontal measurement units to points
set vertical measurement units to points
end tell
set myPage to page 1 of myDocument
tell myPage
set myRectangle to make rectangle with properties
{geometric bounds:{72, 72, 144, 144}}
--Insert a custom label using insert label. The first parameter is the
--name of the label, the second is the text to add to the label.
tell myRectangle
insert label key "CustomLabel" value "This is some text stored
in a custom label."
--Extract the text from the label and display it in an alert.
set myString to extract label key "CustomLabel"
end tell
display dialog ("Custom label contained: " & myString)
end tell
end tell
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 Scripting Tutorial).
3
Chapter Update Status
CS6Changes• Updated list of what this chapter shows you how to do.
•Added section “Making an Adaptive Layout” on page 43
.
•Added section “Collecting and Dropping Content” on page 46
.
• Added subsection “Exporting to grayscale PDF” on page 53
.
• Added subsection “Exporting as a PDF form” on page 56
.
•In “Adjusting Page Sizes and Layout” on page 41
, “Resizing and reframing pages” on page 41, and “Transforming pages” on
page 42, removed outdated references to features being new in CS5.
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.
Apply different sizes to different pages (multiple page sizes).
Apply flexible layout formats to the same pages for use in different devices or documents with
different sizes or orientation.
Print a document.
Export a document as Adobe PDF.
Export pages of a document as EPS.
Export a document as an ePub file.
We assume that you have already read Adobe InDesign Scripting Tutorial and know how to create, install,
and run a script.
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.)
tell application "Adobe InDesign CS6"
set myDocument to make document
end tell
To create a document using a document preset, the make command includes an optional parameter you
can use to specify a document preset, as shown in the following script. (For the complete script, see
MakeDocumentWithPreset.)
tell application "Adobe InDesign CS6"
--Replace "myDocumentPreset" in the following line with the name
--of the document preset you want to use.
set myDocument to make document with properties
{document preset:"myDocumentPreset"}
end tell
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 "showing window" parameter controls the visibility of the document.
--Hidden documents are not minimized, and will not appear until
--you tell the document to create a new window.
tell application "Adobe InDesign CS6"
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
Some script operations are much faster when the document window is hidden.
CHAPTER 3: DocumentsBasic Document Operations 21
Opening a document
The following script shows how to open an existing document. (For the complete script, see
OpenDocument.)
tell application "Adobe InDesign CS6"
--You'll have to fill in your own file path.
set myDocument to open "yukino:myTestDocument.indd"
end tell
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):
tell application "Adobe InDesign CS6"
--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 you've
--opened this way, tell the document to create a new window.
--You'll have to fill in your own file path.
set myDocument to open "yukino:myTestDocument.indd" <lb>
without showing window
--At this point, your script could change or get information
--from the hidden document. Once you've done that, you can show
--the document window:
tell myDocument to make window
end tell
open command to false (the default is true). You might want to do this to improve
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):
--Saves the active document.
--If the active document has been changed since it was last saved, save it.
tell application "Adobe InDesign CS6"
if modified of active document is true then
tell active document to save
end if
end tell
The save command 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.
tell application "Adobe InDesign CS6"
if saved of active document is false then
--If you do not provide a file name, InDesign displays the Save dialog box.
tell active document to save saving in "yukino:myTestDocument.indd"
end if
end tell
You can save a document as a template, as shown in the following script fragment (from the
SaveAsTemplate tutorial script):
save command can do either operation, as
CHAPTER 3: DocumentsBasic Document Operations 22
--Save the active document as a template.
tell application "Adobe InDesign CS6"
set myDocument to active document
tell myDocument
if saved is true then
--Convert the file name to a string.
set myFileName to full name
set myFileName to my myReplace(myFileName, ".indd", ".indt")
else
--If the document has not been saved, then give it a default file
--name/file path. You'll have to fill in the file path.
set myFileName to "yukino:myTestDocument.indt"
end if
save to myFileName with stationery
end tell
end tell
on myReplace(myString, myFindString, myChangeString)
set AppleScript's text item delimiters to myFindString
set myTextList to every text item of (myString as text)
set AppleScript's text item delimiters to myChangeString
set myString to myTextList as string
set AppleScript's text item delimiters to ""
return myString
end myReplace
Closing a document
The close command closes a document, as shown in the following script fragment (from the
CloseDocument tutorial script):
tell application "Adobe InDesign CS6"
close document 1
--document 1 always refers to the front-most document.
--Note that you could also use:
--close active document
end tell
The close command can take up to two optional parameters, as shown in the following script fragment
(from the CloseWithParameters tutorial script):
tell application "Adobe InDesign CS6"
--Use "saving yes" to save the document,
--or "saving no" to close the document without saving,
--or "saving ask" to display a prompt. If you use
--"saving yes",you'll need to provide a reference
--to a file to save to in the second parameter (saving in).
--If the file has never been saved (it's an untitled file),
--display a prompt.
if saved of active document is not equal to true then
close active document saving ask
--Or, to save to a specific file name
--(you'll have to fill in the file path):
--set myFile to "yukino:myTestDocument.indd"
--close active document saving yes saving in myFile
else
--If the file has already been saved to a file, save it.
close active document saving yes
end if
end tell
CHAPTER 3: DocumentsBasic Page Layout 23
You can close all open documents without saving them, as shown in the following script fragment (from
the CloseAll tutorial script):
tell application "Adobe InDesign CS6"
tell documents to close without saving
end tell
Basic Page Layout
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):
make document command, which does not specify these settings. After
document preferences object to control the settings, as shown in
tell application "Adobe InDesign CS6"
set myDocument to make document
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 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”
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.)
.
CHAPTER 3: DocumentsBasic Page Layout 24
tell application "Adobe InDesign CS6"
--Create a new document.
set myDocument to make document
--The bleed and slug properties belong to the document preferences object.
tell document preferences of myDocument
--Bleed
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"
--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
end tell
Alternately, if all the bleed distances are equal, as in the preceding example, you can use the document
bleed uniform size property, as shown in the following script fragment (from the UniformBleed tutorial
script):
tell application "Adobe InDesign CS6"
--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 use the document slug uniform size property, as shown in the
following script fragment (from the UniformSlug tutorial script):
tell application "Adobe InDesign CS6"
--Create a new document.
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 defining the bleed and slug. This property is not in the
pasteboard preferences object, as shown in the following script fragment (from the
in the
document preferences object; instead, it is
BleedSlugGuideColors tutorial script):
CHAPTER 3: DocumentsBasic Page Layout 25
tell application "Adobe InDesign CS6"
--Assumes you have a document open.
tell pasteboard preferences of active document
--Any of InDesign's 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
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.)
tell application "Adobe InDesign CS6"
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 master spread 1 of myDocument
tell margin preferences of pages
set top to 36
set left to 36
set bottom to 48
set right to 36
end tell
end tell
end tell
margin preferences 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):
tell application "Adobe InDesign CS6"
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
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 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
CHAPTER 3: DocumentsBasic Page Layout 26
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.
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):
tell application "Adobe InDesign CS6"
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
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):
CHAPTER 3: DocumentsBasic Page Layout 27
tell application "Adobe InDesign CS6"
tell margin preferences
--Save the current application default margin preferences.
set myY1 to top
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
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
preview background color property sets the color of the pasteboard in Preview
mode, as shown in the following script fragment (from the PasteboardPreferences tutorial script):
tell application "Adobe InDesign CS6"
set myDocument to make document
tell pasteboard preferences of myDocument
--You can use either a number or a measurement string to set the
--space above/below.
set minimum space above and below to "12p"
--You can set the pasteboard background color to any
--of the predefined UIColor constants...
set preview background color to gray
--...or you can specify an array of RGB values
--(with values from 0 to 255)
--set preview Background Color to {192, 192, 192}
end tell
end tell
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.
CHAPTER 3: DocumentsBasic Page Layout 28
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.)
tell application "Adobe InDesign CS6"
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 extend across all pages in a spread. From 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, as shown in the following script fragment (from the GuideOptions tutorial script):
CHAPTER 3: DocumentsBasic Page Layout 29
tell application "Adobe InDesign CS6"
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, <lb>
location:"12p", item layer:myLayer}
make guide with properties {item layer:myLayer, <lb>
orientation:horizontal, location:"14p"}
--Make a locked guide.
make guide with properties {locked:true, <lb>
orientation:horizontal, location:"16p"}
--Set the view threshold of a guide.
make guide with properties {view threshold:100, <lb>
orientation:horizontal, location:"18p"}
--Set the guide color of a guide using a UIColors constant.
make guide with properties {guide color:gray, <lb>
orientation:horizontal, location:"20p"}
--Set the guide color of a guide using an RGB array.
make guide with properties {guide color:{192, 192, 192}, <lb>
orientation:horizontal, location:"22p"}
end tell
end tell
end tell
You also can create guides using the create guides command on spreads and master spreads, as shown
in the following script fragment (from the CreateGuides tutorial script):
tell application "Adobe InDesign CS6"
set myDocument to make document
tell spread 1 of myDocument
--column gutter, guide color, fit margins, remove existing, layer.
--Note that the create guides command does not take an RGB
--array for the guide color parameter.
create guides number of rows 4 number of columns 4 row gutter "1p" <lb>
column gutter "1p" guide color gray with fit margins and remove existing
end tell
end tell
Setting grid preferences
To control the properties of the document and baseline grid, you set the properties of the grid
preferences object, as shown in the following script fragment (from the DocumentAndBaselineGrid
tutorial script):
CHAPTER 3: DocumentsBasic Page Layout 30
tell application "Adobe InDesign CS6"
set myDocument to make document
set horizontal measurement units of view preferences of myDocument to points
set vertical measurement units of view preferences of myDocument to points
tell grid preferences of myDocument
set baseline start to 56
set baseline division to 14
set baseline grid shown to true
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 true
end tell
end tell
Snapping to guides and grids
All snap settings for a document’s grids and guides are in the properties of the guide preferences and
grid preferences objects. The following script fragment shows how to set guide and grid snap
properties. (For the complete script, see GuideGridPreferences.)
tell application "Adobe InDesign CS6"
set myDocument to active document
tell guide preferences of myDocument
set guides in back to true
set guides locked to false
set guides shown to true
set guides snapto to true
end tell
tell grid preferences of myDocument
set document grid shown to false
set document grid snapto to true
--Objects "snap" to the baseline grid when guidePreferences.guideSnapTo
--is set to true.
set baseline grid shown to true
end tell
end tell
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
shown in the following script fragment (from the ViewPreferences tutorial script):
view preferences object, as
CHAPTER 3: DocumentsBasic Page Layout 31
tell application "Adobe InDesign CS6"
set myDocument to active document
tell view preferences of myDocument
--Measurement unit choices are:
--picas, points, inches, inches decimal, millimeters, centimeters, or ciceros
--Set horizontal and vertical measurement units to points.
set horizontal measurement units to points
set vertical measurement units to points
end tell
end tell
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):
tell application "Adobe InDesign CS6"
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 you've 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
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):
CHAPTER 3: DocumentsBasic Page Layout 32
tell application "Adobe InDesign CS6"
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
Creating a document preset
To create a document preset using explicit values, run the following script (from the DocumentPreset
tutorial script):
CHAPTER 3: DocumentsBasic Page Layout 33
tell application "Adobe InDesign CS6"
--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.
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
Setting up master spreads
After setting up the basic document page size, slug, and bleed, you probably will want to define the
document’s master spreads. The following script shows how to do that. (For the complete script, see
MasterSpread.)
tell application "Adobe InDesign CS6"
set myDocument to make document
--Set up the document.
tell document preferences of myDocument
set page height to "11i"
set page width to "8.5i"
set facing pages to true
set page orientation to portrait
end tell
--Set the document's ruler origin to page origin. This is very important--
--if you don't do this, getting objects to the correct position on the
--page is much more difficult.
set ruler origin of view preferences of myDocument to page origin
tell master spread 1 of myDocument
--Set up the left page (verso).
tell margin preferences of page 1
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"
CHAPTER 3: DocumentsBasic Page Layout 34
set top to "4p"
end tell
--Add a simple footer with a section number and page number.
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, as
shown in the following script fragment (from the ApplyMaster tutorial script):
--Assumes that the active document has a master page named "B-Master"
--and at least three document pages.
tell application "Adobe InDesign CS6"
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, as shown in the following script
fragment (from the ApplyMasterToMaster tutorial script):
--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 CS6"
tell active document
set applied master of page 2 of master spread 1 to
master spread "B-Master"
end tell
end tell
CHAPTER 3: DocumentsBasic Page Layout 35
Adding XMP metadata
Metadata is information that describes the content, origin, or other attributes of a file. In the InDesign user
interface, you enter, edit, and view metadata using the File Info dialog (choose File > File Info). This
metadata includes the document’s creation and modification dates, author, copyright status, and other
information. All this information is stored using XMP (Adobe Extensible Metadata Platform), an open
standard for embedding metadata in a document.
To learn more about XMP, see the XMP specification at
You also can add XMP information to a document using InDesign scripting. All XMP properties for a
document are in the document’s metadataPreferences object. The example below fills 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 a category provided by the metadata preferences object, you can create
your own metadata container (
tell application "Adobe InDesign CS6"
set myDocument to make document
tell metadata preferences of myDocument
set author to "Adobe"
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
set property namespace "http://ns.adobe.com/xap/1.0/" ¬
path "email/*[1]" value "someone@adobe.com"
end tell
end tell
email, in this example). (For the complete script, see MetadataExample.)
.
Creating a document template
This example creates a new document, defines slug and bleed areas, adds information to the document’s
XMP metadata, sets up master pages, adds page footers, and adds job information to a table in the slug
area. (For the complete script, see DocumentTemplate.)
CHAPTER 3: DocumentsBasic Page Layout 36
tell application "Adobe InDesign CS6"
--Make a new document.
set myDocument to make document
tell myDocument
tell document preferences
set page width to "7i"
set page height to "9i"
set page orientation to portrait
end tell
tell margin preferences
set top to ((14 * 4) & "pt") as string
set left to ((14 * 4) & "pt") as string
set bottom to "74pt"
set right to ((14 * 5) & "pt") as string
end tell
--Set up the bleed and slug areas.
tell document preferences
--Bleed
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"
--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
CHAPTER 3: DocumentsBasic Page Layout 37
--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
tell grid preferences
set property namespace "http://ns.adobe.com/xap/1.0/"
path "email/*[1]" value "someone@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
CHAPTER 3: DocumentsBasic Page Layout 38
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]"
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
CHAPTER 3: DocumentsBasic Page Layout 39
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
)
Creating watermarks
You can apply watermarks to documents in InDesign or InDesign Server using scripting. Currently, no user
interface component exists in InDesign for managing watermarks.
A document’s watermark preferences can be set in two ways using scripting:
Application-level watermark preferences, if any are set, are applied to the document watermark
preferences for each new document created by InDesign. This setting has no effect on existing
documents.
Document-level watermark preferences apply only to that document. Setting or changing a
document’s watermark preferences replaces any previous watermark settings for the document.
CHAPTER 3: DocumentsBasic Page Layout 40
Both the document and application watermark preference settings persist after the document or
application is closed until a script changes them.
The same group of watermark preferences exist for both the document and the application objects.
Setting watermark preferences
The following script fragment shows how to set watermarks at the application level. A watermark will be
applied to all documents created after this code finishes. (For the complete script for setting application
preferences, see ApplicationWatermark.)
tell watermark preferences
set watermark visibility to true
set watermark do print to true
set watermark draw in back to true
set watermark text to "Confidential"
set watermark font family to "Arial"
set watermark font style to "Bold"
set watermark font point size to 72
set watermark font color to red
set watermark opacity to 60
set watermark rotation to -45
set watermark horizontal position to watermark h center
set watermark horizontal offset to 0
set watermark vertical position to watermark v center
set watermark vertical offset to 0
end tell
The same preferences can be applied to a document object by referring to a document, rather than to the
application. (For the complete script for setting document preferences, see DocumentWatermark.)
tell watermark preferences of document 1
set watermark visibility to true
set watermark do print to true
set watermark draw in back to true
set watermark text to "Confidential"
set watermark font family to "Arial"
set watermark font style to "Bold"
set watermark font point size to 72
set watermark font color to blue
set watermark opacity to 60
set watermark rotation to -45
set watermark horizontal position to watermark h center
set watermark horizontal offset to 0
set watermark vertical position to watermark v center
set watermark vertical offset to 0
end tell
Disabling watermarks
After turning off the application setting for watermarks, InDesign no longer turns on the watermark
settings for new documents by default. However, you can still set watermarks for individual documents.
The following script fragment shows how to turn off application-level watermarks.
tell application "Adobe InDesign CS6"
set watermark visibility of watermark preferences to false
end tell
CHAPTER 3: DocumentsAdjusting Page Sizes and Layout 41
You can turn off watermarks in an individual document at any time, as shown in the following script
fragment.
tell application "Adobe InDesign CS6"
tell document 1
set watermark visibility of watermark preferences to false
end tell
end tell
Adjusting Page Sizes and Layout
InDesign allows different page sizes within a single InDesign document. For information on setting the
default page size, see “Defining page size and document length”
You can also apply geometric transformations to individual pages.
Selecting pages
Before changing a page’s size or applying a transformation to the page, you must select the page. In the
InDesign user interface, you do this using the Page Tool on the Tools Panel. You can also select a page
using scripting. The following script shows how. (For the complete script, see PageSelect.)
.
--Given a document with four pages (1, 2, 3, 4)...
set myPages to pages of active document
--Select page 2 and 3.
select item 2 of myPages
select item 3 of myPages existing selection add to
--Select last page.
select item -1 of myPages existing selection add to
Resizing and reframing pages
You can resize or reframe page items on a page by scripting. You can also apply the resize and reframe
operations to pages to change their sizes.
NOTE: Your minimum page size is determined by the page’s margins. See “Setting page margins and
columns” for more information.
The following script shows how to change a page’s size using the resize method. (For the complete script,
see PageResize.)
--Given a document with four pages (1, 2, 3, 4)...
tell pages of active document
--Resize page to two times bigger
resize item 2 in inner coordinates from center anchor by multiplying current
dimensions by values {2, 2}
--Resize page to 400 points width and 600 points height.
resize item 3 in inner coordinates from center anchor by replacing current
dimensions with values {400, 600}
end tell
Reframing changes the bounding box of a page, so reframing can be used to change a page’s size by
making the bounding box larger or smaller. The following script shows how to change a page’s size using
the reframe method. (For the complete script, see PageReframe.)
CHAPTER 3: DocumentsAdjusting Page Sizes and Layout 42
--Given a document with four pages (1, 2, 3, 4)...
tell item 2 of pages of active document
--Make the page one inch wider and one inch higher.
set myBounds to bounds
set myY1 to item 1 of myBounds
set myX1 to item 2 of myBounds
set myY2 to (item 3 of myBounds) + 72
set myX2 to (item 4 of myBounds) + 72
reframe in inner coordinates opposing corners {{myX1, myY1}, {myX2, myY2}}
end tell
Transforming pages
Operations that change the geometry of objects are called transformations. The transform method can
rotate, scale, shear, and move (translate) page items on a page and can also be used on pages. For
technical details about transformation architecture, refer to “Transforming Page Items”
To transfor m a page:
1.Create a transformation matrix.
2.Apply the transformation matrix to the page using the transform method.
.
The following script shows how to transform a page with scripting. (For the complete script, see
PageTransform.)
--Given a document with four pages (1, 2, 3, 4)...
set myDocument to active document
set myPages to pages of myDocument
--Rotate a page around its center point.
set myRotateMatrix to make transformation matrix with properties {counterclockwise
rotation angle:27}
my myTransform(item 1 of myPages, myRotateMatrix)
--Scale a page around its center point.
set myScaleMatrix to make transformation matrix with properties {horizontal scale
factor:0.8, vertical scale factor:0.8}
my myTransform(item 2 of myPages, myScaleMatrix)
--Shear a page around its center point.
set myShearMatrix to make transformation matrix with properties {clockwise shear
angle:30}
my myTransform(item 3 of myPages, myShearMatrix)
on myTransform(myPage, myTransformationMatrix)
tell application "Adobe InDesign CS6"
transform myPage in pasteboard coordinates from center anchor with matrix
myTransformationMatrix
end tell
end myTransform
Master page overlay
Because pages can have multiple sizes, it is possible for a page and its master page to be different sizes. In
addition to tracking which master is applied, pages also maintain a matrix that determines how the master
page draws on the page. This is called the Master Page Overlay. When you select a page using the Page
CHAPTER 3: DocumentsMaking an Adaptive Layout 43
Tool on the Tools Panel, you can see how the master page is positioned by checking the Show Master Page
Overlay checkbox on the control panel. You can move the overlay around with the mouse. InDesign
achieves this by applying a transform to the master overlay matrix. Although the user interface allows only
translation (moving x and y), you can do more by scripting. The following script shows how to transform a
master page overlay. (For the complete script, see MasterPageTransform.)
--Given a document with four pages (1, 2, 3, 4)...
set myDocument to active document
set myPages to pages of myDocument
--Rotate master page overlay around its top-left corner.
set myRotateMatrix to make transformation matrix with properties {counterclockwise
rotation angle:27}
set master page transform of item 1 of myPages to myRotateMatrix
--Scale master page overlay around its top-left corner.
set myScaleMatrix to make transformation matrix with properties {horizontal scale
factor:0.5, vertical scale factor:0.5}
set master page transform of item 2 of myPages to myScaleMatrix
--Shear master page overlay around its top-left corner.
set myShearMatrix to make transformation matrix with properties {clockwise shear
angle:30}
set master page transform of item 3 of myPages to myShearMatrix
--Translate master page overlay 1 inch right and 2 inches down.
set myTranslateMatrix to make transformation matrix with properties {horizontal
translation:72, vertical translation:144}
set master page transform of item 4 of myPages to myTranslateMatrix
Making an Adaptive Layout
Using InDesign’s layout adaptation workflow, you create your primary layout the same way that you would
create it for a document that will be printed, but then you can quickly adapt that layout to another
orientation, to another dimension or aspect ratio, or to a completely different device class. This workflow
mainly involves two features: Liquid Layout makes the layout flexible, and Create Alternate Layout creates
alternative layouts for different orientations and device classes.
Making a flexible layout
Using layout rules, a designer can create one InDesign file with one set of physical pages that can display
their content suitably on different devices with different sizes and orientations. You can optionally control
the pages’ appearance for each size and orientation. The following example script shows how to do this.
(For the complete script, see LiquidLayout.)
CHAPTER 3: DocumentsMaking an Adaptive Layout 44
tell application "Adobe InDesign CS6"
set myDocument to make document
set myPage to page 1 of myDocument
-- Set layout rule to object rule
tell myPage
--Reposition and resize objects on the page as it resizes.
set layout rule to object based
--Create a text frame on the first page.
set myTextFrame to make text frame
set geometric bounds of myTextFrame to my myGetBounds(myDocument, myPage)
set contents of myTextFrame to "This is object based layoutrule sample doc."
--Create a rectangle
set myItem to make rectangle
set geometric bounds of myItem to {20, 20, 70, 70}
set vertical layout constraints of myItem to {flexible dimension,
flexible dimension, flexible dimension}
set horizontal layout constraints of myItem to {fixed dimension,
flexible dimension, flexible dimension}
end tell
end tell
tell application "Adobe InDesign CS6"
set myDocument2 to make document
set myPage2 to page 1 of myDocument2
-- Set layout rule to scale
tell myPage2
--Scale objects on the page as it resizes.
set layout rule to scale
--Create a text frame on the first page.
set myTextFrame2 to make text frame
set geometric bounds of myTextFrame2 to my myGetBounds(myDocument2, myPage2)
set contents of myTextFrame2 to "This is scale layoutrule sample doc."
set myItem2 to make rectangle
set geometric bounds of myItem2 to {20, 20, 70, 70}
end tell
end tell
tell application "Adobe InDesign CS6"
set myDocument3 to make document
set myPage3 to page 1 of myDocument3
-- Set layout rule to recenter
tell myPage3
--Recenter objects on the page as it resizes.
set layout policy to recenter
--Create a text frame on the first page.
set myTextFrame3 to make text frame
set geometric bounds of myTextFrame3 to my myGetBounds(myDocument3, myPage3)
set contents of myTextFrame3 to "This is recenter layoutrule sample doc."
set myItem3 to make rectangle
set geometric bounds of myItem3 to {20, 20, 70, 70}
end tell
end tell
tell application "Adobe InDesign CS6"
set myDocument4 to make document
set myPage4 to page 1 of myDocument4
-- Set layout rule to guide based
tell myPage4
--objects based on the page as it resizes.
set layout policy to guide based
--Create a text frame on the first page.
set myTextFrame4 to make text frame
set geometric bounds of myTextFrame4 to my myGetBounds(myDocument4, myPage4)
CHAPTER 3: DocumentsMaking an Adaptive Layout 45
set contents of myTextFrame4 to "This is guide based layoutrule sample doc."
set myItem4 to make rectangle
set geometric bounds of myItem4 to {20, 20, 70, 70}
make guide with properties {orientation:horizontal, location:"20p", guide
type:liquid}
end tell
end tell
tell application "Adobe InDesign CS6"
set myDocument5 to make document
set myPage5 to page 1 of myDocument5
-- Set layout rule to use master
tell myPage5
--Use master on the page as it resizes.
set layout rule to use master
--Create a text frame on the first page.
set myTextFrame5 to make text frame
set geometric bounds of myTextFrame5 to my myGetBounds(myDocument5, myPage5)
set contents of myTextFrame5 to "This is master page layoutrule sample doc."
set myItem5 to make rectangle
set geometric bounds of myItem5 to {20, 20, 70, 70}
end tell
end tell
Adding guides for a guide-based layout
The following example script shows how to add guide slices for guide-based layout rules. (For the
complete script, see AddGuides.)
tell application "Adobe InDesign CS6"
set myDocument to make document
set myPage to page 1 of myDocument
tell myPage
set layout rule to guide based
set myTextFrame to make text frame
--Set the bounds of the text frame.
set geometric bounds of myTextFrame to my myGetBounds(myDocument, myPage)
--Enter text in the text frame.
set contents of myTextFrame to "This is guide-based layoutrule sample doc."
set myItem to make rectangle
set geometric bounds of myItem to {20, 20, 70, 70}
end tell
tell myPage
make guide with properties {orientation:horizontal, location:"20p", guide
type:liquid}
end tell
end tell
Setting constraints for an object-based layout
The following example script shows how to set constraints for object-based layout rules. (For the complete
script, see SetConstraints.)
CHAPTER 3: DocumentsCollecting and Dropping Content 46
tell application "Adobe InDesign CS6"
set myDocument to make document
set myPage to page 1 of myDocument
tell myPage
set layout rule to object based
set myTextFrame to make text frame
--Set the bounds of the text frame.
set geometric bounds of myTextFrame to my myGetBounds(myDocument, myPage)
--Enter text in the text frame.
set contents of myTextFrame to "This is object-based layoutrule sample doc."
set myItem to make rectangle
set geometric bounds of myItem to {20, 20, 70, 70}
Create Alternate Layout takes a range of existing pages with content and automatically creates linked
copies of the content on a set of new pages within the same document. Use this when you need to create
unique layouts for different orientations and device classes. (For the complete script, see
CreateAlternateLayout.)
tell application "Adobe InDesign CS6"
set myDocument to make document
tell document preferences of myDocument
set facing pages to false
set pages per document to 1
set page width to 1024
set page height to 768
end tell
set myPage to page 1 of myDocument
tell myPage
set layout rule to object based
set myItem to make rectangle
set geometric bounds of myItem to {50, 50, 100, 100}
end tell
tell myDocument
create alternate layout spread items spreads
name "new layout"
width page height of document preferences
height page width of document preferences
ppi 1
layout rule preserve existing
with create text styles and link text stories
end tell
end tell
Collecting and Dropping Content
With Content Dropper, you can copy the content from a file designed for printing and paste it into another
document.
CHAPTER 3: DocumentsPrinting a Document 47
The following script shows how to collect content in a document using scripting. (For the complete script,
see ContentCollectorAndPlacer.)
--Invoke load with full parameters
tell content placer object 1
load page items myRectangle
with link page items, link stories, map styles and showing options
end tell
The following script shows how to place collected content into another document. (For the complete
script, see ContentCollectorAndPlacer.)
--Invoke Page.contentPlace with full parameters
tell myPage1
content place page items rectangles of myPage
with link page items, link stories, map styles and showing options
end tell
Printing a Document
The following script prints the active document using the current print preferences. (For the complete
script, see PrintDocument.)
tell application "Adobe InDesign CS6"
print active document
end tell
Printing using page ranges
To specify a page range to print, set the page range property of the document’s printpreferences
object before printing, as shown in the following script fragment (from the PrintPageRange tutorial script):
tell application "Adobe InDesign CS6"
set page range of print preferences to "1-3, 10"
print
end tell
Setting print preferences
The printpreferences object contains properties corresponding to the options in the panels of the Print
dialog. The following script shows how to set print preferences using scripting. (For the complete script,
see PrintPreferences.)
CHAPTER 3: DocumentsPrinting a Document 48
--PrintPreferences.as
--An InDesign CS6 AppleScript
--Sets the print preferences of the active document.
tell application "Adobe InDesign CS6"
--Get the bleed amounts from the document's bleed and add a bit.
tell document preferences of active document
set myX1Offset to document bleed inside or left offset + 3
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--we'll set our
--own print preferences.
--printer can be either a string (the name of the printer) or
--postscript file.
set printer to postscript file
--Here's 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 "Device Independent"
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
--Set the following property to true to print all printer's 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
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
CHAPTER 3: DocumentsExporting a Document as PDF 51
--Properties corresponding to the controls in the Advanced panel
--of the Print dialog.
----------------------------------------------------------------------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
Printing with printer presets
To print a document using a printer preset, include the printer preset in the print command.
tell application "Adobe InDesign CS6"
--The following line assumes that you have defined a print preset
--named "myPrintPreset".
print active document using "myPrintPreset"
end tell
Exporting a Document as PDF
InDesign scripting offers full control over the creation of PDF files from your page-layout documents.
Exporting to PDF
The following script exports the current document as PDF, using the current PDF export options. (For the
complete script, see ExportPDF.)
tell application "Adobe InDesign CS6"
tell active document
--You'll have to fill in a valid file path for your system.
export format PDF type to "yukino:test.pdf" without showing options
end tell
end tell
The following script fragment shows how to export to PDF using a PDF export preset. (For the complete
script, see ExportPDFWithPreset.)
tell application "Adobe InDesign CS6"
tell active document
--You'll have to fill in a valid file path for your system and
--a valid PDF export preset name.
export format PDF type to "yukino:test.pdf" using PDF export preset
"myTestPreset" without showing options
end tell
end tell
CHAPTER 3: DocumentsExporting a Document as PDF 52
Setting PDF export options
The following script sets the PDF export options before exporting. (For the complete script, see
ExportPDFWithOptions.)
tell application "Adobe InDesign CS6"
--Get the bleed amounts from the document's bleed.
tell document preferences of active document
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 option to do not include
--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 crop images to frames to true
set optimize PDF to true
CHAPTER 3: DocumentsExporting a Document as PDF 53
--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
--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
--You'll have to fill in a valid file path for your system.
export format PDF type to "yukino:test.pdf" without showing options
end tell
end tell
Exporting to grayscale PDF
An InDesign document that contains colors can be exported to a color PDF or to a grayscale PDF. You can
modify the script in the preceding “Setting PDF export options” on page 52
by changing the
tell PDF export preferences
set PDF color space to gray
end tell
(For a different script that creates a small document containing color and exports it to PDF in grayscale, see
GreyscalePDFforIDS.)
PDF color space option from unchanged color space to gray. For example:
section to export in grayscale
CHAPTER 3: DocumentsExporting a Document as PDF 54
Exporting a range of pages to PDF
The following script shows how to export a specified page range as PDF. (For the complete script, see
ExportPageRangeAsPDF.)
--Assumes you have a document open, and that that document
--contains at least 12 pages.
tell application "Adobe InDesign CS6"
tell PDF export preferences
--page range can be either all pages or a page range string
--(just as you would enter it in the Print or Export PDF dialog box).
set page range to "1, 3-6, 7, 9-11, 12"
end tell
tell active document
--You'll have to fill in a valid file path for your system and
--a valid PDF export preset name.
export format PDF type to "yukino:test.pdf" using
PDF export preset "myTestPreset" without showing options
end tell
end tell
Exporting individual pages to PDF
The following script exports each page from a document as an individual PDF file. (For the complete script,
see ExportEachPageAsPDF.)
display dialog "Please open a document and try again."
end if
end tell
on myChooseFolder()
set myFolder to choose folder with prompt "Choose a Folder"
--Get the folder name (it'll be returned as a Unicode string)
set myFolder to myFolder as string
--Unofficial technique for changing Unicode folder name to plain text string.
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 CS6"
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
CHAPTER 3: DocumentsExporting a Document as PDF 55
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 don't 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--that's 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 AppleScript's text item delimiters to myFindString
set myTextList to every text item of (myString as text)
set AppleScript's text item delimiters to myChangeString
set myString to myTextList as string
set AppleScript's text item delimiters to ""
return myString
end myReplace
Exporting PDF with interactive features
The following script exports a document with interactive features as a PDF. (For the complete script, see
ExportInteractivePDF.)
--Given a document "myDocument" containing at least two spreads...
repeat with myCounter from 1 to (count spreads of myDocument)
set page transition type of spread myCounter of myDocument to wipe transition
set page transition direction of spread myCounter of myDocument to left to right
set page transition duration of spread myCounter of myDocument to medium
end repeat
set myDesktopFolder to path to desktop as string
set myFile to myDesktopFolder & "InteractivePDF.pdf"
tell myDocument
export format interactive PDF to myFile without showing options
end tell
CHAPTER 3: DocumentsExporting a Document as PDF 56
Exporting as a PDF form
To create a PDF that contains form fields, you can either save the InDesign document as PDF, then open it
in Acrobat and apply form fields, or apply text fields, radio buttons, signature fields, and so on directly in
InDesign and export the document to PDF as a form with no additional Acrobat editing required.
The following script applies form elements to an InDesign document and exports the document as a PDF
form. (For the complete script, see ExportInteractivePDFForm.)
tell page 1 of myDocument
--Create a textframe as firstname label
set myTextFrame to make text frame with properties
--Create a button for submit
set submitButton to make button with properties
{geometric:{45, 15, 35, 35}, name:"Submit"}
end tell
tell state 1 of submitButton
set myRightArrow1 to make polygon with properties {fill color:color "Green" of
myDocument, stroke color:"None"}
set entire path of path 1 of myRightArrow1 to {{15, 35}, {35, 40}, {15, 45}}
end tell
--Add the Rollover state.
tell submitButton
set myRolloverState1 to make state
end tell
tell myRolloverState1
set myRolloverArrow1 to make polygon with properties {fill color:color "Green" of
myDocument, stroke color:"None"}
set entire path of path 1 of myRolloverArrow1 to {{15, 35}, {35, 40}, {15, 45}}
--Add a shadow to the polygon in the Rollover state.
end tell
tell drop shadow settings of fill transparency settings of myRolloverArrow1
set mode to drop
set angle to 90
set x offset to 0
CHAPTER 3: DocumentsExporting a Document as PDF 57
set y offset to 0
set size to 6
end tell
tell submitButton
set myClickState1 to make state
end tell
tell myClickState1
set myClickArrow1 to make polygon with properties {fill color:color "Blue" of
myDocument, stroke color:"None"}
set entire path of path 1 of myClickArrow1 to {{15, 35}, {35, 40}, {15, 45}}
end tell
--Set the behavior for the button.
tell submitButton
set submitForm to make submit form behaviors with properties {behavior event:mouse
up}
end tell
tell page 1 of myDocument
--Create a button for print
set printButton to make button with properties {geometric:{45, 15, 35, 35},
name:"Submit"}
end tell
tell state 1 of printButton
set myRightArrow2 to make polygon with properties {fill color:color "Red" of
myDocument, stroke color:"None"}
set entire path of path 1 of myRightArrow2 to {{40, 35}, {60, 40}, {40, 45}}
end tell
--Add the Rollover state.
tell printButton
set myRolloverState2 to make state
end tell
tell myRolloverState2
set myRolloverArrow2 to make polygon with properties {fill color:color "Red" of
myDocument, stroke color:"None"}
set entire path of path 1 of myRolloverArrow2 to {{40, 35}, {60, 40}, {40, 45}}
--Add a shadow to the polygon in the Rollover state.
end tell
tell drop shadow settings of fill transparency settings of myRolloverArrow2
set mode to drop
set angle to 90
set x offset to 0
set y offset to 0
set size to 6
end tell
tell printButton
set myClickState2 to make state
end tell
CHAPTER 3: DocumentsExporting Pages as EPS 58
tell myClickState2
set myClickArrow2 to make polygon with properties {fill color:color "Blue" of
myDocument, stroke color:"None"}
set entire path of path 1 of myClickArrow2 to {{40, 35}, {60, 40}, {40, 45}}
end tell
--Set the behavior for the button.
tell printButton
set PrintForm to make print form behaviors with properties {behavior event:mouse up}
end tell
--Export the document to PDF.
set myDesktopFolder to path to desktop as string
set myFile to myDesktopFolder & "SubmitForm.pdf"
tell myDocument
export format interactive PDF to myFile without showing options
end tell
Exporting Pages as EPS
When you export a document as EPS, InDesign saves each page of the file as a separate EPS graphic (an
EPS, by definition, can contain only a single page). If you export more than a single page, InDesign
appends the index of the page to the filename. The index of the page in the document is not necessarily
the name of the page (as defined by the section options for the section containing the page).
Exporting all pages to EPS
The following script exports the pages of the active document to one or more EPS files. (For the complete
script, see ExportAsEPS.)
tell application "Adobe InDesign CS6"
set page range of EPS export preferences to all pages
tell active document
--You'll have to fill in a valid file name for your system.
--Files will be named "myFile_01.eps", "myFile_02.eps", and so on.
set myFileName to "yukino:myFile.eps"
export format EPS type to myFileName without showing options
end tell
end tell
Exporting a range of pages to EPS
To control which pages are exported as EPS, set the page range property of the EPS export preferences to
a page-range string containing the page or pages you want to export, before exporting. (For the complete
script, see ExportPageRangeAsEPS.)
CHAPTER 3: DocumentsExporting Pages as EPS 59
--Assumes you have a document open, and that that document
--contains at least 12 pages.
tell application "Adobe InDesign CS6"
tell EPS export preferences
--page range can be either all pages or a page range string
--(just as you would enter it in the Print or Export EPS dialog box).
set page range to "1, 3-6, 7, 9-11, 12"
end tell
tell active document
--You'll have to fill in a valid file path for your system.
export format EPS type to "yukino:test.eps" without showing options
end tell
end tell
Exporting as EPS with file naming
The following script exports each page as an EPS, but it offers more control over file naming than the
earlier example. (For the complete script, see ExportEachPageAsEPS.)
display dialog "Please open a document and try again."
end if
end tell
on myChooseFolder()
set myFolder to choose folder with prompt "Choose a Folder"
--Get the folder name (it'll be returned as a Unicode string)
set myFolder to myFolder as string
--Unofficial technique for changing Unicode folder name to plain text string.
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 CS6"
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)
CHAPTER 3: DocumentsExporting to EPub 60
--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 don't 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 AppleScript's text item delimiters to myFindString
set myTextList to every text item of (myString as text)
set AppleScript's text item delimiters to myChangeString
set myString to myTextList as string
set AppleScript's text item delimiters to ""
return myString
end myReplace
Exporting to EPub
InDesign scripting offers full control over the creation of EPub files from your page-layout documents.
Exporting the current document
The following script exports the current document as EPub, using default options. (For the complete script,
see ExportEPub.)
set myDocument to document 1
tell myDocument
export format EPUB to myFile without showing options
end tell
To give the user more control over the the creation of EPub files, specify true for the third parameter. This
opens the EPub export options dialog.
Setting EPub export options
The following script sets the EPub export options before exporting. (For the complete script, see
ExportEPubWithOptions.)
CHAPTER 3: DocumentsExporting to EPub 61
tell myDocument
tell EPub export preferences
--Apply image alignment to anchored object settings.
set apply image alignment to anchored object settings to false
--The unit of space.
set space unit to css em
--The unit of margin.
set margin unit to css em
--Bottom margin of the epub.
set bottom margin to 5
--Left margin of the epub.
set left margin to 5
--Right margin of the epub.
set right margin to 5
--Top margin of the epub.
set top margin to 5
--If true, break InDesign document into smaller pieces when generating epub.
set break document to true
-- The name of paragraph style to break InDesign document.
set paragraph style name to ""
--The buttet export option.
set bullet export option to as text
set CSS export option to embedded CSS
set custom image size option to size relative to page width
set embed font to true
set epub cover to first page
--This will take effect only when epub cover is set to external image.
--set cover image file to "cover.jpg"
set epub publisher to "Adobe Devtech"
--The export order.
set export order to layout order
--If true, output footnote immediately after its paragraph.
set footnote follow paragraph to false
--If true, export epub in XHTML format. Otherwise, in DTBook format.
set format to true
set GIF options interlaced to true
set GIF options palette to windows palette
--The epub unique identifier, like ISBN.
set id to "123"
--Ignore object level image conversion settings.
set ignore object conversion settings to true
--Alignment applied to images.
set image alignment to align center
--The file format to use for converted images.
set image conversion to automatic
CHAPTER 3: DocumentsExporting to EPub 62
set image export resolution to ppi 150
--Image page break settings to be used with objects.
set image page break to page break after
--Space After applied to images.
set image space after to 2
--Space Before applied to images.
set image space before to 2
--If true, include CSS definition.
set include CSS definition to true
--If true, output document metadata into epub.
set include document metadata to true
set JPEG options format to baseline encoding
set JPEG options quality to high
--The PNG compression level.
set level to 5
set numbered list export option to as text
--If true, format image based on layout appearence.
set preserve layout appearence to true
--If true, output local style override.
set preserve local override to true
set strip soft return to true
--If true, image page break settings will be used in objects.
set use image page break to true
--Use InDesign TOC style to generate epub TOC.
set use toc style to true
set view document after export to false
end tell
export format EPUB to myFile without showing options
end tell
4
Chapter Update Status
CS6Unchanged
Working with Layers
InDesign’s layers are the key to controlling the stacking order of objects in your layout. You can think of
layers as transparent planes stacked on top of each other. You also can use layers as an organizational tool,
putting one type of content on a given layer or set of layers.
A document can contain one or more layers, and each document includes at least one layer. Layers are
document wide, not bound to specific pages or spreads.
This chapter covers scripting techniques related to layers in an InDesign layout and discusses common
operations involving layers.
Understanding the Layer Object Model
The following figure shows the layer object model. Note the following about the diagram:
It focuses on the location of a layer and its contents in the context of the object hierarchy of a
document; it does not attempt to show all the other ways a script might work with the content of a
layer (e.g., you can get a reference to a text-frame object from a story, text object, page, or spread, in
addition to finding it inside a layer object).
It uses the JavaScript form of the object names; however, the object hierarchy is the same in all
scripting languages.
The basic properties of a layer are shown in the column at the left of the figure; the objects that may
be contained by the layer object, at the right.
It is important to note the distinction between the page-items collection and the all page items
collection. The former is a collection containing only the top-level page items in a layer. If a page item is
inside a group, for example, it will not appear in the
collection is a flattened collection of all page items assigned to the layer, regardless of their location
items
in the object hierarchy. A page item inside a group on the layer would appear in the
collection.
Similarly, the
regardless of their location in the object hierarchy.
all graphics property contains all graphics stored in page items assigned to the layer,
page items collection. In contrast, the all page
all page items
63
CHAPTER 4: Working with LayersScripting Layers 64
Scripting Layers
In InDesign’s user interface, you add, delete, rearrange, duplicate, and merge layers using the Layers panel.
You also can change the layer to which a selected page item is assigned by dragging and dropping the
layer proxy in the Layers panel. (For more on assigning objects to a layer, see the InDesign online help.)
This section shows how to accomplish these tasks using InDesign scripting.
Creating layers
The following script fragment shows how to create a new layer. (For the complete script, see AddLayer.)
--Given a document "myDocument"...
tell myDocument
set myLayer to make layer
end tell
When you create a new layer, the layer appears above all other layers in the document.
CHAPTER 4: Working with LayersScripting Layers 65
Referring to layers
InDesign scripting offers several ways to refer to a layer object. This section describes the most common
ways to refer to layers.
Getting the active layer
The active layer is the layer on which new objects are created. You can get the active layer using scripting,
as shown in the following script fragment. (For the complete script, see ActiveLayer.)
--Given a document "myDocument"...
tell myDocument
set myLayer to active layer
end tell
Referring to layers by layer index
You can get a reference to a layer using the index of the layer in the layers collection of a document. The
script fragment below uses the layer index to iterate through layers. (For the complete script, see
HideOtherLayers.)
--Given a document "myDocument"...
tell myDocument
set myTargetLayer to active layer
set myLayerName to name of myTargetLayer
repeat with myCounter from 1 to (count layers)
--If the layer is not the target layer, hide it.
set myName to name of layer myCounter
if myName is not equal to myLayerName then
set visible of layer myCounter of myDocument to false
end if
end repeat
end tell
Note that you can use negative numbers to refer to the layers in the layers collection of a document. Layer
-1 refers to the last (bottom) layer in the collection.
Referring to layers by layer name
You also can get a reference to a layer using the name of the layer, as shown in the following script
fragment. (For the complete script, see LayerName.)
set myLayer to layer "Text Layer" of document 1
CHAPTER 4: Working with LayersScripting Layers 66
Deleting layers
Use the delete method to delete a layer from a specific document, as shown in the following script
fragment. (For the complete script, see DeleteLayer.) You cannot delete the last remaining layer in a
document.
--Given a document "myDocument" containing a layer named "Delete This Layer"...
set myLayer to layer "Delete This Layer" of myDocument
tell myLayer
delete
end tell
Moving layers
Use the move method to change the stacking order of layers in a document, as shown in the following
script fragment. (For the complete script, see MoveLayer.)
--Given a document "myDocument" containing at least two layers...
set myLayerA to layer 1 of myDocument
set myLayerB to layer 2 of myDocument
tell myLayer1
move to after myLayer2
end tell
Duplicating layers
Use the duplicate method to create a copy of a layer, as shown in the following script fragment. (For the
complete script, see DuplicateLayer.)
-Given a layer "myLayer"...
tell myLayer
set myNewLayer to duplicate
end tell
Merging layers
The following script fragment shows how to merge two or more layers, including the page items assigned
to them, into a single layer. (For the complete script, see MergeLayers.)
--Given the layers "myLayer1" and "myLayer2"...
tell myLayer1
merge with myLayer2
end tell
Assigning page items to layers
You can assign a page item to a layer by either referring to the layer when you create the page item or
setting the
assign a page item to a layer using both techniques. (For the complete script, see
AssignPageItemsToLayers.)
item layer property of an existing page item. The following script fragment shows how to
CHAPTER 4: Working with LayersScripting Layers 67
--Given a reference to a page "myPage," and a document "myDocument"...
tell myPage
--Create a text frame on a layer named "TextFrames"
set myTextFrame to make text frame with properties
set item layer of myRectangle to layer "Rectangles" of myDocument
--Create a series of ovals.
repeat with myCounter from 72 to 172 by 10
make oval with properties {geometric bounds:{216, myCounter, 226,
myCounter + 10}}
end repeat
--Move all of the ovals on the page to a specific layer.
repeat with myCounter from 1 to (count ovals)
set item layer of oval myCounter to layer "Ovals" of myDocument
end repeat
end tell
Setting layer properties
Layer properties control the layer name, color, visibility, and other attributes of a layer. This section shows
how to work with layer properties.
Setting basic layer properties
Basic layer properties include the name of the layer, the highlight color of the layer, the visibility of the
layer, and whether text objects on the layer ignore text-wrap settings. The following script fragment shows
how to set these basic properties of a layer. (For the complete script, see BasicLayerProperties.)
--Given a document "myDocument"...
tell myDocument
set myLayer to make layer
set name of myLayer to "myLayer"
set layer color of myLayer to charcoal
set ignore wrap of myLayer to false
set visible of myLayer to true
end tell
CHAPTER 4: Working with LayersScripting Layers 68
Working with layer guides
Guides can be assigned to a specific layer, just like page items. You can choose to show or hide the guides
for a layer, and you can lock or unlock the guides on a layer. The following script fragment shows how to
work with the guides on a layer. (For the complete script, see LayerGuides.)
--Given a document "myDocument" and a page "myPage" containing at least one guide...
tell myDocument
set myLayer to make layer
--Move all of the guides on the page to the new layer.
tell myPage
repeat with myCounter from (count guides) to 1 by -1
set item layer of guide myCounter to myLayer
end repeat
end tell
set lock guides of myLayer to true
set show guides of myLayer to true
end tell
Controlling layer printing and visibility
You can control the printing and visibility of objects on a layer, as shown in the following script fragment.
(For the complete script, see LayerControl.)
--Given a document "myDocument" containing layers named "Background,"
--"Language A,", "Language B," and "Language C," export the "Background"
--layer and each "Language" layer to PDF as separate PDF files...
set myList to {"A", "B", "C"}
set myPath to path to desktop as string
tell myDocument
repeat with myCounter from 1 to 3
set myVersion to "Language " & item myCounter of myList
repeat with myLayerCounter from 1 to (count layers)
if name of layer myLayerCounter is equal to myVersion or
name of layer myLayerCounter is equal to "Background" then
set visible of layer myLayerCounter to true
set printable of layer myLayerCounter to true
else
set visible of layer myLayerCounter to false
set printable of layer myLayerCounter to false
end if
end repeat
set myFilePath to myPath & myVersion & ".pdf"
export to myFilePath format PDF type
end repeat
end tell
CHAPTER 4: Working with LayersScripting Layers 69
Locking layers
Layers can be locked, which means the page items on the layers cannot be edited. The following script
fragment shows how to lock and unlock layers. (For the complete script, see LockLayersBelow.)
--Given a document "myDocument"...
tell myDocument
set myLayer to active layer
repeat with myCounter from ((index of myLayer) + 1) to (count layers)
set locked of layer myCounter to true
end repeat
end tell
5
Chapter Update Status
CS6UpdatedAdded section “Fitting text frames to content” on page 89.
Tex t a nd Type
Entering, editing, and formatting text are the tasks that make up the bulk of the time spent working on
most InDesign documents. Because of this, automating text and type operations can result in large
productivity gains.
This chapter shows how to script the most common operations involving text and type. The sample scripts
in this chapter are presented in order of complexity, starting with very simple scripts and building toward
more complex operations.
We assume that you have already read Adobe InDesign Scripting Tutorial and know how to create, install,
and run a script. We also assume that you have some knowledge of working with text in InDesign and
understand basic typesetting terms.
Entering and Importing Text
This section covers the process of getting text into your InDesign documents. Just as you can type text into
text frames and place text files using the InDesign user interface, you can create text frames, insert text
into a story, or place text files on pages using scripting.
Creating a text frame
The following script creates a text frame, sets the bounds (size) of the frame, then enters text in the frame
(for the complete script, see the MakeTextFrame tutorial script):
--Given a document "myDocument"...
set myDocument to document 1
set myPage to page 1 of myDocument
tell myPage
set myTextFrame to make text frame
--Set the bounds of the text frame.
set geometric bounds of myTextFrame to {72, 72, 288, 288}
--Enter text in the text frame.
set contents of myTextFrame to "This is some example text."
--Note that you could also use a properties record
--to set the bounds and contents of the text in a
--single line:
--set myTextFrame to make text frame with properties{geometric bounds:{72, 72, 288,
288}, contents:"This is some example text."}
end tell
The following script shows how to create a text frame that is the size of the area defined by the page
margins.
other examples in this chapter. (For the complete script, see MakeTextFrameWithinMargins.)
myGetBounds is a useful function that you can add to your own scripts, and it appears in many
70
CHAPTER 5: Text and TypeEntering and Importing Text 71
--Given a document "myDocument"
set myPage to page 1 of myDocument
tell myPage
set myTextFrame to make text frame
--Set the bounds of the text frame.
set geometric bounds of myTextFrame to my myGetBounds(myDocument, myPage)
end tell
The following script fragment shows the myGetBounds handler.
on myGetBounds(myDocument, myPage)
tell application "Adobe InDesign CS6"
tell document preferences of myDocument
set myPageWidth to page width
set myPageHeight to page height
end tell
tell margin preferences of myPage
if side of myPage is left hand then
set myX2 to left
set myX1 to right
else
set myX1 to left
set myX2 to right
end if
set myY1 to top
set myY2 to bottom
end tell
set myX2 to myPageWidth - myX2
set myY2 to myPageHeight - myY2
return {myY1, myX1, myY2, myX2}
end tell
end myGetBounds
Adding text
To add text to a story, use the contents property of the insertion point at the location where you want to
insert the text. The following sample script uses this technique to add text at the end of a story (for the
complete script, see AddText):
--Given a document "myDocument" with a text frame on page 1
set myTextFrame to text frame 1 of page 1 of myDocument
--Add text to the end of the text frame. To do this,
--We'll use the last insertion point in the story.
set myNewText to "This is a new paragraph of example text."
tell parent story of myTextFrame
set contents of insertion point -1 to return & myNewText
end tell
Stories and text frames
All text in an InDesign layout is part of a story, and every story can contain one or more text frames.
Creating a text frame creates a story, and stories can contain multiple text frames.
In the preceding script, we added text at the end of the parent story rather than at the end of the text
frame. This is because the end of the text frame might not be the end of the story; that depends on the
length and formatting of the text. By adding the text to the end of the parent story, we can guarantee that
the text is added, regardless of the composition of the text in the text frame.
CHAPTER 5: Text and TypeEntering and Importing Text 72
You always can get a reference to the story using the parenttext frame property of a text frame. It can be
useful to work with the text of a story instead of the text of a text frame; the following script demonstrates
the difference. The alerts shows that the text frame does not contain the overset text, but the story does
(for the complete script, see StoryAndTextFrame).
--Given a document "myDocument" with a text frame on page 1...
set myTextFrame to text frame 1 of myDocument
--Now add text beyond the end of the text frame.
set myString to return & "This is some overset text"
tell insertion point -1 of myTextFrame to set contents to myString
set myString to contents of text 1 of myTextFrame
display dialog ("The last paragraph in this dialog should be \"This is some overset
text\". Is it?" & return & myString)
set myString to contents of parent story of myTextFrame
display dialog ("The last paragraph in this alert should be \"This is some overset
text\". Is it?" & return & myString)
For more on understanding the relationships between text objects in an InDesign document, see
“Understanding Text Objects” on page 80
.
Replacing text
The following script replaces a word with a phrase by changing the contents of the appropriate object (for
the complete script, see ReplaceWord):
--Given a document "myDocument" with a text frame on page 1...
set myTextFrame to text frame 1 of page 1 of myDocument
--Replace the third word with the phrase "a little bit of".
tell word 3 of parent story of myTextFrame
set contents to "a little bit of"
end tell
The following script replaces the text in a paragraph (for the complete script, see ReplaceText):
--Given a document "myDocument" with a text frame on page 1...
set myTextFrame to text frame 1 of page 1 of myDocument
--Replace the text in the second paragraph without
--replacing the return character at the end of the paragraph
--(character -2 is the character before the return).
tell parent story of myTextFrame
set myText to object reference of text from character 1 to character -2 of paragraph
2
set contents of myText to "This text replaces the text in paragraph 2."
end tell
end tell
In the preceding script, we excluded the return character because deleting the return might change the
paragraph style applied to the paragraph. To do this, we supplied a character range—from the first
character of the paragraph to the last character before the return character that ends the paragraph.
Inserting special characters
Because the Script Editor supports Unicode, you can simply enter Unicode characters in text strings that
you send to InDesign. The following script shows several ways to enter special characters. (We omitted the
myGetBounds function from this listing; you can find it in “Creating a text frame” on page 70” or in the
SpecialCharacters tutorial script.)
CHAPTER 5: Text and TypePlacing Text and Setting Text-Import Preferences 73
--Given a document "myDocument" containing a story...
set myStory to story 1 of myDocument
--Entering special characters by their Unicode glyph ID value:
set contents of insertion point -1 of myStory to "Not equal to: <2260>" & return
set contents of insertion point -1 of myStory to "Square root: <221A>" & return
set contents of insertion point -1 of myStory to "Square root: <00B6>" & return
--Entering special characters by their enumerations:
set contents of insertion point -1 of myStory to "Automatic page number marker: "
set contents of insertion point -1 of myStory to auto page number
set contents of insertion point -1 of myStory to return & "Section symbol: "
set contents of insertion point -1 of myStory to section symbol
set contents of insertion point -1 of myStory to return & "En dash: "
set contents of insertion point -1 of myStory to En dash
set contents of insertion point -1 of myStory to return
The easiest way to find the Unicode ID for a character is to use InDesign’s Glyphs palette: move the cursor
over a character in the palette, and InDesign displays its Unicode value. To learn more about Unicode, visit
http://www.unicode.org
.
Placing Text and Setting Text-Import Preferences
In addition to entering text strings, you can place text files created using word processors and text editors.
The following script shows how to place a text file on a document page (for the complete script, see
PlaceTextFile):
--Given a document "myDocument"
set myPage to page 1 of myDocument
--Get the top and left margins to use as a place point.
tell margin preferences of myPage
set myX to left
set myY to right
end tell
--Autoflow a text file on the current page.
--Parameters for the place command of a page:
--file as file or string
--[place point as list {x, y}
--[destination layer as layer object or string]
--[showing options as Boolean (default is false)]
--[autoflowing as Boolean (default is false)]
--You'll have to fill in a valid file path on your system.
tell myPage
--Note that if the PlacePoint parameter is inside a column, only the vertical (y)
--coordinate will be honored--the text frame will expand horizontally to fit the
column.
set myStory to place alias "Macintosh HD:scripting:test.txt" place point {myX, myY}
autoflowing yes without showing options
end tell
The following script shows how to place a text file in an existing text frame. (We omitted the myGetBounds
function from this listing; you can find it in “Creating a text frame” on page 70
,” or see the
PlaceTextFileInFrame tutorial script.)
CHAPTER 5: Text and TypePlacing Text and Setting Text-Import Preferences 74
--Given a document "myDocument" with a text frame on page 1...
set myTextFrame to text frame 1 of page 1 of myDocument
tell insertion point -1 of myTextFrame
--You'll need to fill in a valid file path for your system.
place "yukino:test.txt" without showing options
end tell
The following script shows how to insert a text file at a specific location in text. (We omitted the
myGetBounds function from this listing; you can find it in “Creating a text frame” on page 70,” o r s ee t he
InsertTextFile tutorial script.)
--Given a document "myDocument" with a text frame on page 1...
--Place a text file at the end of the text.
set myTextFrame to text frame 1 of page 1 of myDocument
tell insertion point -1 of parent story of myTextFrame
--You'll need to fill in a valid file path for your system.
place "yukino:test.txt" without showing options
end tell
To specify the import options for the specific type of text file you are placing, use the corresponding
import-preferences object. The following script shows how to set text-import preferences (for the
complete script, see TextImportPreferences). The comments in the script show the possible values for each
property.
tell text import preferences
--Options for character set:
set character set to UTF8
set convert spaces into tabs to true
set spaces into tabs count to 3
--The dictionary property can take many values, such as French, Italian.
set dictionary to "English: USA"
--platform options:
--macintosh
--pc
set platform to macintosh
set strip returns between lines to true
set strip returns between paragraphs to true
set use typographers quotes to true
end tell
The following script shows how to set tagged text import preferences (for the complete script, see
TaggedTextImportPreferences):
tell tagged text import preferences
set remove text formatting to false
--Options for style conflict are:
--publication definition
--tag file definition
set style conflict to publication definition
set use typographers quotes to true
end tell
The following script shows how to set Word and RTF import preferences (for the complete script, see
WordRTFImportPreferences):
CHAPTER 5: Text and TypePlacing Text and Setting Text-Import Preferences 75
tell word RTF import preferences
--convert page breaks property can be:
--column break
--none
--page break
set convert page breaks to none
--convert tables to property can be:
--unformatted tabbed text
--unformatted table
set convert tables to to Unformatted Table
set import endnotes to true
set import footnotes to true
set import index to true
set import TOC to true
set import unused styles to false
set preserve graphics to false
set preserve local overrides to false
set preserve track changes to false
set remove formatting to false
--resolve character style clash and resolve paragraph style clash properties can be:
--resolve clash auto rename
--resolve clash use existing
--resolve clash use new
set resolve character style clash to resolve clash use existing
set resolve paragraph style clash to resolve clash use existing
set use typographers quotes to true
end tell
The following script shows how to set Excel import preferences (for the complete script, see
ExcelImportPreferences):
tell application "Adobe InDesign CS6"
tell excel import preferences
--alignment Style property can be:
--center align
--left align
--right align
--spreadsheet
set alignment style to spreadsheet
set decimal places to 4
set preserve graphics to false
--Enter the range you want to import as "start cell:end cell".
set range name to "A1:B16"
set sheet index to 1
set sheet name to "pathpoints"
set show hidden cells to false
--table formatting property can be:
--excel formatted table
--excel unformatted tabbed text
--excel unformatted table
set table formatting to excel formatted table
set use typographers quotes to true
set view name to ""
end tell
end tell
CHAPTER 5: Text and TypeExporting Text and Setting Text-Export Preferences 76
Exporting Text and Setting Text-Export Preferences
The following script shows how to export text from an InDesign document. Note that you must use text or
story objects to export into text file formats; you cannot export all text in a document in one operation.
(We omitted the
page 70,” or see the ExportTextFile tutorial script.)
tell application "Adobe InDesign CS6"
set myDocument to active document
set myPage to page 1 of myDocument
tell myPage
set myTextFrame to make text frame with properties {geometric bounds:
my myGetBounds(myDocument, myPage), contents:placeholder text}
end tell
--Text export method parameters:
--format as enumeration
--to alias as string
--showing options boolean
--version comments string
--force save boolean
--Format parameter can be:
--InCopy CS Document
--InCopy Document
--rtf
--tagged text
--text type
--Export the story as text. You'll have to fill in a valid file path on your system.
tell parent story of myTextFrame
export to "yukino:test.txt" format text type
end tell
end tell
myGetBounds function from this listing; you can find it in “Creating a text frame” on
The following example shows how to export a specific range of text. (We omitted the myGetBounds
function from this listing; you can find it in “Creating a text frame” on page 70
,” or see the ExportTextRange
tutorial script.)
--Given a document with a text frame on page 1...
set myTextFrame to text frame 1 of page 1 of active document
set myStory to parent story of myTextFrame
set myStartCharacter to index of character 1 of paragraph 1 of myStory
set myEndCharacter to the index of last character of paragraph 1 of myStory
set myText to object reference of text from character myStartCharacter to character
myEndCharacter of myStory
--Export the text range. You'll have to fill in a valid file path on your system.
tell myText to export to "Macintosh HD:scripting:test.txt" format text type
To specify the export options for the specific type of text file you’re exporting, use the corresponding
export preferences object. The following script sets text-export preferences (for the complete script, see
TextExportPreferences):
CHAPTER 5: Text and TypeExporting Text and Setting Text-Export Preferences 77
tell text export preferences
--Options for character set:
--UTF8
--UTF16
--platform
set character set to UTF8
--platform options:
--macintosh
--pc
set platform to macintosh
end tell
The following script sets tagged text export preferences (for the complete script, see
TaggedTextExportPreferences):
tell tagged text export preferences
--Options for character set:
--ansi
--ascii
--gb18030
--ksc5601
--shiftJIS
--unicode
set character set to unicode
--tag form options:
--abbreviated
--verbose
set tag form to verbose
end tell
You cannot export all text in a document in one step. Instead, you need to either combine the text in the
document into a single story and then export that story, or combine the text files by reading and writing
files via scripting. The following script demonstrates the former approach. (We omitted the
function from this listing; you can find it in “Creating a text frame” on page 70
,” or see the ExportAllText
myGetBounds
tutorial script.) For any format other than text only, the latter method can become quite complex.
tell application "Adobe InDesign CS6"
if (count documents) > 0 then
set myDocument to active document
if (count stories of myDocument) > 0 then
my myExportAllText(name of myDocument)
end if
end if
end tell
Here is the ExportAllText handler referred to in the preceding fragment:
CHAPTER 5: Text and TypeExporting Text and Setting Text-Export Preferences 78
on myExportAllText(myDocumentName)
tell application "Adobe InDesign CS6"
--File name for the exported text. Fill in a valid file path on your system.
set myFileName to "Adobe:test.txt"
--If you want to add a separator line between stories,
--set myAddSeparator to true.
set myAddSeparator to true
set myNewDocument to make document
set myDocument to document myDocumentName
tell page 1 of myNewDocument
set myTextFrame to make text frame with properties
{geometric bounds:my myGetBounds(myNewDocument, page 1 of myNewDocument)}
set myNewStory to parent story of myTextFrame
repeat with myCounter from 1 to (count stories in myDocument)
set myStory to story myCounter of myDocument
--Duplicate the text of the story to the end of the temporary story.
tell text 1 of myStory
duplicate to after insertion point -1 of story 1 of myNewDocument
end tell
--If the imported text did not end with a return, enter a return
--to keep the stories from running together.
if myCounter is not equal to (count stories of myDocument) then
if contents of character -1 of myNewStory is not return then
set contents of insertion point -1 of myNewStory to return
if myAddSeparator is true then
set contents of insertion point -1 of myNewStory to
"----------------------------------------" & return
end if
end if
end if
end repeat
tell myNewStory
export to myFileName format text type
end tell
close myNewDocument saving no
end tell
end tell
end myExportAllText
Do not assume that you are limited to exporting text using existing export filters. Because AppleScript can
write text files to disk, you can have your script traverse the text in a document and export it in any order
you like, using whatever text mark-up scheme you prefer. Here is a very simple example that shows how to
export InDesign text as HTML. (We omitted the
“Creating a text frame” on page 70
tell application "Adobe InDesign CS6"
--Use the myStyleToTagMapping array to set up your paragraph style to tag mapping.
set myStyleToTagMapping to {}
--For each style to tag mapping, add a new item to the array.
copy {"body_text", "p"} to end of myStyleToTagMapping
copy {"heading1", "h1"} to end of myStyleToTagMapping
copy {"heading2", "h3"} to end of myStyleToTagMapping
copy {"heading3", "h3"} to end of myStyleToTagMapping
--End of style to tag mapping.
if (count documents) is not equal to 0 then
set myDocument to document 1
if (count stories of myDocument) is not equal to 0 then
--Open a new text file.
set myTextFile to choose file name with prompt "Save HTML As"
--Iterate through the stories.
,” or see the ExportHTML tutorial script.)
myGetBounds function from this listing; you can find it in
CHAPTER 5: Text and TypeExporting Text and Setting Text-Export Preferences 79
repeat with myCounter from 1 to (count stories of myDocument)
set myStory to story myCounter of myDocument
repeat with myParagraphCounter from 1 to (count paragraphs of myStory)
set myParagraph to object reference of paragraph myParagraphCounter
of myStory
if (count tables of myParagraph) is 0 then
--If the paragraph is a simple paragraph--no tables,
--no local formatting--then simply export the text of the
--pararaph with the appropriate tag.
if (count text style ranges of myParagraph) is 1 then
set myTag to my myFindTag(name of applied paragraph style
of myParagraph, myStyleToTagMapping)
--If the tag comes back empty, map it to the
--basic paragraph tag.
if myTag = "" then
set myTag to "p"
end if
set myStartTag to "<" & myTag & ">"
set myEndTag to "</" & myTag & ">"
--If the paragraph is not the last paragraph in the story,
--omit the return character.
if the contents of character -1 of myParagraph is return then
set myText to object reference of text from character 1
to character -2 of myParagraph
set myString to contents of myText
else
set myString to contents of myParagraph
end if
--Write the text of the paragraph to the text file.
if myParagraphCounter = 1 then
set myAppendData to false
else
set myAppendData to true
end if
my myWriteToFile(myStartTag & myString & myEndTag & return,
myTextFile, myAppendData)
else
--Handle text style range export by iterating through
--the text style ranges in the paragraph.
set myTextStyleRanges to text style ranges of myParagraph
repeat with myRangeCounter from 1 to (count text style ranges
of myParagraph)
set myTextStyleRange to object reference of text style
range myRangeCounter of myParagraph
if character -1 of myTextStyleRange is return then
set myStartCharacter to index of character 1 of
myTextStyleRange
set myEndCharacter to index of character -2 of
myTextStyleRange
set myText to object reference of text from character
myStartCharacter to character myEndCharacter of myStory
set myString to contents of myText
else
set myString to contents of myTextStyleRange
end if
if font style of myTextStyleRange is "Bold" then
set myString to "<b>" & myString & "</b>"
else if font style of myTextStyleRange is "Italic" then
set myString to "<i>" & myString & "</i>"
end if
CHAPTER 5: Text and TypeUnderstanding Text Objects 80
my myWriteToFile(myString, myTextFile, true)
end repeat
my myWriteToFile(return, myTextFile, true)
end if
else
--Handle table export (assumes that there is only
--one table per paragraph,
--and that the table is in the paragraph by itself).
set myTable to table 1 of myParagraph
my myWriteToFile("<table border = 1>", myTextFile, true)
repeat with myRowCounter from 1 to (count rows of myTable)
my myWriteToFile("<tr>", myTextFile, true)
repeat with myColumnCounter from 1 to
(count columns of myTable)
if myRowCounter = 1 then
set myString to "<th>"
set myString to myString & text 1 of cell myColumnCounter
of row myRowCounter of myTable
set myString to myString & "</th>"
else
set myString to "<td>"
set myString to myString & text 1 of cell myColumnCounter
of row myRowCounter of myTable
set myString to myString & "</td>"
end if
my myWriteToFile(myString, myTextFile, true)
end repeat
my myWriteToFile("</tr>" & return, myTextFile, true)
end repeat
my myWriteToFile("</table>" & return, myTextFile, true)
end if
end repeat
end repeat
end if
end if
end tell
Understanding Text Objects
The following diagram shows a view of InDesign’s text object model. As you can see, there are two main
types of text object: layout objects (text frames) and text-stream objects (for example, stories, insertion
points, characters, and words):
CHAPTER 5: Text and TypeUnderstanding Text Objects 81
story
insertion points
characters
words
lines
paragraphs
text columns
text style ranges
texts
text frame
insertion points
characters
words
lines
paragraphs
text columns
text style ranges
texts
text containers
document
spread, page, layer
notes
notes
document
pages.item(0)
textFrames.item(0)
characters.item(0)
stories.item(0)
characters.item(0)
textFrames.item(0)
paragraphs.item(0)
characters.item(0)
stories.item(0)
paragraphs.item(0)
characters.item(0)
There are many ways to get a reference to a given text object. The following diagram shows a few ways to
refer to the first character in the first text frame of the first page of a new document:
For any text stream object, the
the text frame (or text frames) containing the text object, use the
parent of the object is the story containing the object. To get a reference to
parent text frames property.
CHAPTER 5: Text and TypeUnderstanding Text Objects 82
For a text frame, the parent of the text frame usually is the page or spread containing the text frame. If the
text frame is inside a group or was pasted inside another page item, the
containing page item. If the text frame was converted to an anchored frame, the
parent of the text frame is the
parent of the text frame
is the character containing the anchored frame.
Working with text selections
Text-related scripts often act on a text selection. The following script demonstrates a way to determine
whether the current selection is a text selection. Unlike many of the other sample scripts, this script does
not actually do anything; it simply presents a selection-filtering routine that you can use in your own
scripts (for the complete script, see TextSelection).
if (count documents) is not equal to 0 then
--If the selection contains more than one item, the selection
--is not text selected with the Type tool.
set mySelection to selection
if (count mySelection) is not equal to 0 then
--Evaluate the selection based on its type.
set myTextClasses to {insertion point, word, text style range,
line, paragraph, text column, text, story}
if class of item 1 of selection is in myTextClasses then
--The object is a text object; display the text object type.
--A practical script would do something with the selection,
--or pass the selection on to a function.
display dialog ("Selection is a text object.")
--If the selection is inside a note, the parent of the selection
--will be a note object.
if class of parent of item 1 of selection is note then
display dialog ("Selection is inside a note.")
end if
else if class of item 1 of selection is text frame then
display dialog ("Selection is a text frame")
else
display dialog ("Selected item is not a text object.")
end if
else
display dialog ("Please select some text and try again.")
end if
else
display dialog ("No documents are open.")
end if
Moving and copying text
You can move a text object to another location in text using the move method. To copy the text, use the
duplicate method (whose arguments are identical to the move method). The following script fragment
shows how it works (for the complete script, see MoveText):
CHAPTER 5: Text and TypeUnderstanding Text Objects 83
--Given a document myDocument" with four text frams on page 1...
set myTextFrameA to text frame 4 of page 1 of myDocument
set myTextFrameB to text frame 3 of page 1 of myDocument
set myTextFrameC to text frame 2 of page 1 of myDocument
set myTextFrameD to text frame 1 of page 1 of myDocument
--Note that moving text removes it from its original location.
tell parent story of myTextFrameD
--Move WordC between the words in TextFrameC.
move paragraph 4 to before word -1 of paragraph 1 of parent story of myTextFrameC
--Move WordB after the word in TextFrameB.
move paragraph 3 to after insertion point -1 of myTextFrameB
--Move WordA to before the word in TextFrameA.
move paragraph 2 to before word 1 in myTextFrameA
end tell
When you want to transfer formatted text from one document to another, you also can use the move
method. Using the
you must make the document visible and select the text you want to copy. Using
move or duplicate method is better than using copy and paste; to use copy and paste,
move or duplicate is
much faster and more robust. The following script shows how to move text from one document to another
move and duplicate. (We omitted the myGetBounds function from this listing; you can find it in
using
“Creating a text frame” on page 70
--Given a document "mySourceDocument"...
set mySourceStory to story 1 of mySourceDocument
--Create a new document to move the text to.
set myTargetDocument to make document
set myPage to page 1 of myTargetDocument
tell myPage
set myTextFrame to make text frame with properties
{geometric bounds:my myGetBounds(myTargetDocument, myPage)}
end tell
set myTargetStory to story 1 of myTargetDocument
set contents of myTargetStory to "This is the target text. Insert the source text after
this paragraph." & return
duplicate paragraph 1 of mySourceStory to after insertion point -1 of myTargetStory
,” or see the MoveTextBetweenDocuments tutorial script.)
When you need to copy and paste text, you can use the copy method of the application. You will need to
select the text before you copy. Again, you should use copy and paste only as a last resort; other
approaches are faster, less fragile, and do not depend on the document being visible. (We omitted the
myGetBounds function from this listing; you can find it in “Creating a text frame” on page 70,” o r s ee t he
CopyPasteText tutorial script.)
CHAPTER 5: Text and TypeUnderstanding Text Objects 84
--Given an open document with a text frame on page 1
set myDocumentA to document 1
set myTextFrameA to text frame 1 of page 1 of myDocumentA
--Create another example document.
set myDocumentB to make document
set myPageB to page 1 of myDocumentB
tell myPageB
set myTextFrameB to make text frame with properties {geometric bounds:my
myGetBounds(myDocumentB, myPageB)}
end tell
--Make document A the active document.
set active document to myDocumentA
--Select the text.
select text 1 of parent story of myTextFrameA
copy
--Make document B the active document.
set active document to myDocumentB
--Select the insertion point at which you want to paste the text.
select insertion point -1 of myTextFrameB
paste
One way to copy unformatted text from one text object to another is to get the contents property of a
text object, then use that string to set the
contents property of another text object. The following script
shows how to do this (for the complete script, see CopyUnformattedText):
tell application "Adobe InDesign CS6"
set myDocument to document 1
set myPage to page 1 of myDocument
tell myPage
set myTextFrameA to make text frame with properties
{geometric bounds:{72, 72, 144, 288}}
set contents of myTextFrameA to "This is a formatted string."
set font style of text 1 of parent story of myTextFrameA to "Bold"
set myTextFrameB to make text frame with properties
{geometric bounds:{228, 72, 300, 288}}
set contents of myTextFrameB to "This is the destination text frame.
Text pasted here will retain its formatting."
set font style of text 1 of myTextFrameB to "Italic"
end tell
--Copy from one frame to another using a simple copy.
select text 1 of myTextFrameA
copy
select insertion point -1 of myTextFrameB
paste
--Create another text frame on the active page.
tell myPage
set myTextFrameC to make text frame with properties
{geometric bounds:{312, 72, 444, 288}}
end tell
set contents of myTextFrameC to "Text copied here will take on
the formatting of the existing text."
set font style of text 1 of parent story of myTextFrameC to "Italic"
--Copy the unformatted string from text frame A to the end of text frame C (note
--that this doesn't really copy the text it replicates the text string from one
--text frame in another text frame):
set contents of insertion point -1 of myTextFrameC to contents of text 1 of parent
story of myTextFrameA
end tell
CHAPTER 5: Text and TypeWorking with Text Frames 85
Text objects and iteration
When your script moves, deletes, or adds text while iterating through a series of text objects, you can
easily end up with invalid text references. The following script demonstrates this problem. (We omitted the
myGetBounds function from this listing; you can find it in “Creating a text frame” on page 70,” o r s ee t he
TextIterationWrong tutorial script.)
--The following for loop will fail to format all of the paragraphs
--and then generate an error.
repeat with myParagraphCounter from 1 to (count paragraphs of myStory)
if contents of word 1 of paragraph myParagraphCounter of myStory is "Delete" then
tell paragraph myParagraphCounter of myStory to delete
else
set point size of paragraph myParagraphCounter of myStory to 24
end if
end repeat
In the preceding example, some of the paragraphs are left unformatted. How does this happen? The loop
in the script iterates through the paragraphs from the first paragraph in the story to the last. As it does so,
it deletes paragraphs that begin with the word “Delete.” When the script deletes the second paragraph,
the third paragraph moves up to take its place. When the loop counter reaches 3, the script processes the
paragraph that had been the fourth paragraph in the story; the original third paragraph is now the second
paragraph and is skipped.
To avoid this problem, iterate backward through the text objects, as shown in the following script. (We
omitted the
myGetBounds function from this listing; you can find it in “Creating a text frame” on page 70,”
or see the TextIterationRight tutorial script.)
--By iterating backwards we can avoid the error.
repeat with myParagraphCounter from (count paragraphs of myStory) to 1 by -1
if contents of word 1 of paragraph myParagraphCounter of myStory is "Delete" then
tell paragraph myParagraphCounter of myStory to delete
else
set point size of paragraph myParagraphCounter of myStory to 24
end if
end repeat
Working with Text Frames
In the previous sections of this chapter, we concentrated on working with text stream objects; in this
section, we focus on text frames, the page-layout items that contain text in an InDesign document.
Linking text frames
The nextTextFrame and previousTextFrame properties of a text frame are the keys to linking (or
“threading”) text frames in InDesign scripting. These properties correspond to the in port and out port on
InDesign text frames, as shown in the following script fragment (for the complete script, see
LinkTextFrames):
CHAPTER 5: Text and TypeWorking with Text Frames 86
--Given a document "myDocument" with two unlinked text frames on page 1...
set myTextFrameA to text frame 2 of page 1 of document 1
set myTextFrameB to text frame 1 of page 1 of document 1
--Link TextFrameA to TextFrameB using the next text frame property.
set next text frame of myTextFrameA to myTextFrameB
--Add a page.
tell myDocument
set myNewPage to make page
end tell
--Create another text frame on the new page.
tell myNewPage
set myTextFrameC to make text frame with properties
{geometric bounds:{72, 72, 144, 144}}
--Link TextFrameC to TextFrameB using the previousTextFrame property.
set previous text frame of myTextFrameC to myTextFrameB
--Fill the text frames with placeholder text.
set contents of myTextFrameA to placeholder text
end tell
Unlinking text frames
The following example script shows how to unlink text frames (for the complete script, see
UnlinkTextFrames):
--Unlink the two text frames.
set next text frame of myTextFrameA to nothing
Removing a frame from a story
In InDesign, deleting a frame from a story does not delete the text in the frame, unless the frame is the only
frame in the story. The following script fragment shows how to delete a frame and the text it contains from
a story without disturbing the other frames in the story (for the complete script, see BreakFrame):
CHAPTER 5: Text and TypeWorking with Text Frames 87
set myObjectList to {}
--Script does nothing if no documents are open or if no objects are selected.
tell application "Adobe InDesign CS6"
if (count documents) is not equal to 0 then
set mySelection to selection
if (count mySelection) is not equal to 0 then
--Process the objects in the selection to create a list of
--qualifying objects (text frames).
repeat with myCounter from 1 to (count mySelection)
if class of item myCounter of mySelection is text frame then
set myObjectList to myObjectList & item myCounter of mySelection
else if class of item myCounter of mySelection is in {text,
insertion point, character, word, line, text style range, paragraph,
text column} then
set myObject to item 1 of parent text frames of item myCounter
of mySelection
set myObjectList to myObjectList & myObject
end if
end repeat
--If the object list is not empty, pass it on to the handler
--that does the real work.
if (count myObjectList) is not equal to 0 then
my myBreakFrames(myObjectList)
end if
end if
end if
end tell
Here is the myBreakFrames handler referred to in the preceding script.
on myBreakFrames(myObjectList)
repeat with myCounter from 1 to (count myObjectList)
my myBreakFrame(item myCounter of myObjectList)
end repeat
end myBreakFrames
on myBreakFrame(myTextFrame)
tell application "Adobe InDesign CS6"
if next text frame of myTextFrame is not equal to nothing and previous text frame
of myTextFrame is not equal to nothing then
set myNewFrame to duplicate myTextFrame
if contents of myTextFrame is not equal to "" then
tell text 1 of myTextFrame to delete
end if
delete myTextFrame
end if
end tell
end myBreakFrame
Splitting all frames in a story
The following script fragment shows how to split all frames in a story into separate, independent stories,
each containing one unlinked text frame (for the complete script, see SplitStory):
CHAPTER 5: Text and TypeWorking with Text Frames 88
on mySplitStory(myStory)
tell application "Adobe InDesign CS6"
tell document 1
local myTextContainers
set myTextContainers to text containers in myStory
if (count myTextContainers) is greater than 1 then
repeat with myCounter from (count myTextContainers) to 1 by -1
set myTextFrame to item myCounter of myTextContainers
tell myTextFrame
duplicate
if text 1 of myTextFrame is not equal to "" then
tell text 1 of myTextFrame
delete
end tell
end if
delete
end tell
end repeat
end if
end tell
end tell
end mySplitStory
Creating an anchored frame
To create an anchored frame (also known as an inline frame), you can create a text frame (or rectangle,
oval, polygon, or graphic line) at a specific location in text (usually an insertion point). The following script
fragment shows an example (for the complete script, see AnchoredFrame):
--Given a document "myDocument" with a text frame on page 1...
set myPage to page 1 of myDocument
set myTextFrame to text frame 1 of myPage
tell insertion point 1 of paragraph 1 of myTextFrame
set myInlineFrame to make text frame
end tell
--Recompose the text to make sure that getting the
--geometric bounds of the inline graphic will work.
tell text 1 of myTextFrame to recompose
--Get the geometric bounds of the inline frame.
set myBounds to geometric bounds of myInlineFrame
--Set the width and height of the inline frame. In this example, we'll
--make the frame 24 points tall by 72 points wide.
set e1 to item 1 of myBounds
set e2 to item 2 of myBounds
set e3 to (item 1 of myBounds) + 24
set e4 to (item 2 of myBounds) + 72
set geometric bounds of myInlineFrame to {e1, e2, e3, e4}
set contents of myInlineFrame to "This is an inline frame."
tell insertion point 1 of paragraph 2 of myTextFrame
set myAnchoredFrame to make text frame
end tell
--Recompose the text to make sure that getting the
--geometric bounds of the inline graphic will work.
tell text 1 of myTextFrame to recompose
--Get the geometric bounds of the inline frame.
set myBounds to geometric bounds of myAnchoredFrame
--Set the width and height of the inline frame. In this example, we'll
--make the frame 24 points tall by 72 points wide.
set e1 to item 1 of myBounds
CHAPTER 5: Text and TypeWorking with Text Frames 89
set e2 to item 2 of myBounds
set e3 to (item 1 of myBounds) + 24
set e4 to (item 2 of myBounds) + 72
set geometric bounds of myAnchoredFrame to {e1, e2, e3, e4}
set contents of myAnchoredFrame to "This is an anchored frame."
tell anchored object settings of myAnchoredFrame
set anchored position to anchored
set anchor point to top left anchor
set horizontal reference point to anchor location
set horizontal alignment to left align
set anchor xoffset to 72
set vertical reference point to line baseline
set anchor yoffset to 24
set anchor space above to 24
end tell
Fitting text frames to content
The following example script shows how to set rules on a text frame to determine how it grows when the
user inputs text (for the complete script, see PersistedTextFrameFill):
tell application "Adobe InDesign CS6"
set myDocument to document 1
set myPage to page 1 of myDocument
tell myPage
set myTextFrame to text frame 4 of myPage
--Now add text at the end of the text frame.
set myString to return & "this is some overset text"
tell insertion point -1 of myTextFrame to set contents to myString
set myString to contents of text 1 of myTextFrame
display dialog
("The last paragraph in this alert should be \"This is some overset text\". Is it?"
& return & myString)
set myString to contents of parent story of myTextFrame
display dialog
("The last paragraph in this alert should be \"This is some overset text\". Is it?"
& return & myString)
end tell
set myPage to page 1 of myDocument
tell myPage
set myTextFrame2 to text frame 3 of myPage
--Set auto sizing dimension of the text frame
tell text frame preferences of myTextFrame2
set auto sizing dimension to height and width proportionally
end tell
--Now add text at the end of the text frame.
set myString to return & "this is some overset text"
tell insertion point -1 of myTextFrame2 to set contents to myString
end tell
set myPage to page 1 of myDocument
tell myPage
set myTextFrame3 to text frame 2 of myPage
--Set auto sizing dimension of the text frame
--useMinimumHeightForAutoSizing and useNoLineBreaksForAutoSizing
tell text frame preferences of myTextFrame3
set auto sizing dimension to height only
set use minimum height for auto sizing to true
set use no line breaks for auto sizing to true
end tell
CHAPTER 5: Text and TypeFormatting Text 90
--Now add text at the end of the text frame.
set myString to return & "this is some overset text"
tell insertion point -1 of myTextFrame3 to set contents to myString
end tell
set myPage to page 1 of myDocument
tell myPage
set myTextFrame4 to text frame 1 of myPage
--Set auto size dimension of the text frame and auto sizing reference point
tell text frame preferences of myTextFrame4
set auto sizing dimension to width only
set auto sizing reference point to top left position
end tell
--Now add text at the end of the text frame.
set myString to return & "this is some overset text"
tell insertion point -1 of myTextFrame4 to set contents to myString
end tell
Formatting Text
In the previous sections of this chapter, we added text to a document, linked text frames, and worked with
stories and text objects. In this section, we apply formatting to text. All the typesetting capabilities of
InDesign are available to scripting.
Setting text defaults
You can set text defaults for both the application and each document. Text defaults for the application
determine the text defaults in all new documents; text defaults for a document set the formatting of all
new text objects in that document. (For the complete script, see TextDefaults.)
set horizontal measurement units of view preferences to points
set vertical measurement units of view preferences to points
--To set the text formatting defaults for a document, replace "app"
--in the following lines with a reference to a document.
tell text defaults
set alignToBaseline to true
--Because the font might not be available, it's usually best
--to apply the font within a try...catch structure. Fill in the
--name of a font on your system.
try
set appliedFont to font "Minion Pro"
end try
--Because the font style might not be available, it's usually best
--to apply the font style within a try...catch structure.
try
set font style to "Regular"
end try
--Because the language might not be available, it's usually best
--to apply the language within a try...catch structure.
try
set applied language to "English: USA"
end try
set autoLeading to 100
set balsanceRaggedLines to false
set baselineShift to 0
set capitalization to normal
set composer to "Adobe Paragraph Composer"
set desiredGlyphScaling to 100
CHAPTER 5: Text and TypeFormatting Text 91
set desiredLetterSpacing to 0
set desiredWordSpacing to 100
set drop cap characters to 0
if drop cap characters is not equal to 0 then
dropCapLines to 3
--Assumes that the application has a default character style named "myDropCap"
set drop cap style to character style "myDropCap"
end if
set fill color to "Black"
set fill tint to 100
set first line indent to 14
set grid align first line only to false
set horizontal scale to 100
set hyphenate after first to 3
set hyphenate before last to 4
set hyphenate capitalized words to false
set hyphenate ladder limit to 1
set hyphenate words longer than to 5
set hyphenation to true
set hyphenation zone to 36
set hyphen weight to 9
set justification to left align
set keep all lines together to false
set keep lines together to true
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 false
set OTF figure style to proportional oldstyle
set OTF fraction to true
set OTF historical to false
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 pointSize to 11
set position to normal
set right indent to 0
set rule above to false
if rule above = true then
set rule above color to color "Black"
set rule above gap color to swatch "None"
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
CHAPTER 5: Text and TypeFormatting Text 92
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 = true then
set rule below color to color "Black"
set rule below gap color to swatch "None"
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 = true then
set strike through color to color "Black"
set strike through gap color to swatch "None"
set strike through gap overprint to false
set strike through gap tint to 100
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 "None"
set stroke tint to 100
set stroke weight to 0
set tracking to 0
set underline to false
if underline = true then
set underline color to color "Black"
set underline gap color to swatch "None"
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
CHAPTER 5: Text and TypeFormatting Text 93
Working with fonts
The fonts collection of the InDesign application object contains all fonts accessible to InDesign. The fonts
collection of a document, by contrast, contains only those fonts used in the document. The fonts
collection of a document also contains any missing fonts—fonts used in the document that are not
accessible to InDesign. The following script shows the difference between application fonts and document
fonts. (We omitted the
set myApplicationFonts to the name of every font
set myDocument to active document
tell myDocument
set myPage to page 1
tell myPage
set myTextFrame to make text frame with properties {geometric bounds:my
myGetBounds(myDocument, myPage)}
end tell
set myStory to parent story of myTextFrame
set myDocumentFonts to name of every font
end tell
set myString to "Document Fonts:" & return
repeat with myCounter from 1 to (count myDocumentFonts)
set myString to myString & (item myCounter) of myDocumentFonts & return
end repeat
set myString to myString & return & "Application Fonts:" & return
repeat with myCounter from 1 to (count myApplicationFonts)
set myString to myString & (item myCounter) of myApplicationFonts & return
end repeat
set contents of myStory to myString
myGetBounds function here; for the complete script, see FontCollections.)
NOTE: Font names typically are of the form familyName<tab>fontStyle, where familyName is the name
of the font family,
"Adobe Caslon Pro<tab>Semibold Italic"
<tab> is a tab character, and fontStyle is the name of the font style. For example:
Applying a font
To apply a local font change to a range of text, use the appliedFont property, as shown in the following
script fragment (from the ApplyFont tutorial script):
--Given a font name "myFontName" and a text object "myText"...
set applied font of myText to myFontName
You also can apply a font by specifying the font family name and font style, as shown in the following script
fragment:
tell myText
set applied font to "Adobe Caslon Pro"
set font style to "Semibold Italic"
end tell
Changing text properties
Text objects in InDesign have literally dozens of properties corresponding to their formatting attributes.
Even one insertion point features properties that affect the formatting of text—up to and including
properties of the paragraph containing the insertion point. The SetTextProperties tutorial script shows
how to set every property of a text object. A fragment of the script is shown below:
CHAPTER 5: Text and TypeFormatting Text 94
--Given a document "myDocument" containing a story...
set myStory to story 1 of myDocument
tell character 1 of myStory
set align to baseline to false
set applied character style to character style "[None]" of myDocument
set applied font to "Minion ProRegular"
set applied language to "English: USA"
set applied numbering list to "[Default]"
set applied paragraph style to paragraph style "[No Paragraph Style]" of myDocument
set auto leading to 120
set balance ragged lines to no balancing
set baseline shift to 0
set bullets alignment to left align
set bullets and numbering list type to no list
set bullets character style to character style "[None]" of myDocument
set bullets text after to "^t"
set capitalization to normal
set composer to "Adobe Paragraph Composer"
set desired glyph scaling to 100
set desired letter spacing to 0
set desired word spacing to 100
set drop cap characters to 0
set drop cap lines to 0
set drop cap style to character style "[None]" of myDocument
set dropcap detail to 0
set fill color to color "Black" of myDocument
set fill tint to -1
set first line indent to 0
set font style to "Regular"
set gradient fill angle to 0
set gradient fill length to -1
set gradient fill start to [0, 0]
set gradient stroke angle to 0
set gradient stroke length to -1
set gradient stroke start to [0, 0]
set grid align first line only to false
set horizontal scale to 100
set hyphen weight to 5
set hyphenate across columns to true
set hyphenate after first to 2
set hyphenate before last to 2
set hyphenate capitalized words to true
set hyphenate ladder limit to 3
set hyphenate last word to true
set hyphenate words longer than to 5
set hyphenation to true
set hyphenation zone to 3
set ignore edge alignment to false
set justification to left align
set keep all lines together to false
set keep first lines to 2
set keep last lines to 2
set keep lines together to false
set keep rule above in frame to false
set keep with next to 0
set kerning method to "Optical"
set last line indent to 0
set leading to 12
set left indent to 0
set ligatures to true
CHAPTER 5: Text and TypeFormatting Text 95
set maximum glyph scaling to 100
set maximum letter spacing to 0
set maximum word spacing to 133
set minimum glyph scaling to 100
set minimum letter spacing to 0
set minimum word spacing to 80
set no break to false
set numbering alignment to left align
set numbering apply restart policy to true
set numbering character style to character style "[None]" of myDocument
set numbering continue to true
set numbering expression to "^#.^t"
set numbering format to "1, 2, 3, 4..."
set numbering level to 1
set numbering start at to 1
set OTF contextual alternate to true
set OTF discretionary ligature to false
set OTF figure style to proportional lining
set OTF fraction to false
set OTF historical to false
set OTF locale to true
set OTF mark to true
set OTF ordinal to false
set OTF slashed zero to false
set OTF stylistic sets to 0
set OTF swash to false
set OTF titling to false
set overprint fill to false
set overprint stroke to false
set point size to 72
set position to normal
set positional form to none
set right indent to 0
set rule above to false
set rule above color to "Text Color"
set rule above gap color to swatch "None" of myDocument
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" of myDocument
set rule above width to column width
set rule below to false
set rule below color to "Text Color"
set rule below gap color to swatch "None" of myDocument
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" of myDocument
set rule below width to column width
set single word justification to left align
CHAPTER 5: Text and TypeFormatting Text 96
set skew to 0
set space after to 0
set space before to 0
set start paragraph to anywhere
set strike thru to false
set strike through color to color "Black" of myDocument
set strike through gap color to swatch "None" of myDocument
set strike through gap overprint to false
set strike through gap tint to 100
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" of myDocument
set strike through weight to 0.25
set stroke color to swatch "None" of myDocument
set stroke tint to -1
set stroke weight to 1
set tracking to 0
set tracking to 0
set underline to false
set underline color to color "Black" of myDocument
set underline gap color to swatch "None" of myDocument
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" of myDocument
set underline weight to 0.25
set vertical scale to 100
end tell
Changing text color
You can apply colors to the fill and stroke of text characters, as shown in the following script fragment
(from the TextColors tutorial script):
set myStory to story 1 of myDocument
set myColorA to color "DGC1_664a" of myDocument
set myColorB to color "DGC1_664b" of myDocument
tell paragraph 1 of myStory
set point size to 72
set justification to center align
--Apply a color to the fill of the text.
set fill color to myColorA
set stroke color to myColorB
end tell
tell paragraph 2 of myStory
set stroke weight to 3
set point size to 144
set justification to center align
set fill color to myColorB
set stroke color to myColorA
set stroke weight to 3
end tell
CHAPTER 5: Text and TypeFormatting Text 97
Creating and applying styles
While you can use scripting to apply local formatting—as in some of the examples earlier in this
chapter—you probably will want to use character and paragraph styles to format your text. Using styles
creates a link between the formatted text and the style, which makes it easier to redefine the style, collect
the text formatted with a given style, or find and/or change the text. Paragraph and character styles are
the keys to text formatting productivity and should be a central part of any script that applies text
formatting.
The following example script fragment shows how to create and apply paragraph and character styles (for
the complete script, see CreateStyles):
--Given a document "myDocument" containing a story and the color "Red"...
tell myDocument
set myColor to color "Red"
set myStory to story 1 of myDocument
set contents of myStory to "Normal text. Text with a character style applied to it.
More normal text."
--Create a character style named "myCharacterStyle" if
--no style by that name already exists.
try
set myCharacterStyle to character style "myCharacterStyle"
on error
--The style did not exist, so create it.
set myCharacterStyle to make character style with properties
{name:"myCharacterStyle"}
end try
--At this point, the variable myCharacterStyle contains a reference to a character
--style object, which you can now use to specify formatting.
set fill color of myCharacterStyle to myColor
--Create a paragraph style named "myParagraphStyle" if
--no style by that name already exists.
try
set myParagraphStyle to paragraph style "myParagraphStyle"
on error
--The paragraph style did not exist, so create it.
set myParagraphStyle to make paragraph style with properties
{name:"myParagraphStyle"}
end try
--At this point, the variable myParagraphStyle contains a reference to a paragraph
--style object, which you can now use to specify formatting.
--(Note that the story object does not have the apply paragraph style method.)
tell text 1 of myStory
apply paragraph style using myParagraphStyle
tell text from character 13 to character 54
apply character style using myCharacterStyle
end tell
end tell
end tell
Why use the applyParagraphStyle method instead of setting the appliedParagraphStyle property of
the text object? The
applyParagraphStyle method gives the ability to override existing formatting;
setting the property to a style retains local formatting.
Why check for the existence of a style when creating a new document? It always is possible that the style
exists as an application default style. If it does, trying to create a new style with the same name results in an
error.
CHAPTER 5: Text and TypeFormatting Text 98
Nested styles apply character-style formatting to a paragraph according to a pattern. The following script
fragment shows how to create a paragraph style containing nested styles (for the complete script, see
NestedStyles):
--Given a document "myDocument"...
--Get the last paragraph style.
set myParagraphStyle to paragraph style -1 of myDocument
--Get the last character style
set myCharacterStyle to character style -1 of myDocument
--At this point, the variable myParagraphStyle contains a reference to a paragraph
--style object. Next, add a nested style to the paragraph style.
tell myParagraphStyle
set myNestedStyle to make nested style with properties {applied character
style:myCharacterStyle, delimiter:".", inclusive:true, repetition:1}
end tell
set myPage to page 1 of myDocument
set myTextFrame to text frame 1 of myPage
--Apply the paragraph style to the story so that we can see the
--effect of the nested style we created.
--(Note that the story object does not have the apply paragraph style method.)
set myStory to parent story of myTextFrame
tell text 1 of myStory
apply paragraph style using myParagraphStyle
end tell
Deleting a style
When you delete a style using the user interface, you can choose the way you want to format any text
tagged with that style. InDesign scripting works the same way, as shown in the following script fragment
(from the RemoveStyle tutorial script):
--Given a document "myDocment" with paragraph styles named
--"myParagraphStyleA" and "myParagraphStyleB", remove the
--paragraph style "myParagraphStyleA" and replace with
--"myParagraphStyleB."
tell myDocument
delete paragraph style "myParagraphStyleA" replacing with paragraph style
"myParagraphStyleB"
end tell
Importing paragraph and character styles
You can import character and paragraph styles from other InDesign documents, as shown in the following
script fragment (from the ImportTextStyles tutorial script):
CHAPTER 5: Text and TypeFinding and Changing Text 99
--You'll have to fill in a valid file path for your system.
set myFilePath to "Macintosh HD:scripting:styles.indd"
--Create a new document.
set myDocument to make document
tell myDocument
--Import the styles from the saved document.
--importStyles parameters:
--Format options for text styles are:
-- paragraph styles format
-- character styles format
-- text styles format
--From as file or string
--Global Strategy options are:
-- do not load the style
-- load all with overwrite
-- load all with rename
import styles format text styles format from myFilePath global strategy load all
with overwrite
end tell
Finding and Changing Text
The find/change feature is one of the most powerful InDesign tools for working with text. It is fully
supported by scripting, and scripts can use find/change to go far beyond what can be done using the
InDesign user interface. InDesign has three ways of searching for text:
You can find text and/or text formatting and change it to other text and/or text formatting. This type
of find/change operation uses the
specify parameters for the
You can find text using regular expressions, or “grep.” This type of find/change operation uses the
findGrepPreferences and changeGrepPreferences objects to specify parameters for the findGrep
changeGrep methods.
and
You can find specific glyphs (and their formatting) and replace them with other glyphs and formatting.
findText and changeText methods.
findTextPreferences and changeTextPreferences objects to
This type of find/change operation uses the
objects to specify parameters for the
All the find/change methods take one optional parameter,
which the results of the search are returned. If you are processing the results of a find or change operation
in a way that adds or removes text from a story, you might face the problem of invalid text references, as
discussed earlier in this chapter. In this case, you can either construct your loops to iterate backward
through the collection of returned text objects, or you can have the search operation return the results in
reverse order and then iterate through the collection normally.
About find/change preferences
Before you search for text, you probably will want to clear find and change preferences, to make sure the
settings from previous searches have no effect on your search. You also need to set some find/change
preferences to specify the text, formatting, regular expression, or glyph you want to find and/or change. A
typical find/change operation involves the following steps:
findGlyphPreferences and changeGlyphPreferences
findGlyph and changeGlyph methods.
ReverseOrder, which specifies the order in
1.Clear the find/change preferences. Depending on the type of find/change operation, this can take one
of the following three forms:
CHAPTER 5: Text and TypeFinding and Changing Text 100
--find/change text preferences
tell application "Adobe InDesign CS6"
set find text preferences to nothing
set change text preferences to nothing
end tell
--find/change grep preferences
tell application "Adobe InDesign CS6"
set find grep preferences to nothing
set change grep preferences to nothing
end tell
--find/change glyph preferences
tell application "Adobe InDesign CS6"
set find glyph preferences to nothing
set change glpyh preferences to nothing
end tell
2.Set up search parameters.
3.Execute the find/change operation.
4.Clear find/change preferences again.
Finding and changing text
The following script fragment shows how to find a specified string of text. While the following script
fragment searches the entire document, you also can search stories, text frames, paragraphs, text columns,
or any other text object. The
the complete script, see FindText.)
--Clear the find/change preferences.
set find text preferences to nothing
set change text preferences to nothing
--Search the document for the string "Text".
set find what of find text preferences to "text"
--Set the find options.
set case sensitive of find change text options to false
set include footnotes of find change text options to false
set include hidden layers of find change text options to false
set include locked layers for find of find change text options to false
set include locked stories for find of find change text options to false
set include master pages of find change text options to false
set whole word of find change text options to false
tell active document
set myFoundItems to find text
display dialog ("Found " & (count myFoundItems) & " instances of the search
string.")
end tell
findText method and its parameters are the same for all text objects. (For
The following script fragment shows how to find a specified string of text and replace it with a different
string (for the complete script, see ChangeText):
Loading...
+ hidden pages
You need points to download manuals.
1 point = 1 manual.
You can buy points or you can get point for every manual you upload.