345 Park Avenue
San Jose, CA 95110-2704
408-536-9000
FaxYI: 206-628-5737
ada@adobe.com
http://partners.adobe.com
Europe:
PO Box 12356
Edinburgh EH11 4GJ
United Kingdom
+44.131.458.6800
Fax: +44.131.458 6801
euroADA@adobe.com
ii
Adobe Illustrator 10 Scripting Guide
Copyright 2000 Adobe Systems Incorporated.
All Rights Reserved.
The information in this document 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 this document. The software described in this
document is furnished under license and may only be used or copied in accordance with
the terms of such license.
Adobe, Adobe Aft er Effects, Adobe PhotoDeluxe, A dobe Premier e, Adobe Photoshop,
Adobe Illustrator, Adobe InDesign, Adobe Type Manager, ATM and PostScript are
trademarks of Adobe Systems Inc o rporated that ma y be registered in certain jurisdictions.
Macintosh and Apple are registered trademarks, and Mac OS and AppleScript are
trademarks of Apple Computer, Inc. Microsoft, Visual Basic, Windows, Windows 95,
Windows 98, and Windows NT are registered trademarks of Microsoft Corporation. All
other products or name brands are trademarks of their respective holders.
Welcome to scripting, arguably the most exciting new feature of Illustrator. No other
feature, new or old, can save you as much time, effort, and money as scripting.
About this manual
This manual provides an introduction to scripting Adobe Illustrator 10 on Mac OS and
Windows. We realize that not every Illustrator user will be familiar with programming
terms, concepts, and techniques, so we’ve included Chapter 2, “Scripting Basics,” which
contains introductory information that should help get you started with scripting. If you’re
an experienced AppleScript scripter or Visual Basic programmer, you will probably want
to skip to Chapter 3 to get the specifics on scripting Illustrator.
This manual consists of the following chapters:
1. An introduction to scripting.
2. The basics of each platform’s scripting language: AppleScript in Mac OS and
Visual Basic in Windows. If you are new to scripting, be sure to read this
chapter. Beginners are heartily encouraged to consult the Bibliograph y for books
on AppleScript and Visual Basic.
3. A brief introduction to the specifics of scripting Illustrator. Concepts and
approaches specific to the application are covered here, such as measurement
units, matrices, and color models.
4. The Illustrator AppleScript Reference. Here you’ll find details and examples for
every object and command in Illustrator’s AppleScript dictionary.
5. The Illustrator Visual Basic Reference. Details and examples are provided for
every class in Illustrator’s Visual Basic type library.
6. A bibliography of helpful resources for learning more about scripting.
11
What is scripting?Introduction12
What is scripting?
A script is a series of commands that tells Illustrator to perform a series of actions. These
actions can be simple, and affect only a single, selected object in the current document;
or complex, and affect all of the objects in all of your Illustrator documents. The actions
might involve only Illustrator, or they might involve other applications, such as word
processors, spreadsheets, and database management programs. Many of the tasks you
can perform with Illustrator’s tools, menus, palettes, and dialog boxes can be performed
by a script (a notable exception is third-party plug-ins, which cannot be scripted at this
time).
We naturally think of scripting as a way to automate repetitive tasks, but it can also be a
creative tool. You can use scripts for creative tasks that would be too difficult or time
consuming to do manually. For example, you could write a script to systematically create
a series of objects, modifying the new objects’ position, stroke, and fill properties along
the way. You could also write a script that accessed Illustrator’s built-in transformation
matrix functions to stretch, scale and distort a series of objects. Without scripting, you’ll
likely miss out on the creative potential of such labor-intensive techniques.
Scripting isn’t just for computer programmers—it’ s f or e v erybody. You don’t need a degree
in computer science or mathematics to write scripts that can automate a wide variety of
common tasks. If you can read this text, you can write scripts.
Why use scripting?
Graphic design is a field characterized by creativity, but aspects of the actual work of
illustration and page layout are anything but creative. When you think about the work that
you do, chances are good you’ll find that you spend most of your time doing the same or
similar production tasks, over and over again. In fact, you’ll probably notice that the time
you spend placing and replacing images, correcting errors in text, and preparing files for
printing at an imagesetting service provider often reduce the time you have available for
doing creative work.
Wouldn’t it be great if you had an assistant—one that wouldn’t mind doing some or all of
the boring, repetitive tasks for you? With that kind of help, you’d have more time to
concentrate on the creative aspects of your work.
With a small investment of time, Illustrator scripting can be the assistant you need. You
can start with short, simple scripts that save you a few seconds every day, and move on
to scripts that work all night while you’re sleeping.
Adobe Illustrator 10 Scripting Guide What about actions?13
Think about your work—is there a repetitive task that’s driving you crazy? If so, you’ve
identified a candidate for a script. What are the steps involved in performing the task?
What are the conditions in which you need to do the task? Once you understand the
process you go through to perform the task, you’ll be ready to turn it into a script.
What about actions?
Illustrator actions are different from scripts. An Illustrator action is a series of tasks you
have recorded while using the application—menu choices, tool choices, object selection,
and other commands. When you “play” an action, Illustrator performs all of the recorded
commands.
You record, play, edit and delete actions using Illustrator’s built-in Actions palette. The
“Automating Tasks” chapter in the Adobe Illustrator User Guide covers actions in detail.
With the introduction of scripting for Illustrator , it is important to avoid an y confusion about
the difference between actions and scripting. Actions and scripts are both ways of
automating repetitive tasks, but the y work v ery differently. The following points summarize
the key differences.
•Actions use a program’s user interface to do their work. As an action runs, menu
choices are executed, objects are selected, and recorded paths are created. Scripts
do not use a program’s user interface to perform tasks, and can execute faster than
actions.
•Actions have very limited facilities for getting and responding to information. You
cannot add conditional logic to an action. Therefore, actions cannot make decisions
based on the current situation. Scripts are capable of getting information and making
decisions and calculations based on the information they receive from Illustrator.
•A script can execute an action, but actions cannot execute scripts.
System requirements
The language you use to write scripts depends on the operating system of the platform
you’re using: AppleScript for Mac OS; Visual Basic for Windows. While the two scripting
systems differ, the ways that they work with Illustrator are very similar. Each example
script shown in this manual will be shown in both systems. Make sure the scripting plug-in
is installed on your system before attempting to script Illustrator.
System requirementsIntroduction14
Mac OS
To write scripts on Mac OS, you must have Mac OS v ersion 8.6 or later . You will also need
AppleScript and a script editor installed. AppleScript and the Script Editor application
from Apple come installed on all supported versions of Mac OS. The default location for
the Script Editor application is the Apple Extras folder. In the unlikely event that these
items are not installed on your system, reinstall them from your original system software
CD-ROM.
As your scripts become more complex, you may find the need for debugging and
productivity features not found in Script Editor. Third-party script editors, such as Script
Debugger (from Late Night Software, http://www.latenightsw.com) or Scripter (from Main
Event Software, http://www.mainevent.com) provide additional features that aid script
development.
If your script would benefit from a complete user interface, you might want to use
FaceSpan (http://www.facespan.com) or Real Basic (http://www.realsoftware.com)—
programs created in these development environments can have complete graphical user
interfaces as well as send AppleScript commands to Illustrator.
We use the Script Editor from Apple in this manual.
Windows
To use Illustrator scripting in Windows, you must have Windows 98, Windows NT 4.0, or
Windows 2000. You will also need the Microsoft Visual Basic dev elopment en vironment or
one of the applications that contain a Visual Basic editor. Many applications that support
the Visual Basic for Applications (VBA) language contain a built-in editor. Applications
that contain a built-in editor include: Microsoft Word, Microsoft Excel, and Visio. You can
use any Visual Basic editor to create your scripts.
As your scripts become more complex or require a user interface, you will find the need
for a complete development environment than one of the built-in editors. The Microsoft
Visual Basic development environment comes in a variety of package, all of which
provide everything you need to script Illustrator.
In this manual, we use the Microsoft Visual Basic development environment’s editor.
2
Scripting Basics
If you use Illustrator, then you work with documents and their contents. You create
documents, layers, colors, and design elements. If you do all of this, you’ve probably
gotten used to thinking of an Illustrator document as a series of objects.
Automating Illustrator with scripting uses the same object-oriented way of thinking. The
heart of a scriptable application is the object model. In Illustrator, the object model is
comprised of documents, layers, colors, and page items—objects that can appear in an
Illustrator document. Each type of object has its own special properties, and every object
in an Illustrator document has its own identity.
In this chapter, we’ll co v er the basic concepts of scripting f or both AppleScript on Mac OS
and Visual Basic on Windows. This brief introduction to the basic concepts and syntax of
each scripting language is by no means complete or exhaustive. The bibliography
contains references to more complete language guides for both scripting languages.
For detailed information on using your particular scripting system with Illustrator, see the
appropriate reference chapter later in this manual. Experienced scripters may want to
skip to those chapters now.
Object model concepts
The terminology of object oriented programming can be hard to understand, at first.
“Objects” belong to “classes” and have “properties” you manipulate using “commands”
(AppleScript) or “methods” (Visual Basic). What do these words mean in this context?
Here’s a way to think about objects and their properties. Imagine that you live in a house
that responds to your commands (you can think of this house as technologically
advanced, or magical, or both). The house is an object, and its properties might include
the number of rooms, the color of the exterior paint, or the date of its construction.
15
Object classes Object model concepts16
Your house can also contain other objects. Just lik e y our house can contain other objects,
the objects within the house can also contain a number of smaller objects. Each room, for
example, is an object in the house, while each window, door, or appliance is an object
inside of the room.
Each object can respond to various commands according to its capabilities. Windo ws and
doors, for example, can open or close—but the floor and ceiling cannot. Using scripting,
you can talk to each object directly, or you can talk to them as part of the house. You have
to be very specific, though—you can’t tell your house to open a window without telling it
which window you want to open. So windows, just like all other objects, need names or at
least a numbering system so you can refer to them specifically. “Tell the house to open
the north window of the living room,” you might say.
Objects also have properties that describe specific details about them, like color and size.
Imagine that the properties of objects in your house can be changed. You might say,
“Door, paint y ourself blue.” Because your door can respond to the command “paint,” you’ll
soon have a door of a different color.
Now let’ s apply this object model idea to Illustrator . The Illustrator application is the house,
its documents are the rooms, and the objects in your documents are the windows and
doors. You can tell Illustrator documents to add and remove objects. You can ask objects
to get or change their properties.
Object classes
Objects with the same properties and behaviors are grouped into “classes.” In the house
example, windows and doors belong to their own classes, since they have unique
properties, like number of panes for windows or the door style for doors. In Illustrator,
every type of graphic object—paths, text, meshes, etc.—belongs to its own class, each
with its own set of properties and behaviors. Properties such as
width
, and
height
, for example, are common to all
page items
visible bounds
.
,
Object inheritance
Object classes may also “inherit,” or share, the properties of a parent, or superclass.
When an class inherits properties, we call that class a child, or subclass of the class from
which it inherits properties. So in our house example , windo ws and doors are subclasses
of an openings class, since they are both openings in a house. In Illustrator,
items
page item
Classes will often have properties that aren’t shared with their superclass. In our house,
both a window and door inherit an opened property from the opening class, but a window
has number of panes property which the opening class doesn’t. In Illustrator,
items
, for example, have the property
page item
stroke color
class.
which isn’t inherited from the
path
Object elements or collections
Object elements (AppleScript) or collections (Visual Basic) are objects contained within
other objects. For example, rooms are elements (or collections) of our house, contained
within the house object. In Illustrator, documents are elements of the application object,
and page items are elements of a document object.
Object references
The objects in your documents are arranged in a hierarchy like the house object—page
items are in layers, which are inside a document, which is inside Illustrator. When you
send a command to an Illustrator object, you need to make sure y ou send the message to
the right object. To do this, you identify objects by their position in the hierarchy. You
might, for example, write the following statement.
AppleScript
page item 1 of layer 1 of document 1
Visual Basic
Documents(1).Layers(1).PageItems(1)
When you identify an object in this fashion, you’re creating an
AppleScript and Visual Basic use diff erent wa ys of creating object references , but the idea
is the same—to give the script a way of finding the object you want to work with.
object reference
.
Scripting concepts
Comments
Comments are a way to add descriptive text to a script. Comments come in handy when
you want to document the operation of a script (for y ourself or f or someone else). The use
of comments is the most important technique for good scripting. Comments are where
you should leave important notes about the specific operation of a script that might
provide valuable help when the script is modified at a later date. The time you save later
trying to figure out what the script does may be your own. Comments are ignored by the
scripting system as the script executes and cause no run-time speed penalty.
About long script lines Scripting concepts18
AppleScript
To enter a single-line comment in an AppleScript, type “--” to the left of your description.
For multiple line comments, start your comment with the characters “(*” and end it with
“*)”.
-- this is a single-line comment
(* this is a
multiple line comment *)
Visual Basic
In Visual Basic, enter “'” (a single straight quote) to the left of the comment.
' This is a comment
About long script lines
In some cases, individual script lines are too long to print on a single line in this guide.
AppleScript
AppleScript uses the special character (¬) to show that the line continues to the next line .
This continuation character denotes a “soft return” in the script. You can enter this
character in the script editor by pressing Option-Return at the end of the line you wish to
continue.
Visual Basic
Visual Basic uses a special character (_) to show that the line continues to the next line.
This continuation character denotes a “soft return” in the script. You can enter this
character in the editor by pressing Shift--(dash) at the end of the line you wish to
continue.
Values
Values are the data your scripts use to do their work. Most of the time , the values used in
your scripts will be numbers or text.
BooleanLogical true or false.true
IntegerWhole numbers (no decimal
points). Integers can be
positive or negative.
RealA number which may contain
a decimal point.
StringA series of text characters.
Strings appear inside
(straight) quotation marks.
ListAn ordered list of values. The
values of a list may be any
type.
Object referenceA specific reference to an
object.
RecordAn unordered list of
properties, Each property is
identified by its label.
14
13.9972
"I am a string"
{10.0, 20.0, 30.0, 40.0}
document 1
{name: "you", index: 1}
Visual Basic
Value type:What it is:Example:
BooleanLogical true or falsetrue
LongWhole numbers (no decimal
points). Longs can be positiv e
or negative.
DoubleA number which may contain
a decimal point.
StringA series of text characters.
Strings appear inside
(straight) quotation marks.
ArrayA list of values. Arrays
contain a single value type
unless the type is defined as
Variant.
Object referenceA specific reference to an
object.
User-definedA collection of elements
referenced by a key and
stored as a key-value pair.
14
13.9972
"I am a string"
Array(10.0, 20.0, 30.0, 40.0)
Application.Documents(1)
Var.name = "you"
Var.index = 1
Variables Scripting concepts20
Variables
Variables are containers for data. A variable might contain a number, a string, a list (or
array), or an object reference. Variables have names, and you refer to a variable by its
name. To put data into a variable, we assign the data to the variable. The file name of the
current Illustrator document or the current date are both examples of data that can be
assigned to a variable.
Why not simply enter the value directly in the script rather than using a variable? When
you use a value directly the flexibility of script is reduced. By using variables the scripts
you write will be reusable in a wider variety of situations. As a script executes, it can
assign data to the variables that reflect the state of the current document and selection,
for example, and then make decisions based on the content of the variables.
In AppleScript, it is not important to declare your variables before assigning values to
them. In Visual Basic, however, it is considered good form to declare all of your variables
before using them with the
to the variable, which helps us keep our scripts clear and readable. Memory is also used
more efficiently if variables are declared before use. If you start your scripts in Visual
Basic with the line
Option Explicit, you will be required to declare all variables
before assigning data to them.
Dim statement. Using the Dim statement assigns a value type
Visual Basic
Option Explicit
Dim thisNumber As Single
thisNumber = 10
Assigning values to variables is fairly simple, as shown below.
AppleScript
set thisNumber to 10
set thisString to "Hello, World!"
Visual Basic
thisNumber = 10
thisString = "Hello, World!"
Variables can also be used to store references to objects. In AppleScript, a reference is
returned when you create a new object in an Illustrator document. This returned ref erence
points to the newly created object. Storing references in variables is just the same as
assigning any other value to the variable.
set thisLayer to make new layer at beginning of document 1
or you can fill the variable with a reference to an existing object:
set thisLayer to layer 1 of document 1
Visual Basic works similarly, however, there is an important distinction to note. If you are
assigning an object reference to a variable you must use the
example, to assign a variable as you create a layer, use
Set thisLayer = Illustrator.Documents(1).Layers.Add
Set command. For
Set:
or in reference to an existing layer, since it is also an object reference, use Set:
Set thisLayer = Illustrator.Documents(1).Layers(1)
If you are simply trying to assign a value to a variable in Visual Basic that is not an object
reference, do not use
set but simply use Visual Basic’s assignment operator, the equals
sign:
thisNumber = 12
Try to use descriptive names for your variables—something like firstPage or
corporateLogo, rather than x or c. While it will take a little more time to type the
longer names, using them will make your scripts much easier to read. The length of a
variable’s name has no effect on the execution speed of your script, so use descriptive
names. You can also give your variable names a standard prefix so that they’ll stand out
from the objects, commands, and keywords of your scripting system. Variable names
must be a single word, but you can use internal capitalization (such as myFirstPage)
or underscore characters (
my_first_page) to create more readable names. Variable
names cannot begin with a number, and they can’t contain punctuation or quotation
marks.
Properties
Both AppleScript and Visual Basic allow you to define properties for your scripts. Script
properties are much like variables, but with additional features and requirements specific
to each language. Since the meaning and usage of script properties differs so greatly
Operators Scripting concepts22
between AppleScript and Visual Basic, please consult the bibliography for appropriate
language references.
Operators
Operators perform calculations (addition, subtraction, multiplication, and division) on
variables or values and return a result. For example:
docWidth/2
would return a value equal to half of the content of the variable docWidth. So if
docWidth contained the number 20.5, the value returned would be 10.25.
You can also use operators to perform comparisons (equal to, not equal to, greater than,
or less than). For example:
docWidth > docHeight
Would return the value true if docWidth is greater than docHeight, or false, if it
is not.
Some operators differ between AppleScript and Visual Basic. For example, AppleScript
uses the non-equality symbol (
the greater and less than symbols juxtaposed:
Both scripting systems use the ampersand (
strings.
"Pride " & "and Prejudice."
would return the string “Pride and Prejudice.”
≠, use Option- = from keyboard), while Visual Basic uses
<>.
&) as the concatenation operator to join two
Commands and methods
If objects are “nouns” and properties are “adjectives” in our scripting systems, then
commands (AppleScript) or methods (Visual Basic) are the “verbs”—they’re the parts of
the script that make things happen. The type of the object you’re working with determines
which methods you can use to manipulate it.
In AppleScript, use the make command to create new objects, the set command to
assign object references to variables and to change object properties, and the
command to retrieve objects and their properties.
Visual Basic
In Visual Basic, use the Add method to create new objects, the Set statement to assign
object references to Visual Basic variables or properties, the assignment operator (
to retrieve and change object properties.
get
= )
Conditional statements
If you could speak to Illustrator in the course of a work session, you might say, “If the
selected object is a path, then set its stroke width to 12 points.” Conditional statements
make decisions—they give your scripts a way to evaluate something (the color of the
selected object, or the number of color swatches in the document, or the date) and then
act according to the result. Most conditional statements start with the word
scripting systems.
The following examples check the number of currently open documents. If no documents
are open, the scripts display a messages in a dialog box.
if in both
Control structures Scripting concepts24
AppleScript
tell application "Adobe Illustrator 10"
activate
set documentCount to count every document
if documentCount = 0 then
display dialog "No Illustrator documents are open!"
end if
end tell
Visual Basic
Private Sub Command1_Click()
Dim documentCount as long
Dim appRef As New Illustrator.Application
documentCount = appRef.Documents.Count
If documentCount = 0 then
MsgBox "No Illustrator documents are open!"
End If
End Sub
Control structures
If you could talk to Illustrator, you might say, “Repeat the following procedure twenty
times.” In scripting terms, this sort of direction is called a “control structure.” Control
structures provide for repetitive processes , or “loops.” The idea of a loop is to repeat some
action over and over again, with or without changes each time through the loop, until
some condition is met.
Both AppleScript and Visual Basic have a variety of different control structures to choose
from. The simplest form of a loop is one that repeats some series of script operations a
set number of times.
AppleScript
repeat with counter from 1 to 20
display dialog counter
end repeat
Visual Basic
For counter = 1 to 20
MsgBox counter
Next
A more complicated type of control structure includes conditional logic, so that it loops
while or until some condition is true or false.
set flag to (button returned of display dialog "Quit?") = "Cancel"
end repeat
repeat until flag = true
set flag to (button returned of display dialog "Quit?") = "OK"
end repeat
Visual Basic
Do While flag = false
flag = (MsgBox ("Quit?", vbOKCancel)) = vbCancel
loop
Do Until flag = true
flag = (MsgBox ("Quit?", vbOKCancel)) = vbOK
loop
Handlers and subroutines
Handlers (in AppleScript) or subroutines (in Visual Basic) are scripting modules you can
refer to from within your script. Handlers and subroutines are ways to re-use parts of
scripts. Typically, you send one or more values to a handler (or subroutine), and it returns
one or more values. Handlers (and subroutines) can be used for performing conversions
from one measurement system to another, or f or calculating the geometric center point of
an object from its geometric bounds.
There’s nothing special about the code used in subroutines and handlers—they are
simply conveniences that save you from having to type the same lines of code over and
over again in your script. If you find yourself typing or pasting the same lines of code into
several different places in a script, you’ve identified a good candidate for a subroutine or
handler.
Handlers and subroutines Scripting concepts26
AppleScript
-- Calculate the geometric center of a selected art item
-- Assumes you have a single art item selected
tell application "Adobe Illustrator 10"
-- Get the selection from the current document
set selectedItems to selection
(* Make sure there is a selected item, and that the selection is not
text *)
if selectedItems ≠ {} and class of selectedItems ≠ text then
-- Get the first item from the list and get it bounds
set firstItem to item 1 of selectedItems
set itemBounds to geometric bounds of firstItem
end if
end tell
set itemCenter to GetItemCenter(itemBounds)
display dialog "Center x:" & item 1 of itemCenter & ", y:" & item 2 of
itemCenter
-- This handler finds the center of an item given its bounds
on GetItemCenter(itemBounds)
-- Assign coordinates from the bounds to individual variables
set {itemLeft, itemTop, itemRight, itemBottom} to itemBounds
-- Calculate the center position
set xCenter to (itemLeft + itemRight) / 2
set yCenter to (itemTop + itemBottom) / 2
return {xCenter, yCenter}
end GetItemCenter
Visual Basic
Private Sub Command1_Click()
' Calculate the geometric center of a selected art item
' Assumes you have a single art item selected
Dim appRef As New Illustrator.Application
Dim selectedObjects As Variant
Dim objectBounds As Variant
Dim objectCenter As Variant
If appRef.Documents.Count > 0 Then
Adobe Illustrator 10 Scripting Guide Testing and troubleshooting27
selectedObjects = appRef.Documents(1).Selection
If TypeName(selectedObjects) = "Variant()" Then
objectBounds = selectedObjects(0).GeometricBounds
objectCenter = GetItemCenter(objectBounds)
MsgBox ("Center x:" & objectCenter(0) & ", y:" &
objectCenter(1))
End If
End If
End Sub
' The following lines define the function
Function GetItemCenter(sourceBounds As Variant) As Variant
Dim left As Single
Dim top As Single
Dim right As Single
Dim bottom As Single
Dim xCenter As Single
Dim yCenter As Single
left = sourceBounds(0)
top = sourceBounds(1)
right = sourceBounds(2)
bottom = sourceBounds(3)
GetItemCenter = Array(xCenter, yCenter)
End Function
Testing and troubleshooting
Both scripting environments provide tools for monitoring the progress of your script while
it is running—which make it easier for you to track down any problems your script might
be encountering or causing.
AppleScript
While the basic syntax of your script will be checked when compiled, it is possible to
create and compile scripts in AppleScript that will not run properly. The Script Editor
doesn’t have extensive debugging tools, but it does have the an Event Log window.
Handlers and subroutines Testing and troubleshooting28
To watch the commands your script sends and the results it receives, choose Controls >
Open Event Log. The Script Editor displays the Event Log window. Check the Show
Events and Show Ev ents Results options at the top of the Event Log windo w and then run
your script. As the script executes, you’ll see the commands sent to Illustrator, and
Illustrator’s responses.
In addition, the Result window (choose Controls > Show Result) will display the value
from the last script statement evaluated. Third-party editors offer additional debugging
features.
Visual Basic
In Visual Basic, you can stop your script at any point, or step through your script one line
at a time. To stop your script at a particular line, select that line in your script and choose
Adobe Illustrator 10 Scripting Guide About error handling29
Debug > Toggle Breakpoint. When you run the script, Visual Basic will stop at the
breakpoint you hav e set. Choose Debug > Step Into (or press F8) to execute the ne xt line
of your script, or choose Run > Start (or press F5) to continue normal execution of the
script. You can also observe the values of variables defined in your script using the Watch
window—a very valuable tool for debugging your scripts. To view a variable in the Watch
window, select the variable and choose Debug > Quick Watch. Visual Basic displays the
Quick Watch dialog box. Click the Add button. Visual Basic displays the Watch window.
If you have closed the Watch window, you can display it again by choosing View > Watch
Window.
About error handling
Imagine that you’ve written a script that formats the current text selection. What should
the script do if the current selection turns out not to be text at all, but a path item? “Error
handling” is code you add to your script to respond to conditions other than those you
expect it to encounter.
Handlers and subroutines About error handling30
If you have complete control over the situations in which your script will run, there’s no
need for you to worry about error handling. If not, however, you’ll have to add some error
handling capabilities to your script. The following examples show how to how you can
stop a script from executing when a specific file cannot be found.
AppleScript
--Store a reference to the fifth path item of the document in a variable
--If the object does not exist in the current document, display a message
tell application "Adobe Illustrator 10"
activate
try
set itemCount to count of path items in current document
set fifthItem to path item 5 of current document
' Store a reference to the fifth path item of the document in a
' variable. If the object does not exist in the current document,
' display message.
Dim appRef As New Illustrator.Application
Dim docRef As Illustrator.Document
Dim aiObject As Illustrator.PathItem
Dim numObjects As Single
Dim errorMessage As String
Set docRef = appRef.ActiveDocument
numObjects = docRef.PathItems.Count
On Error GoTo DisplayError
Set aiObject = docRef.PathItems(5)
Exit Sub
DisplayError:
errorMessage = "Couldn't locate 5th path object - Only "
errorMessage = errorMessage & numObjects & " objects."
MsgBox errorMessage
End Sub
3
Scripting Illustrator
At this point, you should have a good idea of what scripting is and how it works. We are
ready to begin looking at scripting Adobe Illustrator.
Looking at Illustrator’s objects and commands
While the objects and commands available in Illustrator are all documented in this guide,
you can also view them from inside your scripting system.
AppleScript
To view Illustrator’s AppleScript dictionary:
1. Start Illustrator and then your script editor. Apple’s Script Editor comes with all
Macintosh systems. If you can’t find the Script Editor application, you’ll have to
reinstall it from your Mac OS System CD.
2. In Script Editor, choose File > Open Dictionary. Script Editor displays an Open
File dialog.
3. Find and then select the Illustrator application and click the OK button. Script
Editor displays a list of Illustrator’s objects and commands. You’ll also be able to
see the properties and elements associated with each object, as well as the
parameters for each command.
31
Looking at Illustrator’s objects and commandsScripting Illustrator32
Adobe Illustrator 10 Scripting Guide Looking at Illustrator’s objects and commands33
Visual Basic
To view Illustrator’s type library:
1. In any Visual Basic project, choose Project > References. Visual Basic displays
the References dialog box. If you are using a built-in editor in a VBA application,
choose Tools > References.
2. Turn on the “Adobe Illustrator 10.0 Type Library” option from the list of available
references and click the
available references, reinstall Illustrator with your scripting plugins.
OK button. If the library does not appear in the list of
4. Choose “Illustrator” from the list of open libraries shown in the top-left pull-down
menu. Visual Basic displays the classes and the members of those classes in
the Object Browser window.
The applicationScripting Illustrator34
5. Click an object class or class member. Visual Basic displays more information
about the object in the frame at the bottom of the Object Browser window.
The application
In all of your scripts, in either AppleScript or Visual Basic, the first thing you refer to is the
application. As w e’ re concerned here with Illustrator 10, that is the application your scripts
will target.
Your first Illustrator script
The traditional first project in any programming language is to displa y the message “Hello
World!” In this example, we’ll create a new Illustrator document, then add a text art item
containing this message.
Creating an AppleScript script
To create an AppleScript script follow these steps:
1. Locate and open Script Editor.
2. Enter the following script. The lines preceded by
ignored by the scripting system. They’re included to document the operation of
the script. As you look through the script, you’ll see how we create, then
-- are comments, and will be
Adobe Illustrator 10 Scripting Guide Your first Illustrator script35
address, each object in turn. The AppleScript command tell indicates the
object that will receive the next message we send.
-- Send the following commands to Illustrator
tell application "Adobe Illustrator 10"
-- Create a new document with the string "Hello World"
set docRef to make new document
set textRef to make new text art item in docRef ¬
with properties {contents: "Hello World!", position:{200,
200}}
end tell
3. Run the script. Illustrator will create a new document, add a text art item at
position (200, 200) and set the text to “Hello World!”.
Creating a Visual Basic script
To create a Visual Basic script follow these steps:
1. Start Visual Basic and create a new project. Add the “Adobe Illustr ator 10.0 Type
Library” reference to the project, as shown earlier. If you are using a built-in
editor in a VBA application, skip to step 4.
2. Add a form to the project.
3. Create a new button on the form. Double-click the button to open the Code
window.
Your first Illustrator scriptScripting Illustrator36
4. Enter the following code. The lines preceded by’ (single-quote) are
comments, and will be ignored by the scripting system. They’re included to
describe the operation of the script. As you look through the script, you’ll see
how we create, then address each object in turn.
'Hello World! Script
Private Sub Command1_Click()
Dim appRef As New Illustrator.Application
Dim documentRef As Illustrator.Document
Dim sampleText As Illustrator.TextArtItem
'Create a new document and assign it to a variable
Set documentRef = appRef.Documents.Add
'Create a new text art item and assign it to a variable
Set sampleText = documentRef.TextArtItems.Add
'Set the contents and position of the TextArtItem
sampleText.Position = Array(200, 200)
sampleText.Contents = "Hello World!"
End Sub
5. Save the form.
6. Start Illustrator.
7. Return to Visual Basic and run the program. If you created a form, click the
button you created earlier.
8. Run the script. Illustrator will create a new document, add a text art item at the
specified position, and set the text to “Hello World!”.
VBScript
You don't need to use Visual Basic to run scripts on Windows. Another way to script
Illustrator is to use a VBA editor (such as the one that is included in Microsoft Word) or to
use Windows Scripting Host.
Windows Scripting Host is part of Windows2000. If you don't ha v e Windows2000, y ou can
download Windows Scripting Host from : http://msdn.microsoft.com/scripting/
Both VBA and Windows Scripting Host use VBScript as their scripting language. The
syntax for VBScript is very similar to the Visual Basic syntax. The three main differences
relating to the scripts shown in this guide are:
Adobe Illustrator 10 Scripting Guide Your first Illustrator script37
• VBScript is not as strongly typed as Visual basic. In Visual Basic you say:
Dim aRef as Illustrator.PathItem
in VBScript you say:
Dim aRef
For VBScript simply omit the "as X" part
• VBScript does not support the "as New Illustrator.Application" form.
In Visual Basic you retrieve the Application object as:
Dim appRef as New Illustrator.Application
In VBScript you write the following to retrieve the Application object:
Dim appRef
Set appRef = CreateObject("Illustrator.Application")
• VBScript does not support enumerations. Here’s an example of how to close the
frontmost document without saving. In Visual Basic:
Dim appRef As New Illustrator.Application
appRef.ActiveDocument.Close (aiDoNotSaveChanges)
In VBScript you must use integer values instead of the enumeration. (See
“Enumerations reference” at the end of Chapter 5 to find the values that correspond
to the various enumerations.) The corresponding VBScript is:
Dim appRef
Set appRef = CreateObject("Illustrator.Application")
appRef.ActiveDocument.Close ( 2 )
Here is an example of Hello World! for VBScript:
'Hello World! script
Dim appRef
Dim documentRef
Dim SampleText
Adding features to “Hello World”Scripting Illustrator38
'Create a new document and assign it to a variable
Set appRef = CreateObject("Illustrator.Application")
Set documentRef = appRef.Documents.Add
'Create a new text art item and assign it to a variable
To run this script create a text file and copy the script into it. Save the file with a
"vbs" extension. If you have Windows Scripting Host installed, you can double-click
on the file to execute the script.
Another way to e x ecute the script is to choose File>Scripts>Browse from the Scripts
menu in Illustrator and select the file.
Adding features to “Hello World”
Next, let’ s create a ne w script that makes changes to the Illustrator document y ou created
with your first script. Don’t worry if you’ve closed the Illustrator document without saving
it—just run your script to create a new one.
Our second script will demonstrate how to:
1. Get the active document.
2. Get the width of the active document.
3. Resize the text art item to match the document’s width.
Adding features to the AppleScript script
To create the enhanced script follow these steps:
1. Choose File > New in Script Editor to create a new script.
2. Enter the following code.
Adobe Illustrator 10 Scripting Guide Adding features to “Hello World”39
tell application "Adobe Illustrator 10"
-- current document is always the active document
set docRef to the current document
set docWidth to the width of docRef
-- resize the text art item to match the page width
set width of text art item 1 of docRef to docWidth
-- alternatively, one can reference the item directly, as follows:
set width of text art item 1 of current document to docWidth
end tell
3. Save the script.
4. Make sure you have the document created by the original “Hello World” script
open, then run the script.
Adding features to the Visual Basic script
To create the enhanced script follow these steps:
1. Open the project you created for the “Hello World” script, if it’s not already open.
2. Add a new button to the form.
3. Double-click the button to display the Code window, then enter the following
code.
Private Sub Command1_Click()
Dim appRef As New Illustrator.Application
Dim documentRef As Illustrator.Document
Dim sampleText As Illustrator.TextArtItem
Dim documentWidth As Single
' Get the active document
Set documentRef = appRef.ActiveDocument
documentWidth = documentRef.Width
Set sampleText = documentRef.TextArtItems(1)
' Resize the TextArtItem to match the document width
5. Open the original document you created using the “Hello World” script, then
return to Visual Basic and run the script.
Measurement unitsScripting Illustrator40
6. Click the button you created in Step 2.
Measurement units
Illustrator always uses points as the unit of distance measurement. One inch is equal to
72 points. Even if you change the current document ruler’s units of measurement,
Illustrator will still use points when communicating with your scripts. Your scripts will need
to perform any unit conversions needed to represent your measurements as points. For
example, to move the current selection to a position 2 inches to the right of and 6 inches
above its current position, you’d use the following script in AppleSccript:
tell application "Adobe Illustrator 10"
(* first, manually select the text art item from the previous e xercise or use AppleScript to make the
selection *)
set selection to text art item 1 of current document
(* There are 72 points per inch. To translate an item by 2 inches to the right and 6 inches to
the left, multiply by 72 translate selection delta x (2 * 72) delta y (6 * 72) *)
end tell
and this script for Visual Basic:
Private Sub Command1_Click()
Dim appRef As New Illustrator.Application
Dim documentRef As Illustrator.Document
Dim selectedObjects As Variant
Dim objectRef As Variant
Set documentRef = appRef.ActiveDocument
selectedObjects = documentRef.Selection
If TypeName(selectedObjects) = "Variant()" Then
For Each objectRef In selectedObjects
There are 72 points per inch, so the following will move the
'object 2" to the right and 6" up
objectRef.Translate 144, 226
Next
End If
End Sub
If your script depends on adding, subtracting, multiplying, or dividing specific
measurement values for units other than points, the script will need to convert between
the units numerically. For e xample, to use English measurements such as inch values for
coordinates or measurement units, your script will need to multiply all inch values b y 72 to
convert to points, since there are 72 points in an inch. To use metric measurements such
as centimeters, you will need to multiply all centimeter values by 28.346, since there are
28.346 points in a centimeter.
Unit conversion to points
This table displays the conversion formulae for various units of measurement:
Illustrator uses simple two-dimensional geometry to record the position of objects in a
document. The coordinates used in Illustrator are the same as the “traditional” geometric
coordinate system you learned about in school. The horizontal component of a coordinate
pair (or “point”) is referred to as “x” and the v ertical position is denoted by “y”. You can see
these coordinates in the Info palette when you select or create an object in Illustrator.
Illustrator scripting uses a special class called
fixed point to receive and return
coordinate data. The fixed point is represented as a list of two items in AppleScript and as
a variant array of two elements in Visual Basic. In both cases, the first item is the
horizontal or “x” coordinate, while the second item is the vertical or “y” coordinate. The
position (Position in Visual Basic) of objects on a document are described with a
fixed point.
Fixed points
In AppleScript, a fixed point with an x coordinate of 5.0 and a y coordinate of 10.2 is
represented as a list that looks like this:
{5.0, 10.2}
CoordinatesScripting Illustrator42
In Visual Basic, a fixed point with an x coordinate of 5.0 and a y coordinate of 10.2 is
represented as a variant array that looks like this:
Array (5.0, 10.2)
Note that if you declare an array to hold the values of a point, you should pass 1 as the
dimension, since Visual Basic uses index position 0 for the first item in an array.
Dim aPoint(1) As Single
aPoint(0) = 5.0
aPoint(1) = 10.2
Zero point
The zero point (0, 0) for coordinate numbering in Illustrator is in the lo wer left corner of the
document. On the horizontal axis, coordinates to the right of the ruler’s zero point are
positive numbers, and on the vertical axis, coordinates above the zero point are positive.
page origin (PageOrigin in Visual Basic) of a document defines the lo wer left
The
corner of the printable region of the document as a fixed point.
Fixed rectangle
To work with rectangular coordinates where there are a pair of x and y values, Illustrator
uses the special class called a
with four items in AppleScript and a variant array with four elements in Visual Basic. The
coordinates of a fixed rectangle in order are: left, top, right, bottom.
fixed rectangle. This class is comprised of a list
In AppleScript, a fixed rectangle with a left-top corner of (5.0, 200.0) and a right-bottom
corner of (100.0, 20.0) is represented by a list that looks like this:
{5.0, 200.0, 100.0, 20.0}
In Visual Basic, a fixed rectangle with a left-top corner of (5.0, 200.0) and a right-bottom
corner of (100.0, 20.0) is represented by a variant array that looks like this:
Array (5.0, 200.0, 100.0, 20.0)
Alternatively, you can define your array and assign values to its elements like this:
Dim boundsRect(3) As Single
boundsRect(0) = 5.0
boundsRect(1) = 20.0
Every object, or page item, in a document has a position described by a fixed point and a
width and height. The maximum value allowed for the width or height of a page item is
16348 points.
position
Position
control bounds
ControlBounds
visible bounds
VisibleBounds
geometric bounds
GeometricBounds
page origin
PageOrigin
(0,0)
Detail
Every page item also has three properties that describe the object’s overall extent using
fixed rectangles. The
geometric bounds (GeometricBounds in Visual Basic) of a
page item are the rectangular dimensions of the object excluding stroke width. The
visible bounds (VisibleBounds in Visual Basic) of a page item are the
dimensions of the object including any stroke widths. Finally, the
(
ControlBounds in Visual Basic) define the rectangular dimensions of the object
including in- and out- control points.
control bounds
Object references
The different scripting languages take different approaches to object references.
Object referencesScripting Illustrator44
Object references in AppleScript
In AppleScript, Illustrator returns object references by index position or name. For
example, a ref erence to the first path in la yer 2 would be:
of document 1
. An object’s index position may change when other objects are
path item 1 of layer 2
created or deleted. For example, when a new path item is created on layer 2, it will
become
path item 1 of layer 2 of document 1. This new object displaces
our original path item, forcing it to index position 2. Therefore, any references made to
path item 1 of layer 2 of document 1 will refer to the ne w object. Consider
the following sample script.
-- Make 2 new objects and try to select both
tell application "Adobe Illustrator 10"
set newDocument to make new document
set rectPath to make new rectangle in newDocument
set starPath to make new star in newDocument
set selection of newDocument to {rectPath, starPath}
end tell
This script will not select both the rectangle and the star. It will select only the star. Try
running the script with the Event Log window open to observe the references returned
from Illustrator for each of the consecutive
commands return the same object reference:
document 1
.
make commands. You will notice that both
path item 1 of layer 1 of
Therefore, the script really says:
set selection of document 1 to ¬
{path item 1 of layer 1 of document 1, path item 1 of layer 1 of
document 1}
Instead, you might try referencing the objects by name, such as:
tell application "Adobe Illustrator 10"
set newDocument to make new document
make new rectangle in newDocument with properties {name:"rectangle"}
make new star in newDocument with properties {name:"star"}
set selection of newDocument to ¬
{path item "rectangle" of newDocument, path item "star" of
newDocument}
end tell
Adobe Illustrator 10 Scripting Guide Object containment: document vs. layer45
This example illustrates the need to uniquely identify objects. It is recommended that you
assign names to objects you need to access at a later time, as there’s no guarantee
you’re accessing the objects you expect when accessing them by index.
Object references in Visual Basic
Object references in Visual Basic are dynamic and remain valid until disposed.
To create a star and rectangle, and then select them, you could do:
Private Sub Command1_Click()
'Make 2 new objects and select both
Dim appRef As New Illustrator.Application
Dim pathItemsRef As Illustrator.PathItems
Dim rectPath As Illustrator.PathItem
Dim starPath As Illustrator.PathItem
Set pathItemsRef = appRef.ActiveDocument.ActiveLayer.PathItems
Set rectPath = pathItemsRef.Rectangle(50, 70, 100, 200)
Set starPath = pathItemsRef.Star(40, 70, 200, 110, 5, False)
Dim pathSelection(1) As Variant
Set pathSelection(0) = rectPath
Set pathSelection(1) = starPath
appRef.Selection = pathSelection
End Sub
Object containment: document vs. layer
In Illustrator, all artwork objects are contained in layers, groups or compound paths that
are themselves contained in a document. The index of an object in a layer or group
indicates the object’s position in the stacking order of the layer or group. This means that
page item 1 of layer 1, or Layers(1).PageItems(1) in Visual Basic, is
the frontmost object in a document, while
Layers(1).PageItems(2) in Visual Basic, lies directly behind in the stacking order .
Note that if you delete all the layers in a document, the document is left with the default
empty layer called
When you refer to an object in your document, you can reference it directly as part of the
document or by its complete containment hierarchy, including layers and any group or
compound path if valid. When y ou ref er to objects contained by the document directly, you
can access the entire flattened contents of the document, without regard to the
Layer 1.
page item 2 of layer 1, or
Object containment: document vs. layerScripting Illustrator46
containment of objects within layers, groups, or compound paths. All objects, whether or
not they are contained in groups or compound paths, are returned as individual objects
contained by the document. The following scripts demonstrate how to reference an object
as part of a document.
In AppleScript:
-- Get reference for first page item of document 1
tell application "Adobe Illustrator 10"
set pageItemRef to page item 1 of document 1
end tell
In Visual Basic:
Private Sub Command1_Click()
'Get reference for first page item of document 1
Dim appRef As New Illustrator.Application
Dim documentRef As Illustrator.Document
Dim pageItemRef As Illustrator.PageItem
Set documentRef = appRef.ActiveDocument
Set pageItemRef = documentRef.PageItems(1)
End Sub
In the scripts below, the variable pageItemRef will not necessarily refer to the same
object as the above script since this script includes a reference to a layer:
In AppleScript:
-- Get reference for first page item of layer 1 of document 1
tell application "Adobe Illustrator 10"
set pageItemRef to page item 1 of layer 1 of document 1
end tell
In Visual Basic:
Private Sub Command1_Click()
'Get reference for first page item of document 1
Dim appRef As New Illustrator.Application
Dim documentRef As Illustrator.Document
Dim pageItemRef As Object
Adobe Illustrator 10 Scripting Guide Working with selections47
Set documentRef = appRef.ActiveDocument
Set pageItemRef = documentRef.Layers(1).PageItems(1)
End Sub
Working with selections
There are instances where you will want to write scripts that act upon the currently
selected object(s). For example, y ou might w ant to ha v e a script that applies f ormatting to
selected text, or changes a selected path’s shape. To do this, you need to know the
number of selected objects and the type of each object. The following scripts work with
the current selection.
In AppleScript:
--selection sorter
tell application "Adobe Illustrator 10"
set selectedObjects to selection
try
if selectedObjects is {} then
display dialog "No objects are selected"
else
if class of selectedObjects = list and ¬
(count of items in selectedObjects > 1) then
--selection contains more than one object.
else
--a single object is selected. What is it?
set selectedObjectClass to class of selectedObjects
if selectedObjectClass = list then ¬
set selectedObjectClass to class of item 1 of
selectedObjects
if selectedObjectClass = text then
-- text is selected
else
-- determine what type of object is selected.
if selectedObjectClass = path item then
-- object is a path item
else if selectedObjectClass = compound path item then
-- object is a compound path
else if selectedObjectClass = raster item then
-- object is a raster image
else if selectedObjectClass = placed item then
-- object is a placed image
else if selectedObjectClass = mesh item then
-- object is a mesh
Working with selectionsScripting Illustrator48
else if selectedObjectClass = text art item then
-- object is a text art item
else if selectedObjectClass = plugin item then
-- object is a plugin art item
else if selectedObjectClass = path point then
-- object is a point of a path
else if selectedObjectClass = group item then
-- object is a group
end if
end if
end if
end if
on error errString
display dialog errString
end try
end tell
In Visual Basic:
'Selection sorter
Private Sub Command1_Click()
Dim appRef As New Illustrator.Application
Dim documentRef As Illustrator.Document
Set documentRef = appRef.ActiveDocument
selectedObjects = documentRef.Selection
If TypeName(selectedObjects) = "String" Then
'text is selected
Else
'Is anything selected?
If selectedObjects = Empty Then GoTo noSelection
For Each artObject In selectedObjects
selectedObjectClass = TypeName(artObject)
Adobe Illustrator 10 Scripting Guide Working with paths49
Select Case selectedObjectClass
'Something is selected, let’s find out what it is.
Case "PathItem"
'Object is a path item
Case "CompoundPathItem"
'Object is a compound path
Case "RasterItem"
'Object is a raster image
Case "PlacedItem"
'Object is a placed image
Case "MeshItem"
'Object is a mesh
Case "TextArtItem"
'Object is a text art item
Case "PluginItem"
'Object is a plugin art item
Case "PathPoint"
'Object is a point of a path
Case "GroupItem"
'Object is a group of objects
End Select
Next
End If
Exit Sub
noSelection:
MsgBox "Select an object and try again."
End Sub
Working with paths
Path items include all artwork that is comprised of paths, including rectangles, ellipses,
polygons, as well as freeform paths. In Illustrator, every path is comprised of a series of
points. Path items, as well as path points, can be created and manipulated from a script.
Every aspect of a path point can be accessed from scripting, including the anchor
point
direction
(
RightDirection in Visual Basic) properties. Refer to the Illustrator Plug-in Software
Development Kit Function Reference for more information on working with paths, bezier
curves and path points. This document is available in Adobe Acrobat® Portable
Document Format (PDF) as part of the Illustrator Software Development Kit (SDK). The
(AnchorPoint in Visual Basic) and both control points, known as the left
(LeftDirection in Visual Basic) and right direction
Working with colorScripting Illustrator50
SDK can be downloaded from the Adobe Solutions Network web site (http://
partners.adobe.com/asn/developer/sdks.html).
path point
PathPoint
path item
PathItem
right direction
RightDirection
anchor
Anchor
left direction
LeftDirection
Working with color
Swatches can be created and manipulated from your scripts. You can also create new
patterns, gradients and spot colors from scripts. Just as in the user interf ace , percentages
(0.0 through 100.0) are used to specify grayscale , individual CMYK values and spot tints.
The range 0.0 to 255.0 is used for the individual RGB color values. Special attention
should be paid to working with CMYK and RGB color values. Illustr ator 10 supports only a
single color model within each document, either CMYK or RGB. When you specify a
CMYK color value in a document that uses the RGB color model, Illustrator will convert
the values to RGB and return an RGB color, and vice-versa when specifying RGB colors
in a CMYK document. However, there is some data loss during this conversion. Refer to
the “Applying Color” chapter in the Adobe Illustrator User Guide for more information on
working with color.
Working with symbols
Symbols are art objects that are stored in the Symbols palette and applied to
documents. You can create, delete and duplicate symbols. When you create
symbols, Illustrator adds them to the Symbols Palette for the target document.
When you save the document, Illustrator also saves the symbols you created and
used in the document.
Working with symbol items
Symbol items refer to instances of symbols in a document. You can create, delete, and
duplicate symbol
items. They are “link ed” to the symbol definition such that changing the
Working with text artScripting Illustrator51
definition of a symbol causes all of the instances of the symbol to change as well. Symbol
items are Illustrator art objects and therefore can be treated as other art objects or page
items. In other words, you can rotate, resize, select, lock, hide and perform other
operations on them.
Working with text art
There are three types of text art items in Adobe Illustrator: point text, path text, and area
text. The
type of the text art item. While all three kinds of text art have some common
characteristics, such as an orientation, each kind of text art also has unique
characteristics.
kind property (Kind in Visual Basic) of a te xt art item is used to determine the
All three kinds of text art have least one text path associated with them. A
(
TextPath in Visual Basic) is not the same as a path art item, but defines the text art
item’s position on the artboard and its orientation (horizontal or vertical). Point text is
defined completely by the properties of its text art item and associated text path.
For path and area text, text paths are associated with normal path art items. These path
art items can be accessed and manipulated to modify the appearance of the associated
text art item. If the text art item is path text, it will have a
(
TextPathOffset in Visual Basic), which indicates where on the path object the text
begins.
All text art objects also have at least one line of text depending on the object’s geometry.
line of text (TextLine in Visual Basic) is all of the characters that fit on a single line
A
in the text art item. Text art will have multiple te xt lines if it contains hard line breaks or its
characters flow to a new line because they do not fit in the width of the text art. Unlike
characters, paragraphs and w ords , lines can only be created by the Illustrator application.
Refer to the “Using T ype” chapter in the Adobe Illustrator User Guide for more information
on working with text art.
text path offset property
text path
Transformation matricesScripting Illustrator52
Transformation matrices
Thanks to the matrix class and the many commands that support matrices, you have
access to the power of geometric transformation matrices. Transformation matrices are
mathematical concepts originating in the field of linear algebra. Geometric manipulations
like scaling, rotating and moving can all be described using transformation matrices.
Matrices are the basis of how Illustrator internally performs a user’s request to scale,
rotate or move an object. Using the command set available to create, concatenate, and
apply matrices, you can transform objects in documents with programmatic precision and
control. By concatenating a series of rotation, translation and scaling matrices together
and applying the resulting matrix, you can perform a large series of geometric
transformations in record speed. The following examples demonstrate how to combine
multiple modifications in a single matrix and then apply the matrix to every object in a
document.
Refer to the Illustrator Plug-in Software Development Kit Function Reference for more
information on working with transformation matrices.
Using a matrix in an AppleScript script
(* This script gets the identity matrix, combines it with a
rotation matrix and a scale matrix and then applies the
resulting matrix to all page items. *)
tell application "Adobe Illustrator 10"
set transformationmatrix to get identity matrix
set transformationmatrix to concatenate rotation matrix ¬
transformationmatrix angle 45.0
set transformationmatrix to concatenate scale matrix ¬
transformationmatrix horizontal scale 60
transform every page item of document 1 using transformationmatrix
end tell
Using a matrix in a Visual Basic script
'This example shows how to apply 2 transformations to all art in
'a document using the matrix command. This is more efficient than
'performing these transformations one at a time
Private Sub ApplyMatrix_Click()
Dim appRef As New Illustrator.Application
Dim moveMatrix As Illustrator.Matrix
Dim totalMatrix As Illustrator.Matrix
Working with variables and datasetsScripting Illustrator53
'Move art half an inch to the right and 1.5 inch up on the page
Set moveMatrix = appRef.GetTranslationMatrix(72# * 0.5,
72# * 1.5)
'Add a rotation to the translation. We rotate 10 degrees counter clockwise
Set totalMatrix = appRef.ConcatenateRotationMatrix(moveMatrix,
10)
'Apply the transformation to all art in the document
Dim frontDocument As Illustrator.Document
Dim artItem As Illustrator.PageItem
Set frontDocument = appRef.ActiveDocument
For Each artItem In frontDocument.PageItems
artItem.Transform totalMatrix
Next
End Sub
A matrix object in Illustrator is comprised of 6 properties. In AppleScript, these properties
mvalue_a, mvalue_b, mvalue_c, mvalue_d, mvalue_tx, and
are:
mvalue_ty. In Visual Basic, these properties are: MValueA, MValueB, MValueC,
MValueD, MValueTX, and MValueTY. By e xperimenting with the matrix concatenation
commands in both AppleScript and Visual Basic, you can discover how to construct
matrices that can applied to perform movement (also called translation), rotation, scaling,
skewing and other transformations. See the script e xamples for the matrix commands for
working samples.
Working with variables and datasets
By creating dynamic objects, you can create data-driven graphics. You can define
dynamic objects by using
to these variables. V ariables are document-le v el objects; theref ore , y ou create them in the
document object. You can add and delete variables to/from a script by using the
Remove/ RemoveAll methods (Visual Basic) or make and delete (AppleScript).
Datasets
Datasets are closely related to variables in that a dataset collects variables and their
associated dynamic data into a single object. The
is the object that corresponds to an
document class provides methods so you can create, update and delete datasets.
variables. In scripting, the variable class corresponds
Add and
DataSet (VB) / dataset (AS) class
AI DataSet. The dataset collection in the
Launching and quitting Illustrator from a scriptScripting Illustrator54
Launching and quitting Illustrator from a script
Your scripts can control the activation and quitting of the Illustrator application. Take note
of the particular comments below for your scripting system.
Launching and quitting from AppleScript
Use the activate and quit commands to control Illustrator’s run state. The
activate command will bring the Illustrator application to the front if it is not already
the frontmost application. Note that if the clipboard contains data at the time of quitting,
Illustrator may show a dialog asking if the data on the clipboard should be sa v ed for other
applications. You can avoid this dialog by clearing the clipboard with the statement:
set the clipboard to {}
Launching and quitting from Visual Basic
In Visual Basic , the Activate method will bring the Illustrator application to the front if it
is not already frontmost.
Note that if the clipboard contains data at the time of quitting, Illustrator may show a
dialog prompting the user to save the data on the clipboard f or other applications. You can
avoid this dialog by clearing the clipboard with the command:
Clipboard.Clear
Some objects that cannot be created by a script
Following are some objects that cannot be created from a script:
•Art styles
•Brushes
•Graphs
•Mesh art
•Plugin art
•Spirals
User Interaction LevelsScripting Illustrator55
User Interaction Levels
An application will usually present a dialog when it needs to provide feedback or request
information. This is called user interaction, and is useful and expected when you are
directly interacting with the application. On the other hand, when a script is interacting
with an application, an unexpected dialog will bring the execution of the script to a halt
until the dialog is dismissed. This can be a serious problem in an automation environment
where there is typically no one present to deal with dialogs.
The Illustrator 10 application class contains a user interaction level property. By setting
this property a script can control the level of interaction allowed during script execution.
All interaction is normally suppressed in an automation environment, and some
interaction might be useful where scripts are being used in a more interactive fashion.
AppleScript
There are four possible values for the user interaction level property in AppleScript:
•never interactNo interaction is allowed
•interact with selfInteract only with scripts executed from the scripts menu
•interact with localInteract with script executed on the local machine (including self)
•interact with allInteract with all scripts
Using AppleScript, it is possible to send commands from one machine to another. The
four possible values allow you to control interaction based on the source of the script
commands. For example, if the application is acting as a server for remote users, it would
be difficult for a remote user to dismiss a dialog, but it would be no problem for someone
sitting in front of the machine. In this case , an interaction level of ‘interact with local’ would
prevent dialogs from halting remote scripts but would allow dialogs to be presented for
local scripts.
Visual Basic and JavaScript
There are two possible values for the UserInteractionLevel property in Visual Basic:
• aiDontDisplayAlertsNo interaction is allowed
• aiDisplayAlertsInteraction is allowed
The Scripts menuScripting Illustrator56
The Illustrator 10 Windows scripting interface doesn’t support remote script execution so
it doesn’t need to provide values based on where a script is being executed.
The Scripts menu
Illustrator 10’s interface includes a Scripts menu (File>Scripts) which provides quick and
easy access to your scripts. To execute a script from the Scripts menu simply select it in
the menu. The script associated with the selected menu item will be then be executed.
Notes
If there is an error encounter during script execution an error dialog will be displayed
containing the error message returned by the script.
It is not possible to execute scripts that contain the
do script (DoScript in Visual
Basic) command from the Scripts menu. Attempting to do so will result in an error.
Supported scripting languages
The Scripts menu supports AppleScript and JavaScript scripts for Mac OS, and VBScript,
JavaScript, and Visual Basic scripts for Windows.
Script files
For a file to be recognized by Illustrator as a valid script file it must have the correct file
type (Mac OS) or name extension (Mac OS and Windows).
Script T ypeFile Type ExtensionPlatform(s)
AppleScriptcompiled script .scpt Mac OS
JavaScripttext .jsMac OS &
Windows
VBScripttext .vbsWindows
Visual Basicexecutable.exeWindows
Note: For files on Mac OS (9.x and 10.x) it is possible for files to be identified by the
classic file type and creator codes, file name e xtensions, or both. The
only required for AppleScript files which do not have file type information, such as those
installed with Mac OS X. There is no harm in having a name extension when a file has file
type codes.
.scpt extension is
The Scripts menuScripting Illustrator57
Installing scripts
To install a script in the Scripts menu, place it in the Scripts folder (Illustrator
10>Presets>Scripts
name extension, will be displayed in the Scripts menu. Any number of scripts may be
installed in the Scripts menu.
Note: Scripts added to the Scripts folder while Illustrator is running will not appear in the
Scripts menu until the next time you launch Illustrator.
If you have a large collection of scripts you wish to use, you may use sub-folders in the
Scripts folder to help organize the scripts in the Scripts menu. Each subfolder will be
displayed as a separate submenu containing the scripts in that subfolder.
Note: Because of a limitation in the Mac OS, there is a limit of 4 levels of nested subfolders inside the Scripts folder for the Mac OS version of Illustrator.
). The names of the scripts in the Scripts folder, less any file
Executing other scripts
A Browse item is provided at the end of the Scripts menu (File>Scripts>Browse…)
which allows you to execute scripts which are not installed in the Scripts folder. Selecting
the Browse menu item will display a file browser dialog which will allow you to select a
script file for execution. Only files which are of one of the supported file types, as listed in
the Script Files section above will be displayed in the browse dialog. When a script file is
selected in the browse dialog, it will be executed the same way as an installed script.
The Scripts menuScripting Illustrator58
4
AppleScript Reference
This reference section describes the objects and commands in Illustrator’s AppleScript
dictionary. All of the objects in the dictionary are presented alphabetically. Following the
objects is a command reference which lists all of the commands in the Illustrator
dictionary.
Each object listing includes the following:
•Elements that are contained within the object.
•Properties of the object, including value type, read-only status, and an explanation.
•Valid commands.
•Notes to explain special issues.
•Script examples.
Throughout this guide, when an object inherits properties from another object, we repeat
all of the property definitions to maximize usability.
About the script examples
The examples presented here do not necessarily represent the most efficient way to
construct an AppleScript script. All example scripts are written in a manner that should be
easy to read and understand. The samples contain little error checking, and assume that
the proper context exists for the scripts to execute in, i.e., that there is a document open,
items selected, etc. The purpose of these examples is to show you how to address and
work with Illustrator’s objects. These examples may be combined to make scripts with
greater functionality.
67
Illustrator’s object modelAppleScript Reference60
Illustrator’s object model
A good understanding of Illustrator’s object model will impro v e your scripting abilities. This
diagram shows the containment hierarchy of the object model, starting with the
application object. Note that the
additional objects of the same class which can in turn contain additional nested objects.
layer, group item, and all text classes can contain
settingsIllustrator preferencesPreferences for the Illustrator
application.
selectionlist (of object references)All of the currently selected
objects in the active (frontmost)
document. See the note for
more information.
user interaction levelinteract with all/interact
with local/interact with
self/never interact
versionR/OstringThe version of the Adobe
The level of interaction with the
user that is allowed when
handling script commands.
Default: interact with all
Illustrator application.
Valid Commands
•activate
•copy
•cut
•do script
•launch
•paste
•quit
•redraw
Notes
In Illustrator, the application’s selection can be accessed as well as modified. The
selection will contain an empty list,
all objects in the current document, simply set the
reference to an insertion point is returned when there is an active insertion point in the
contents of a text art item. Similarly, a reference to a range of text is returned when
characters are selected in the contents of a text art item.
{}, when there are no selected objects. To deselect
selection to an empty list. A
applicationAppleScript Reference64
Illustrator does not support the select command to change the application’s current
selection. Use
-- Select the first object in the document
tell application "Adobe Illustrator 10"
-- Make sure there is a page item to select
if (document 1 exists) and (page item 1 of document 1 exists) then
set the selection to page item 1 of document 1
end if
end tell
set the selection to in place of select.
Example 1.1
You don’t need to make objects part of the selection to act on them. The selection is most
useful for moving objects to and from the clipboard using the
commands, which act on the current selection. The clipboard can be used effectively for
moving data between applications that do not share common object classes.
Note that Illustrator must be the frontmost application when executing any command that
deals with the clipboard. We bring Illustrator to the front in Example 1.1 by using
AppleScript’s
activate command.
cut, copy and paste
-- Copy the current selection to the clipboard then paste it into a new document
tell application "Adobe Illustrator 10"
-- If Illustrator is not the frontmost application, activate it.
if not frontmost then activate
-- Make sure there is a document to copy from
if (count of documents) > 0 then
-- and a selection to work with
set selectedItems to selection of current document
if selectedItems is not {} then
copy
set colorSpace to color space of current document
make new document with properties {color space:colorSpace}
paste
end if
end if
end tell
Adobe Illustrator 10 Scripting Guide art style, art styles65
art style, art styles
An art style or list of art styles. Each art style defines a set of appearance attributes that
you can apply non-destructively to page items. Art styles are contained in documents.
Properties
Property:R/OValue type:What it is:
best typeR/OclassThe best type for the art style
object's value. Always returns
reference.
classR/OclassThe art style object's class,
which is
containerR/Oobject referenceA reference to the document
that contains this art style.
default typeR/OclassThe default type for the art style
object, which is
reference.
indexR/OintegerThe index of this art style.
nameR/OstringThe name of this art style.
propertiesR/OrecordAll of the properties of this
object returned as a record.
art style.
Valid Commands
•apply
•count
•delete
•exists
Notes
Illustrator’s art styles can be accessed from scripting, but cannot be created.
You cannot delete default art styles.
art style, art stylesAppleScript Reference66
Example 2.1
This example demonstrates how to apply art styles to newly created groups of objects.
Note how this script deals with the fact that applying an art style to a group item does not
apply the art style to the page items contained in the group.
-- Duplicate and group the selected path items, then apply
-- a user-selected art style to the items in the new group
tell application "Adobe Illustrator 10" to ¬
set selectedItems to selection of document 1
-- Check for empty selection or a text selection before proceeding
if selectedItems is not {} and class of selectedItems is not text then
tell application "Adobe Illustrator 10"
-- Create the new group to contain the duplicated items
set groupRef to make new group item at document 1
-- Duplicate the selected items to the new group
set newItemList to duplicate selectedItems to beginning of groupRef
-- Get art style names for display in the choice list
set artStyleNames to name of every art style of document 1
end tell
-- Present dialog and let user choose the style to apply
set styleName to (choose from list artStyleNames ¬
with prompt "Style for selection?") as string
if styleName is not "" then
tell application "Adobe Illustrator 10"
(*
The chosen art style is applied to the list of items returned by the
duplicate command, rather than to the new group itself, because the
apply command works on individual path items, not groups of items
*)
apply art style styleName of current document to newItemList
A character or list of characters in the contents of a text art item.
Elements
Element:Refer to by:
characterindex, before/after, range, test
insertion pointindex, before/after, range, test
lineindex, before/after, range, test
paragraphindex, before/after, range, test
textindex, before/after, range
wordindex, before/after, range, test
Properties
Property:R/OValue type:What it is:
auto kerningbooleanShould the font’ s built-in k erning
rules be used?
baselinerealBottom position of horizontally-
oriented text or left position of
vertically-oriented text.
baseline shiftrealThe baseline offset.
best typeR/OclassThe best type for the character
object's value. Always returns
reference.
character offsetR/OintegerOffset from beginning (in
characters).
classR/OclassThe character object's class,
which is
clippingR/ObooleanIs there a clipping path
associated with the text art item
containing this character?
containerR/Oobject referenceA reference to the text art item
that contains this character.
contentsstringThe contents of the character
directionnormal/rotated/KumiMojiThe direction of characters in a
vertical text block.
evenoddbooleanShould the even-odd rule be
used to determine fills?
fill colorCMYK color info/gray
color info/RGB color info/
spot color info/pattern
color info/gradient color
info
fill overprintbooleanShould art beneath the filled
filledbooleanShould the character’s path be
fontstringThe name of the text face (font).
indexR/OintegerThe index of this character in
kerningrealThe character spacing between
leadingrealThe leading.
lengthR/OintegerLength (in characters).
noteR/OstringA note associated with the text.
propertiesrecordAll of the character’s properties
resolutionrealThe resolution of the path in
scalingfixed pointHorizontal and vertical scaling
sizerealThe font size.
stroke capbutted/rounded/
projecting
The character’s fill color.
character be overprinted?
filled?
the complete string.
characters.
returned in a single record
(properties which are
individually read-only remain so
in this record).
dots per inch.
specified as a point value.
The type of cap on the
character’s stroke.
character, charactersAppleScript Reference72
Property:R/OValue type:What it is:
stroke colorCMYK color info/gray
color info/RGB color info/
spot color info/pattern
color info/gradient color
info
stroke dash offsetrealThe default distance to start the
stroke dasheslist (of real numbers)The lengths for dashes and
stroke joinmitered/rounded/beveled The type of joins in the
stroke miter limitrealThe angle at which a stroke join
stroke overprintbooleanShould art beneath the stroked
stroke widthrealThe width of the stroke.
strokedbooleanShould the character’s path be
text orientationR/Ohorizontal/verticalShould this text be displayed
text pathR/Oobject referenceA reference to the text path
This example demonstrates how to use char acter properties to create unique effects from
a script.
(* Distort every character in the first text art item of a document by incrementally modifying the
horizontal scaling of each character to give the effect of stretching words out *)
-- A smaller value for this property means more difference between largest and
-- smallest horizontal scaling of the characters
property pVariability : 1.0
character, charactersAppleScript Reference74
tell application "Adobe Illustrator 10"
-- Is there is a document and a text art item to work with
if (exists text art item 1 of current document) then
-- Make sure the text art item contains some text
set textArtItem to first text art item of current document
if textArtItem is not "" then -- contains some text
-- Gather info needed to calculate the scale factor
set characterCount to count of characters in textArtItem
set factor to (characterCount + 1) / 2
-- Iterate over each character, changing its horizontal scale
repeat with i from 1 to characterCount
set hScaling to (factor - i) / factor
if hScaling < 0 then set hScaling to -hScaling
set widthScale to 100 * pVariability - (hScaling * 100)
set scaling of character i of text art item 1 of document 1 ¬
to {widthScale, 100.0}
end repeat
end if
end if
end tell
Adobe Illustrator 10 Scripting Guide CMYK color info75
CMYK color info
A CMYK color specification, used to specify a CMYK color in conjunction with the color
property.
Properties
Property:R/OValue type:What it is:
cyanrealThe cyan color value as a value
in the range 0.0 - 100.0.
magentarealThe magenta color value as a
value in the range 0.0 - 100.0.
yellowrealThe yellow color value as a
value in the range 0.0 - 100.0.
blackrealThe black color value as a v alue
in the range 0.0 - 100.0.
Valid Commands
none
Notes
This class is used to define a record which contains the color component values of a
CMYK color. It is used for specifying and retrieving color information from an Illustrator
document or from page items in a document.
If the
color space of a document is RGB and you specify the color value for a page
item in that document using
color specification into a RGB color specification. The same thing happens if the
document’s
color space is CMYK and you specify colors using RGB color info.
Since this translation can cause information loss you should specify colors using the color
info class that matches the document’s
CMYK color info, Illustrator will translate the CMYK
color space.
CMYK color infoAppleScript Reference76
Example 5.1
This example demonstrates how to create a new swatch in a document and assign a
CMYK color to the swatch.
-- Make a new CYMK color swatch in the current document
tell application "Adobe Illustrator 10"
if not (exists swatch "Yellow" in current document) then
set swatchColor to {cyan:50.0, magenta:20.0, yellow:20.0, black:0.0}
make new swatch at beginning of current document with properties ¬
A compound path or list of compound paths. Compound paths are objects composed of
multiple intersecting paths, resulting in transparent interior spaces where the original
paths overlapped.
Elements
Element:Refer to by:
path itemname, index, before/after, range, test
tagname, index, before/after, range, test
Paths contained within a compound path or group in a document will be returned as
individual paths when a script asks for the paths contained in the document. However,
paths contained in a compound path or group will not be returned when a script asks for
the paths in a layer which contains the compound path or group.
All paths inside of a compound path share property values. Therefore, if y ou set the v alue
of a property of any one of the paths in the compound path, all other path’s matching
property will be updated to the new value.
This example demonstrates how to get a list containing all of the paths in a document that
are not part of a compound path or a group by iterating through each layer in the
document.
-- A handler which return paths in a document that are not part of a
-- compound path or group
to GetPathItemsOfDocument(docRef)
tell application "Adobe Illustrator 10"
set pathItemList to {}
set layerCount to count of layers of docRef
repeat with i from 1 to layerCount
set pathItemList to pathItemList & path items of layer i of docRef
end repeat
end tell
return pathItemList
end GetPathItemsOfDocument
-- Call handler
tell application "Adobe Illustrator 10" to set docRef to current document
set allPathItems to GetPathItemsOfDocument(docRef)
Example 6.2
Compound paths contain path items that can be accessed from a script. This example
shows how to duplicate the paths in a compound path and then group them in a new
group item.
-- Create a group containing a set of paths duplicated from the
-- first compound path item of the document
tell application "Adobe Illustrator 10"
set pathItemList to path every item of ¬
compound path item 1 of current document
set groupRef to make new group item at beginning of ¬
layer 1 of document 1
duplicate pathItemList to beginning of groupRef
end tell
dataset, datasetsAppleScript Reference82
dataset, datasets
An object, or list of objects, that contains variables and their dynamic data.
Properties
Property:R/OValue type:What it is:
best typeR/OclassThe best type for the dataset’s
value. Always returns
reference.
classR/OclassThe dataset object’s class,
which is
containerR/Oobject referenceA reference to the art object
that contains this dataset.
default typeR/OclassThe default type for the dataset.
Always returns
reference.
indexR/OintegerThe index of this dataset in the
art object.
namestringThe name of the dataset.
propertiesrecordall of the dataset’s properties
An Illustrator document or a list of documents. Documents are contained in the
application object.
Elements
Element:Refer to by:
art stylename, index, before/after, range, test
brushname, index, before/after, range, test
compound path itemname, index, before/after, range, test
datasetname, index, before/after, range, test
gradientname, index, before/after, range, test
graph itemname, index, before/after, range, test
group itemname, index, before/after, range, test
layername, index, before/after, range, test
mesh itemname, index, before/after, range, test
page itemname, index, before/after, range, test
path itemname, index, before/after, range, test
patternname, index, before/after, range, test
placed itemname, index, before/after, range, test
plugin itemname, index, before/after, range, test
raster itemname, index, before/after, range, test
spotname, index, before/after, range, test
swatchname, index, before/after, range, test
symbolname, index, before/after, range, test
symbol itemname, index, before/after, range, test
tagname, index, before/after, range, test
text art itemname, index, before/after, range, test
variablename, index, before/after, range, test
viewindex, before/after, range, test
Properties
Property:R/OValue type:What it is:
best typeR/OclassThe best type for the document
object's value. Always returns
reference.
document, documentsAppleScript Reference84
Property:R/OValue type:What it is:
classR/OclassThe document object's class,
which is
color spaceR/ORGB/CMYKThe color specification system
to use for this document’s color
space.
crop marksfixed rectangleThe boundary of the
document's cropping box for
output.
crop stylestandard/japaneseThe style of the document's
cropping box, either standard or
japanese.
current datasetobject referenceThe currently active dataset.
current layerobject referenceThe active layer in the
document.
current viewR/Oobject referenceThe document's current view.
default fill colorCMYK color info/gray
color info/RGB color info/
spot color info/pattern
color info/gradient color
info
default fill overprintbooleanWill art beneath a filled object
default filledbooleanShould a new path be filled?
default stroke capbutted/rounded/
projecting
default stroke colorCMYK color info/gray
color info/RGB color info/
spot color info/pattern
color info/gradient color
info
default stroke dash offsetrealThe default distance into the
default stroke dasheslist (of real numbers)Default lengths for dashes and
default stroke joinmitered/rounded/beveled Default type of joints in new
Illustrator’s default document settings—those properties starting with the word “default”—
are global settings that affect the current document. Be sure to modify these default
properties only when a document is open. Note that if you set default properties to
desired values before creating new objects, you can streamline your scripts, eliminating
the need to specify properties such as
analogous default properties.
fill color and stroked that have
A document’s
document is created. Once a document is created, these properties cannot be changed.
The frontmost document can be referred to as either
color space, height, and width can only be set when the
current document or
document 1.
document, documentsAppleScript Reference88
Example 7.1
The following e xample sho ws how to mak e sure a document is open bef ore setting an y of
the application’s default properties.
-- Check to make sure a document is open in Illustrator
-- before setting the application's default stroke width to 8 points
tell application "Adobe Illustrator 10"
if not (document 1 exists) then
make new document with properties {color space: CMYK, width: 100.0,
height: 50.0}
end if
set the default stroke width of document 1 to 8.0
end tell
Example 7.2
The following example shows how to make new documents with custom defaults.
-- Present a dialog to the user to choose a new document type
-- from, then create a new document with its properties set accordingly
-- Note: You can only change writable document defaults when a document is open
-- Prompt user for new document properties from list of choices
set listChoice to (choose from list ¬
{"CMYK, filled, 2 pt stroke with dashes", ¬
"RGB, filled, no stroke", ¬
"RGB, no fill, 1 pt stroke"} ¬
with prompt "What kind of new document to create?")
if listChoice is not false then
-- Gather the values needed to set the document's properties
set documentType to item 1 of listChoice
set fillPaths to (documentType contains "filled")
set strokePaths to (documentType contains "pt stroke")
set strokeWidth to 0.0
if documentType contains "1 pt" then
set strokeWidth to 1.0
else if documentType contains "2 pt" then
set strokeWidth to 2.0
document, documentsAppleScript Reference89
end if
if documentType contains "with dashes" then
set strokeDashes to {2.5, 1, 2.5, 1, 2.5, 1}
else
set strokeDashes to {}
end if
tell application "Adobe Illustrator 10"
-- Create a document with the requested color space
if documentType starts with "CMYK" then
set docRef to make new document with properties {color space:CMYK}
else
set docRef to make new document with properties {color space:RGB}
This example demonstrates how to use document properties in other applications. In this
case, the script uses the
containing the Illustrator document in the Finder.
-- Reveal and select a document’s file icon in the Finder
tell application "Adobe Illustrator 10"
set filePath to file path of current document
end tell
tell application "Finder"
activate
reveal filePath
end tell
file path property of the active document to open the folder
ellipseAppleScript Reference90
ellipse
A class used to create an elliptical path in an Illustrator document. This class can only be
used to create new path item objects.
Properties
Property:R/OValue type:What it is:
boundsW/O fixed rectangleThe bounds of the ellipse.
inscribedW/O booleanIs the ellipse path inscribed
(drawn inside the rectangle
described by the bounds)?
reversedW/O booleanIs the ellipse path reversed?
Valid Commands
•make
Notes
Illustrator’s ellipse object is available exclusively for use with the make command.
The class of the object created will be a path item. Therefore, the properties for an ellipse
are write-once (W/O) in the sense that they can be used only to specify the creation of a
new path item. This special class allows you to quickly create complex path items using
the straightforward properties provided. If you do not specify any properties when making
a new ellipse, default values will be used. Properties usually associated with path items,
such as
fill color, can also be specified at the time of creation.
Example 8.1
This examples demonstrates how to create a series of ellipses based on the geometry of
a single selected object.
-- Embellish a single selected path item by adding a bright red
-- ellipse to each point on the path
property pEllipseScale : 0.1
tell application "Adobe Illustrator 10"
activate
set selectedItems to selection
-- A bit of sanity checking
ellipseAppleScript Reference91
if (count of selectedItems) is not 1 ¬
or class of selectedItems is text ¬
or class of item 1 of selectedItems is not path item then
display dialog "Please select a single path item before running this
script"
else
set pathItem to item 1 of selectedItems
-- Set ellipse color based on document color space
set docColorSpace to color space of current document
if docColorSpace is RGB then
set ellipseColor to {red:255.0, green:0.0, blue:0.0}
else
set ellipseColor to {cyan:0.0, magenta:100.0, yellow:100.0,
black:0.0}
end if
-- Gather needed info about the path item to be embellished
set itemWidth to width of pathItem
set itemHeight to height of pathItem
set pathPointList to anchor of every path point of pathItem
-- Calculate the position and bounds for each ellipse
repeat with aPoint in pathPointList
set {x, y} to aPoint
set rectLeft to x - (itemWidth * pEllipseScale)
set rectRight to x + (itemWidth * pEllipseScale)
set rectTop to y + (itemHeight * pEllipseScale)
set rectBottom to y - (itemHeight * pEllipseScale)
set ellipseRect to {rectLeft, rectTop, rectRight, rectBottom}
make new ellipse at beginning of current document ¬
with properties {bounds:ellipseRect, inscribed:true ¬
, reversed:false, stroke color:ellipseColor, fill
color:ellipseColor} ¬
end repeat
end if
end tell
EPS save optionsAppleScript Reference92
EPS save options
Options which may be supplied when saving a document as an Illustrator EPS file. See
save command in the command reference for additional details.
embed all fonts boolean Include fonts used in the EPS
embed linked files boolean Are linked image files to be
flatten outputpreserve paths/preserve
appearance
included document thumbnails booleanInclude thumbnail image of the
japanese file format boolean Save the file using Japanese
PostScript level 1/level 2/level 3 Specifies the PostScript lev el to
preview none/BW Macintosh/
color Macintosh/BW
TIFF/color TIFF/
transparent color TIFF
Specifies the version of the
Illustrator file format to create.
default:
Illustrator
10
file? default:
included in the saved
document? default:
How should transparency be
flattened for file formats before
Illustrator 10. default:
false
false
preserve
appearance
EPS artwork? default:
version of file format? Valid only
for Illustrator 3 - 5 compatibility.
default:
use when saving the file.
default:
Specifies the format for the EPS
preview image. default:
false
level 3
true
color Macintosh
Notes
Postscipt level 1 is only valid for compatibility with Illustrator 8 or earlier.
Adobe Illustrator 10 Scripting Guide EPS save options93
This class is used to define a record containing properties that specify options when
saving a document as an EPS file.
conjunction with the
options
object.
save command. It is not possible to get or create an EPS save
EPS save options can only be used in
It is not necessary to specify values for all properties. Default values will be provided for
any properties not specified.
Example 9.1
This handler processes a folder of Illustrator files, saving each as an EPS file with level 2
PostScript and Illustrator 10 compatibility. The files are save to the folder specified in the
destinationFolder parameter. Note that the class property is specified in the
record to ensure that Illustrator can determine the save option class.
-- fileList is a list of aliases to Illustrator files
-- destinationFolder is an alias to a folder where the EPS files are to be saved
set sourceFolder to choose folder with prompt "Source folder?"
tell application "Finder" to
set fileList to every file of folder sourceFolder as alias list
set destinationFolder to choose folder with prompt "Destination folder?"
set destinationPath to destinationFolder as string
repeat with aFile in fileList
tell application "Finder" to set fileName to name of aFile
set newFilePath to destinationPath & fileName & ".EPS"
tell application "Adobe Illustrator 10"
open aFile
save current document in file newFilePath as eps ¬
with options {class:EPS save options ¬
, compatibility:Illustrator 10 ¬
, preview:color Macintosh ¬
, embed linked files:true ¬
, include document thumbnails:true ¬
, embed all fonts:true ¬
, japanese file format:false ¬
, CMYK PostScript:true ¬
, PostScript:level 2}
A pair of values that defines the coordinates for a point. Stored as a list of two real
numbers, where the first item is the horizontal (x) coordinate of the point and the second
item is the vertical (y) coordinate of the point. For example,
specify a point where the x coordinate is 10.0 and the y coordinate is 5.0.
Notes
The point is used to specify the coordinates for many properties of objects in Illustrator.
All distance and measurement values in Illustrator use the points unit of measure.
It is not possible to get or create a fixed point object.
Example 10.1
The values in fixed point can be used in a number of way in a script.
tell application "Adobe Illustrator 10"
if (count of documents)>0 then
-- Get the position of a page item
set itemPos to position of page item 1 of document 1
--> {100.0, 200.0}
{10.0, 5.0} would
-- Assigns the two values in a fixed point to two variables
set {x, y} to itemPos
--> x = 100.0, y = 200.0
-- or assign to two variables directly
set {x, y} to position of page item 1 of document 1
--> x = 100.0, y = 200.0
-- Change the x value in a fixed point
set item 1 of itemPos to (item 1 of itemPos) + 100.0
--> {200.0, 200.0}
-- Change position of a page item
set position of page item 1 of document 1 to itemPos
-- or change it using the individual variables
set position of page item 1 of document 1 to {x + 100.0, y}
Four coordinates that defines the rectangular geometry of an object. Stored as a list of
four real numbers, where the first item is the leftmost horizontal coordinate of the
rectangle, the second item is the top vertical coordinate of the rectangle, the third item is
the rightmost horizontal coordinate, and the fourth item is the bottom vertical coordinate
of the rectangle.
Notes
The fixed rectangle is used to specify the geometry for a number of properties for objects
in Illustrator. All distance and measurement values in Illustrator use the points unit. It is
not possible to get or create fixed rectangle object.
Remember that in the Illustrator coordinate system, vertical coordinates increase from
bottom to top, which is the opposite of screen coordinates. This mean that the top
coordinate value in a fixed rectangle will be larger than the bottom coordinate value.
Example 11.1
The values in a fixed rectangle can be used in a number of way in a script.
tell application "Adobe Illustrator 10"
-- Get the bounds of a page item
set itemBounds to geometric bounds of page item 1 of document 1
--> {100.0, 400.0, 300.0, 200.0}
-- Assigns the four values in a rectangle point to four variables
set {l, t, r, b} to itemBounds
--> l = 100.0, t = 400.0, r = 300.0, b = 200.0
-- or assign to four variables directly
set {l, t, r, b} to geometric bounds of page item 1 of document 1
--> l = 100.0, t = 400.0, r = 300.0, b = 200.0
-- Calculate center of page item from its bounds
set xCenter to ((item 1 of itemBounds) + (item 3 of itemBounds)) / 2
set yCenter to ((item 2 of itemBounds) + (item 4 of itemBounds)) / 2
--> xCenter = 200.0, yCenter = 300.0
-- or calculate the center using the individual coordinate variables
set xCenter to (l + r) / 2
set yCenter to (t + b) / 2
fixed rectangleAppleScript Reference98
--> xCenter = 200.0, yCenter = 300.0
-- Change the left value in a fixed rectangle
set item 1 of itemBounds to (item 1 of itemBounds) + 100.0
You can supply a number of options when exporting a document as Flash (.SWF). See
export command in the command reference for additional details.
the
Properties
Property:R/OValue type:What it is:
artboard clippingbooleanShould the resulting image be
clipped to the artboard? default:
false
curve qualityintegerHow much curve information
should be preserved (0-10,
default: 7)
export styleFlash file/layers to files/
layers to Flash frames
frame raterealWhen exporting layers to Flash
generate HTMLbooleanexport as HTML file (default:
JPEG methodoptimized/standardWhat method to use (default:
JPEG qualityintegerLevel of compression (0-10,
loopingbooleanShould the Flash file be set to
read onlybooleanExport as read only file (default:
replacingyes/no/askIf a file with the same name
resolutionrealPixels per inch (72-2400,
How the Flash file should be
created (default: Flash file)
frames (0.01-120, default: 12)
true)
standard)
default: 3)
loop when run (default: false)
false)
already exists, should it be
replaced?
Default: ask
default: 72)
Notes
This class is used to define a record containing properties that specify options when
exporting a document as a Flash (.SWF) file.
supplied in conjunction with the
export command. It is not possible to get or create a
Flash export options can only be
Flash export options object.
Flash export optionsAppleScript Reference100
It is not necessary to specify values for all properties. Default values will be provided for
all properties not specified.
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.