Adobe Illustrator Scripting

Adobe Illustrator Scripting

Helps write, debug and optimise Adobe Illustrator ExtendScript automation, covering the object model, coordinates, exports and batch workflows, with reference files and example scripts.

Skill files5 files

references/

scripts/

SKILL.md1024 lines
1
---
2
name: adobe-illustrator-scripting
3
description: 'Write, debug, and optimize Adobe Illustrator automation scripts using ExtendScript (JavaScript/JSX). Use when creating or modifying scripts that manipulate documents, layers, paths, text frames, colors, symbols, artboards, or any Illustrator DOM objects. Covers the complete JavaScript object model, coordinate system, measurement units, export workflows, and scripting best practices.'
4
---
5
6
# Adobe Illustrator Scripting
7
8
Expert guidance for automating Adobe Illustrator through ExtendScript (JavaScript/JSX). This skill covers the Illustrator scripting object model, all major API objects, code patterns, and best practices for writing production-quality `.jsx` scripts.
9
10
## Bundled Assets
11
12
- [`references/object-model-quick-reference.md`](references/object-model-quick-reference.md): Use this as a quick lookup for the Illustrator scripting object model, common document and page item types, and related DOM concepts while writing or debugging scripts.
13
- `scripts/`: Contains example Illustrator automation scripts you can use as starting points or implementation patterns for common tasks such as document manipulation, exports, batch processing, and DOM usage. Review and adapt these examples when you need working JSX patterns or want to compare behavior while debugging.
14
## When to Use This Skill
15
16
- Writing new Illustrator automation scripts (`.jsx` or `.js` files)
17
- Debugging or fixing existing Illustrator ExtendScript code
18
- Manipulating documents, layers, page items, paths, text, or colors programmatically
19
- Batch-processing Illustrator files or generating artwork from data
20
- Exporting documents to various formats (PDF, SVG, PNG, EPS, etc.)
21
- Working with the Illustrator DOM (Application, Document, Layer, PathItem, TextFrame, etc.)
22
- Creating data-driven graphics using variables and datasets
23
- Automating print workflows with scripted print options
24
25
## Prerequisites
26
27
- Adobe Illustrator CC or later installed
28
- Basic JavaScript knowledge (ExtendScript is ES3-based with Adobe extensions)
29
- Scripts are executed via File > Scripts > Other Scripts, the Scripts menu, or placed in the Startup Scripts folder
30
- The ExtendScript Toolkit (ESTK) or any text editor can be used to write `.jsx` files
31
32
## Scripting Environment
33
34
### Language and File Extensions
35
36
| Language | Extension | Platform |
37
|---|---|---|
38
| ExtendScript/JavaScript | `.jsx`, `.js` | Windows, macOS |
39
| AppleScript | `.scpt` | macOS only |
40
| VBScript | `.vbs` | Windows only |
41
42
**This skill focuses on ExtendScript/JavaScript** as the cross-platform, most widely used option.
43
44
### Executing Scripts
45
46
- **Scripts menu**: File > Scripts lists scripts from the application scripts folder
47
- **Other Scripts**: File > Scripts > Other Scripts to browse and run any `.jsx` file
48
- **Startup Scripts**: Place scripts in the Startup Scripts folder to run automatically on launch
49
- **Target directive**: Begin scripts with `#target illustrator` when running from ESTK or external tools
50
- **`#targetengine` directive**: Use `#targetengine "session"` to persist variables across script executions
51
- **External invocation**: Scripts are frequently launched from outside Illustrator — by shell scripts, task runners, CI jobs, ExtendScript Toolkit (`ExtendScript Toolkit.exe -run script.jsx`), or `BridgeTalk` messages from other Adobe apps. See [External Invocation & Argument Passing](#external-invocation--argument-passing).
52
53
### Naming Conventions (JavaScript)
54
55
- Objects and properties use **camelCase**: `activeDocument`, `pathItems`, `textFrames`
56
- The `app` global references the `Application` object
57
- Collection indices are **zero-based**: `documents[0]` is the frontmost document
58
- Use `typename` property to identify object types at runtime
59
60
## Object Model Overview
61
62
The Illustrator DOM follows a strict containment hierarchy:
63
64
```
65
Application (app)
66
├── activeDocument / documents[]
67
│ ├── layers[]
68
│ │ ├── pageItems[] (all artwork)
69
│ │ ├── pathItems[]
70
│ │ ├── compoundPathItems[]
71
│ │ ├── textFrames[]
72
│ │ ├── placedItems[]
73
│ │ ├── rasterItems[]
74
│ │ ├── meshItems[]
75
│ │ ├── pluginItems[]
76
│ │ ├── graphItems[]
77
│ │ ├── symbolItems[]
78
│ │ ├── nonNativeItems[]
79
│ │ ├── legacyTextItems[]
80
│ │ └── groupItems[]
81
│ ├── artboards[]
82
│ ├── views[]
83
│ ├── selection (array of selected items)
84
│ ├── swatches[], spots[], gradients[], patterns[]
85
│ ├── graphicStyles[], brushes[], symbols[]
86
│ ├── textFonts[] (via app.textFonts)
87
│ ├── stories[], characterStyles[], paragraphStyles[]
88
│ ├── variables[], datasets[]
89
│ └── inkList[], printOptions
90
├── preferences
91
├── printerList[]
92
└── textFonts[]
93
```
94
95
### Top-Level Objects
96
97
- **Application** (`app`): The root object. Provides access to documents, preferences, fonts, and printers. Key properties: `activeDocument`, `documents`, `textFonts`, `printerList`, `userInteractionLevel`, `version`.
98
- **Document**: Represents an open `.ai` file. Key properties: `layers`, `pageItems`, `selection`, `activeLayer`, `width`, `height`, `rulerOrigin`, `documentColorSpace`. Key methods: `saveAs()`, `exportFile()`, `close()`, `print()`.
99
- **Layer**: A drawing layer. Key properties: `pageItems`, `pathItems`, `textFrames`, `visible`, `locked`, `opacity`, `name`, `zOrderPosition`, `color`.
100
101
## Measurement Units and Coordinates
102
103
### Units
104
105
All scripting API values use **points** (72 points = 1 inch). Convert other units:
106
107
| Unit | Conversion |
108
|---|---|
109
| Inches | multiply by 72 |
110
| Centimeters | multiply by 28.346 |
111
| Millimeters | multiply by 2.834645 |
112
| Picas | multiply by 12 |
113
114
Kerning, tracking, and `aki` properties use **em units** (thousandths of an em, proportional to font size).
115
116
### Coordinate System
117
118
- For **scripted documents**, the origin `(0,0)` is at the **bottom-left** of the artboard
119
- X increases left to right; Y increases bottom to top
120
- The `position` property of a page item is the **top-left corner** of its bounding box as `[x, y]`
121
- Maximum page item width/height: 16348 points
122
123
### Art Item Bounds
124
125
Every page item has three bounding rectangles:
126
127
- `geometricBounds`: Excludes stroke width `[left, top, right, bottom]`
128
- `visibleBounds`: Includes stroke width
129
- `controlBounds`: Includes control/direction points
130
131
## Working with Documents
132
133
### Creating and Opening
134
135
```javascript
136
// Create a new document
137
var doc = app.documents.add();
138
139
// Create with a preset
140
var preset = new DocumentPreset();
141
preset.width = 612; // 8.5 inches
142
preset.height = 792; // 11 inches
143
preset.colorMode = DocumentColorSpace.CMYK;
144
var doc = app.documents.addDocument("Print", preset);
145
146
// Open an existing file
147
var fileRef = new File("/path/to/file.ai");
148
var doc = app.open(fileRef);
149
```
150
151
### Saving and Exporting
152
153
```javascript
154
// Save as Illustrator format
155
var saveOpts = new IllustratorSaveOptions();
156
saveOpts.compatibility = Compatibility.ILLUSTRATOR17; // CC
157
doc.saveAs(new File("/path/to/output.ai"), saveOpts);
158
159
// Export as PDF
160
var pdfOpts = new PDFSaveOptions();
161
pdfOpts.compatibility = PDFCompatibility.ACROBAT7;
162
pdfOpts.preserveEditability = false;
163
doc.saveAs(new File("/path/to/output.pdf"), pdfOpts);
164
165
// Export as PNG
166
var pngOpts = new ExportOptionsPNG24();
167
pngOpts.horizontalScale = 300;
168
pngOpts.verticalScale = 300;
169
pngOpts.transparency = true;
170
doc.exportFile(new File("/path/to/output.png"), ExportType.PNG24, pngOpts);
171
172
// Export as SVG
173
var svgOpts = new ExportOptionsSVG();
174
svgOpts.fontType = SVGFontType.OUTLINEFONT;
175
doc.exportFile(new File("/path/to/output.svg"), ExportType.SVG, svgOpts);
176
```
177
178
## Working with Paths and Shapes
179
180
### Built-in Shape Methods
181
182
The `pathItems` collection provides convenience methods for common shapes:
183
184
```javascript
185
var doc = app.activeDocument;
186
var layer = doc.activeLayer;
187
188
// Rectangle: rectangle(top, left, width, height)
189
var rect = layer.pathItems.rectangle(500, 100, 200, 150);
190
191
// Rounded rectangle: roundedRectangle(top, left, width, height, hRadius, vRadius)
192
var rrect = layer.pathItems.roundedRectangle(500, 100, 200, 150, 20, 20);
193
194
// Ellipse: ellipse(top, left, width, height)
195
var oval = layer.pathItems.ellipse(400, 200, 100, 100);
196
197
// Polygon: polygon(centerX, centerY, radius, sides)
198
var hex = layer.pathItems.polygon(300, 300, 50, 6);
199
200
// Star: star(centerX, centerY, radius, innerRadius, points)
201
var star = layer.pathItems.star(300, 300, 50, 25, 5);
202
```
203
204
### Freeform Paths Using Coordinate Arrays
205
206
```javascript
207
var doc = app.activeDocument;
208
var path = doc.pathItems.add();
209
path.setEntirePath([[100, 100], [200, 200], [300, 100]]);
210
path.closed = false;
211
path.stroked = true;
212
path.strokeWidth = 2;
213
```
214
215
### Freeform Paths Using PathPoint Objects
216
217
```javascript
218
var doc = app.activeDocument;
219
var path = doc.pathItems.add();
220
221
var point1 = path.pathPoints.add();
222
point1.anchor = [100, 100];
223
point1.leftDirection = [100, 100];
224
point1.rightDirection = [150, 150];
225
point1.pointType = PointType.SMOOTH;
226
227
var point2 = path.pathPoints.add();
228
point2.anchor = [300, 100];
229
point2.leftDirection = [250, 150];
230
point2.rightDirection = [300, 100];
231
point2.pointType = PointType.SMOOTH;
232
233
path.closed = false;
234
```
235
236
### Path Properties
237
238
```javascript
239
var item = doc.pathItems[0];
240
item.filled = true;
241
item.stroked = true;
242
item.strokeWidth = 1.5;
243
item.strokeCap = StrokeCap.ROUNDENDCAP;
244
item.strokeJoin = StrokeJoin.ROUNDENDJOIN;
245
item.opacity = 80;
246
item.closed = true;
247
```
248
249
## Working with Colors
250
251
### Color Objects
252
253
```javascript
254
// RGB Color (values 0-255)
255
var red = new RGBColor();
256
red.red = 255;
257
red.green = 0;
258
red.blue = 0;
259
260
// CMYK Color (values 0-100)
261
var cyan = new CMYKColor();
262
cyan.cyan = 100;
263
cyan.magenta = 0;
264
cyan.yellow = 0;
265
cyan.black = 0;
266
267
// Grayscale (0-100, 0 = black)
268
var gray = new GrayColor();
269
gray.gray = 50;
270
271
// Lab Color
272
var lab = new LabColor();
273
lab.l = 50;
274
lab.a = 20;
275
lab.b = -30;
276
277
// No color (transparent)
278
var none = new NoColor();
279
```
280
281
### Applying Colors
282
283
```javascript
284
var item = doc.pathItems[0];
285
item.fillColor = red;
286
item.strokeColor = cyan;
287
288
// Gradient fill
289
var gradient = doc.gradients.add();
290
gradient.type = GradientType.LINEAR;
291
gradient.gradientStops[0].color = red;
292
gradient.gradientStops[1].color = cyan;
293
294
var gradColor = new GradientColor();
295
gradColor.gradient = gradient;
296
item.fillColor = gradColor;
297
```
298
299
### Spot Colors and Swatches
300
301
```javascript
302
// Create a spot color
303
var spot = doc.spots.add();
304
spot.name = "My Spot Color";
305
spot.color = red; // Base color definition
306
307
var spotColor = new SpotColor();
308
spotColor.spot = spot;
309
spotColor.tint = 100;
310
311
item.fillColor = spotColor;
312
313
// Access a swatch by name
314
var swatch = doc.swatches.getByName("PANTONE 185 C");
315
item.fillColor = swatch.color;
316
```
317
318
## Working with Text
319
320
### Text Frame Types
321
322
```javascript
323
var doc = app.activeDocument;
324
325
// Point text
326
var pointText = doc.textFrames.add();
327
pointText.contents = "Hello World!";
328
pointText.position = [100, 500];
329
330
// Area text (text inside a path)
331
var rectPath = doc.pathItems.rectangle(500, 100, 200, 100);
332
var areaText = doc.textFrames.areaText(rectPath);
333
areaText.contents = "Text inside a rectangle shape.";
334
335
// Path text (text along a path)
336
var curvePath = doc.pathItems.add();
337
curvePath.setEntirePath([[50, 300], [150, 400], [250, 300]]);
338
var pathText = doc.textFrames.pathText(curvePath);
339
pathText.contents = "Text on a path";
340
```
341
342
### Character and Paragraph Formatting
343
344
```javascript
345
var tf = doc.textFrames[0];
346
var textRange = tf.textRange;
347
348
// Character attributes
349
var charAttr = textRange.characterAttributes;
350
charAttr.size = 24; // Font size in points
351
charAttr.textFont = app.textFonts.getByName("ArialMT");
352
charAttr.fillColor = red;
353
charAttr.tracking = 50; // Em units
354
charAttr.horizontalScale = 100;
355
charAttr.verticalScale = 100;
356
charAttr.baselineShift = 0;
357
358
// Paragraph attributes
359
var paraAttr = textRange.paragraphAttributes;
360
paraAttr.justification = Justification.CENTER;
361
paraAttr.firstLineIndent = 0;
362
paraAttr.leftIndent = 0;
363
paraAttr.spaceBefore = 0;
364
paraAttr.spaceAfter = 0;
365
```
366
367
### Accessing Text Content
368
369
```javascript
370
var tf = doc.textFrames[0];
371
372
// Access sub-ranges
373
var firstChar = tf.characters[0];
374
var firstWord = tf.words[0];
375
var firstPara = tf.paragraphs[0];
376
var firstLine = tf.lines[0];
377
378
// Modify specific ranges
379
tf.words[0].characterAttributes.size = 36;
380
tf.paragraphs[0].paragraphAttributes.justification = Justification.LEFT;
381
```
382
383
### Threading Text Frames
384
385
```javascript
386
var frame1 = doc.textFrames.areaText(path1);
387
var frame2 = doc.textFrames.areaText(path2);
388
389
// Link frames so text flows from frame1 to frame2
390
frame1.nextFrame = frame2;
391
392
// Stories represent the full text across threaded frames
393
var storyCount = doc.stories.length;
394
var fullText = doc.stories[0].textRange.contents;
395
```
396
397
## Working with Layers
398
399
```javascript
400
var doc = app.activeDocument;
401
402
// Create a layer
403
var newLayer = doc.layers.add();
404
newLayer.name = "Background";
405
newLayer.visible = true;
406
newLayer.locked = false;
407
newLayer.opacity = 100;
408
409
// Access existing layers
410
var topLayer = doc.layers[0];
411
var layerByName = doc.layers.getByName("Background");
412
413
// Move items between layers
414
var item = doc.pathItems[0];
415
item.move(newLayer, ElementPlacement.PLACEATBEGINNING);
416
417
// Reorder layers
418
newLayer.zOrder(ZOrderMethod.SENDTOBACK);
419
```
420
421
## Working with Selections
422
423
```javascript
424
// Get current selection
425
var sel = app.activeDocument.selection;
426
427
// Iterate selected items
428
for (var i = 0; i < sel.length; i++) {
429
var item = sel[i];
430
// Check type using typename
431
if (item.typename === "PathItem") {
432
item.fillColor = red;
433
} else if (item.typename === "TextFrame") {
434
item.contents = "Modified";
435
}
436
}
437
438
// Select an item programmatically
439
doc.pathItems[0].selected = true;
440
441
// Deselect all
442
doc.selection = null;
443
```
444
445
## Working with Symbols
446
447
```javascript
448
// Place a symbol instance
449
var sym = doc.symbols.getByName("MySymbol");
450
var instance = doc.symbolItems.add(sym);
451
instance.position = [200, 400];
452
453
// Access symbol definition
454
var symDef = instance.symbol;
455
456
// Break link to symbol (expand to regular art)
457
instance.breakLink();
458
```
459
460
## Transformations
461
462
```javascript
463
var item = doc.pathItems[0];
464
465
// Rotate 45 degrees around center
466
item.rotate(45);
467
468
// Scale to 50% width, 75% height
469
item.resize(50, 75);
470
471
// Translate (move) by 100 points right and 50 points up
472
item.translate(100, 50);
473
474
// Using a transformation matrix
475
var matrix = app.getIdentityMatrix();
476
matrix = app.concatenateRotationMatrix(matrix, 30);
477
matrix = app.concatenateScaleMatrix(matrix, 150, 150);
478
item.transform(matrix);
479
```
480
481
## Working with Artboards
482
483
```javascript
484
var doc = app.activeDocument;
485
486
// Access artboards
487
var ab = doc.artboards[0];
488
var rect = ab.artboardRect; // [left, top, right, bottom]
489
490
// Create a new artboard
491
var newAB = doc.artboards.add([0, 0, 612, 792]); // Letter size
492
newAB.name = "Page 2";
493
494
// Set active artboard
495
doc.artboards.setActiveArtboardIndex(1);
496
```
497
498
## Data-Driven Graphics (Variables and Datasets)
499
500
```javascript
501
// Variables link document items to data fields
502
var v = doc.variables.add();
503
v.kind = VariableKind.TEXTUAL;
504
v.name = "headline";
505
506
// Link a text frame to the variable
507
var tf = doc.textFrames[0];
508
tf.contentVariable = v;
509
510
// Create datasets for batch content
511
var ds = doc.dataSets.add();
512
ds.name = "Version 1";
513
// Dataset captures current variable bindings
514
515
// Switch datasets to swap content
516
doc.dataSets[0].display();
517
```
518
519
## Printing
520
521
```javascript
522
var doc = app.activeDocument;
523
var opts = new PrintOptions();
524
525
opts.printPreset = "Default";
526
527
// Paper options
528
var paperOpts = new PrintPaperOptions();
529
paperOpts.name = "Letter";
530
opts.paperOptions = paperOpts;
531
532
// Job options
533
var jobOpts = new PrintJobOptions();
534
jobOpts.copies = 1;
535
jobOpts.designation = PrintArtworkDesignation.VISIBLELAYERS;
536
opts.jobOptions = jobOpts;
537
538
doc.print(opts);
539
```
540
541
## User Interaction Levels
542
543
Control whether Illustrator shows dialogs during script execution:
544
545
```javascript
546
// Suppress all dialogs
547
app.userInteractionLevel = UserInteractionLevel.DONTDISPLAYALERTS;
548
549
// Perform operations that might prompt dialogs...
550
doc.close(SaveOptions.DONOTSAVECHANGES);
551
552
// Restore dialog display
553
app.userInteractionLevel = UserInteractionLevel.DISPLAYALERTS;
554
```
555
556
## Working with Methods (JavaScript-Specific)
557
558
When calling methods with multiple optional parameters, use `undefined` to skip middle parameters:
559
560
```javascript
561
// rotate(angle, [changePositions], [changeFillPatterns], [changeFillGradients], ...)
562
item.rotate(30, undefined, undefined, true);
563
```
564
565
## External Invocation & Argument Passing
566
567
Illustrator scripts are routinely launched from outside the application —
568
shell scripts, schedulers, build pipelines, ExtendScript Toolkit, or
569
`BridgeTalk` messages from other Creative Cloud apps. The execution
570
environment under those launchers differs from the in-application *File >
571
Scripts* path in several ways that frequently break otherwise-correct code.
572
573
### `arguments[]` Is Unreliable Under External Launchers
574
575
ExtendScript Toolkit's `-run` invocation and `BridgeTalk.send()` do not
576
forward arbitrary launcher arguments into the script's top-level
577
`arguments[]` array. In many configurations the array contains a single
578
`[object BridgeTalk]` element instead of the values the caller passed, as
579
demonstrated below:
580
581
```javascript
582
// At top of script
583
var passed = (typeof arguments !== "undefined") ? arguments : [];
584
for (var i = 0; i < passed.length; i++) {
585
$.writeln("arg[" + i + "] = " + passed[i]);
586
// Often prints: arg[0] = [object BridgeTalk]
587
}
588
```
589
590
**Do not rely on `arguments[]` for required inputs when the script is
591
launched externally.** Use one of the following more reliable channels.
592
593
### Sidecar File for Parameters
594
595
When a script fails under an external launcher and the source of the error
596
is not obvious, fall back to a sidecar file: have the caller write a small
597
text file at a known absolute path, and read it on startup. This works
598
regardless of launcher quirks and is easy to inspect after a failed run.
599
600
```javascript
601
var SIDECAR_PATH = "C:/Users/userName/job.args.txt";
602
603
function readSidecar(path) {
604
var f = new File(path);
605
if (!f.exists || !f.open("r")) return null;
606
var lines = [];
607
while (!f.eof) {
608
var ln = f.readln();
609
if (ln && !/^\s*$/.test(ln)) lines.push(ln);
610
}
611
f.close();
612
return {
613
input: lines[0],
614
output: lines[1],
615
mode: lines[2]
616
};
617
}
618
```
619
620
A `key=value` format is equally workable and avoids positional fragility:
621
622
```text
623
input=C:/path/to/input.ai
624
output=C:/path/to/output.pdf
625
mode=preview
626
```
627
628
### Environment Variables
629
630
`$.getenv("NAME")` returns environment variables visible to **Illustrator's
631
process**, not the launcher's. If the launcher needs Illustrator to see a
632
value, it must set the variable system-wide or in Illustrator's parent
633
environment before launching. For per-invocation values, prefer a sidecar
634
file.
635
636
### `$.fileName` and `File($.fileName).parent`
637
638
Under in-application execution, `$.fileName` is the absolute path of the
639
running script and `File($.fileName).parent` yields the script's folder.
640
Under some external launchers (notably ESTK `-run`) `$.fileName` can be
641
empty, causing relative path resolution to silently fail.
642
643
```javascript
644
// Fragile: returns null under some launchers
645
var here = $.fileName ? File($.fileName).parent : null;
646
var sidecar = here ? new File(here.fsName + "/job.args.txt") : null;
647
648
// Robust: hardcode a known absolute path or fall back to a stable location
649
var sidecar = new File("C:/Users/userName/job.args.txt");
650
if (!sidecar.exists) sidecar = new File(Folder.temp.fsName + "/job.args.txt");
651
```
652
653
### Diagnostic Logging to an Absolute Path
654
655
Silent failures are common because dialogs are suppressed and the launcher
656
may not surface `$.writeln` output. Write a plain-text log to a known
657
absolute path so a run can be inspected after the fact. Create the parent
658
folder on demand so the first call cannot fail for a missing directory.
659
660
```javascript
661
var LOG_PATH = "C:/Users/userName/logs/job.log";
662
663
function log(msg) {
664
try {
665
var f = new File(LOG_PATH);
666
try { if (!f.parent.exists) f.parent.create(); } catch (eDir) {}
667
if (f.open("a")) {
668
f.writeln("[" + new Date() + "] " + msg);
669
f.close();
670
}
671
} catch (e) {}
672
}
673
```
674
675
### Wrap the Entry Point in `try { ... } catch`
676
677
Externally launched scripts often fail without any visible indication. A
678
top-level `try`/`catch` that writes the error to the log file converts
679
silent failures into a single inspectable line.
680
681
```javascript
682
try {
683
main();
684
} catch (err) {
685
log("FATAL: " + err + (err && err.line ? " line=" + err.line : ""));
686
}
687
```
688
689
### Suppress User Interaction
690
691
External callers cannot answer dialogs. Disable them before any DOM work
692
and avoid `alert()` / `confirm()` / `prompt()` entirely in scripts that may
693
be launched headlessly.
694
695
```javascript
696
app.userInteractionLevel = UserInteractionLevel.DONTDISPLAYALERTS;
697
```
698
699
### Save Explicitly
700
701
Closing or letting Illustrator return to its idle state does not save the
702
working file. After all DOM edits, call `doc.saveAs(...)` (or `doc.save()`)
703
explicitly and log whether it succeeded.
704
705
```javascript
706
var opts = new IllustratorSaveOptions();
707
opts.compatibility = Compatibility.ILLUSTRATOR17;
708
doc.saveAs(new File(doc.fullName.fsName), opts);
709
```
710
711
## Common Patterns
712
713
### Iterate All Page Items in a Document
714
715
```javascript
716
function processAllItems(doc) {
717
for (var i = 0; i < doc.pageItems.length; i++) {
718
var item = doc.pageItems[i];
719
// Process based on type
720
switch (item.typename) {
721
case "PathItem":
722
// handle path
723
break;
724
case "TextFrame":
725
// handle text
726
break;
727
case "GroupItem":
728
// handle group (may contain nested items)
729
break;
730
}
731
}
732
}
733
```
734
735
### Recursively Unlock Layers and Groups Before Editing
736
737
A locked layer or any locked ancestor (parent group, clip group, sublayer)
738
will cause edits to throw `Error: Target layer cannot be modified`. Walk the
739
full hierarchy and clear `locked` / `hidden` flags before performing DOM
740
modifications.
741
742
```javascript
743
function unlockAll(doc) {
744
function visitLayers(layers) {
745
for (var i = 0; i < layers.length; i++) {
746
var lyr = layers[i];
747
try { lyr.locked = false; lyr.visible = true; } catch (e) {}
748
visitItems(lyr);
749
if (lyr.layers && lyr.layers.length) visitLayers(lyr.layers);
750
}
751
}
752
function visitItems(container) {
753
var items = container.pageItems;
754
for (var j = 0; j < items.length; j++) {
755
var it = items[j];
756
try { it.locked = false; it.hidden = false; } catch (e) {}
757
if (it.typename === "GroupItem") visitItems(it);
758
}
759
}
760
visitLayers(doc.layers);
761
}
762
```
763
764
### Replacing the File Behind a Linked Image (Relink)
765
766
`PlacedItem.file = newFile` replaces a linked image while preserving the
767
parent, stacking order, and (after re-applying) the bounds. **`RasterItem`
768
does not expose a writable `file` property**, so when a placeholder is a
769
raster you must add a fresh `PlacedItem` in the same parent, copy the bounds,
770
then remove the original.
771
772
```javascript
773
function relinkOrRebuild(item, newFile) {
774
var bounds = item.geometricBounds.slice();
775
var parent = item.parent;
776
var name = item.name;
777
778
if (item.typename === "PlacedItem") {
779
item.file = newFile;
780
item.geometricBounds = bounds;
781
return item;
782
}
783
784
// RasterItem path: rebuild as a linked PlacedItem in the same parent.
785
var fresh = parent.placedItems.add();
786
fresh.file = newFile;
787
fresh.geometricBounds = bounds;
788
if (name) try { fresh.name = name; } catch (e) {}
789
fresh.move(item, ElementPlacement.PLACEBEFORE);
790
item.remove();
791
return fresh;
792
}
793
```
794
795
### Placing SVG Content (Copy/Paste Pattern)
796
797
`PlacedItem.file` accepts raster formats and AI/PDF, **but not SVG**. Setting
798
it to an `.svg` File throws `Unable to set placed item's file, is the file
799
path provided valid?`. The reliable way to bring SVG artwork into a document
800
is to open the SVG as a separate document, select all, copy, close, and paste
801
into the working document.
802
803
```javascript
804
function placeSVG(targetDoc, svgFile, targetLayer) {
805
var donor = app.open(svgFile);
806
app.executeMenuCommand("selectall");
807
app.executeMenuCommand("copy");
808
donor.close(SaveOptions.DONOTSAVECHANGES);
809
810
app.activeDocument = targetDoc;
811
targetDoc.activeLayer = targetLayer;
812
app.executeMenuCommand("pasteFront");
813
814
var sel = targetDoc.selection;
815
if (!sel || sel.length === 0) return null;
816
if (sel.length === 1) return sel[0];
817
818
// Multiple pasted items: group them so callers get a single handle.
819
var group = targetLayer.groupItems.add();
820
for (var i = sel.length - 1; i >= 0; i--) {
821
sel[i].move(group, ElementPlacement.PLACEATBEGINNING);
822
}
823
return group;
824
}
825
```
826
827
### Finding a Clipping Path Inside a Mask Group
828
829
Clip groups expose their clipping shape as a child `PathItem` (or, less
830
commonly, a child of a `CompoundPathItem`) with `clipping === true`. The
831
clip's `geometricBounds` give the visible frame to size or center content
832
against.
833
834
```javascript
835
function findClipPath(group) {
836
var items = group.pageItems;
837
for (var i = 0; i < items.length; i++) {
838
var it = items[i];
839
try {
840
if (it.typename === "PathItem" && it.clipping) return it;
841
if (it.typename === "CompoundPathItem") {
842
for (var j = 0; j < it.pathItems.length; j++) {
843
if (it.pathItems[j].clipping) return it;
844
}
845
}
846
} catch (e) {}
847
}
848
return null;
849
}
850
```
851
852
### Cover-Fit and Contain-Fit Sizing
853
854
To make an image fully cover a rectangle (any overflow hidden by a mask), use
855
the larger of the width/height ratios. To make it fit entirely inside, use
856
the smaller. A bleed factor (e.g. `1.10`) lets a cover image extend slightly
857
past the clip edge.
858
859
```javascript
860
function fitItemToRect(item, rect, mode, bleed) {
861
// rect = [L, T, R, B] (Illustrator: T > B)
862
var rw = rect[2] - rect[0];
863
var rh = rect[1] - rect[3];
864
var ib = item.geometricBounds;
865
var iw = ib[2] - ib[0];
866
var ih = ib[1] - ib[3];
867
if (iw <= 0 || ih <= 0) return;
868
869
var sx = rw / iw;
870
var sy = rh / ih;
871
var s = (mode === "cover" ? Math.max(sx, sy) : Math.min(sx, sy))
872
* (bleed || 1);
873
item.resize(s * 100, s * 100);
874
875
var cx = (rect[0] + rect[2]) / 2;
876
var cy = (rect[1] + rect[3]) / 2;
877
var b = item.geometricBounds;
878
var w = b[2] - b[0];
879
var h = b[1] - b[3];
880
item.position = [cx - w / 2, cy + h / 2];
881
}
882
```
883
884
885
886
### Batch Process Files in a Folder
887
888
```javascript
889
var folder = Folder.selectDialog("Select folder of .ai files");
890
if (folder) {
891
var files = folder.getFiles("*.ai");
892
for (var i = 0; i < files.length; i++) {
893
var doc = app.open(files[i]);
894
// Process each document...
895
doc.close(SaveOptions.DONOTSAVECHANGES);
896
}
897
}
898
```
899
900
### Error Handling
901
902
```javascript
903
try {
904
var doc = app.activeDocument;
905
var layer = doc.layers.getByName("NonExistentLayer");
906
} catch (e) {
907
alert("Error: " + e.message);
908
// e.message, e.line, e.fileName available
909
}
910
```
911
912
## Troubleshooting
913
914
- **"undefined is not an object"**: Usually means the collection is empty or the index is out of bounds. Check `.length` before accessing items.
915
- **Script runs but nothing changes visually**: Call `app.redraw()` to force a screen refresh after modifications.
916
- **Color mode mismatch**: Document color space (RGB vs CMYK) must match color objects. Use `doc.documentColorSpace` to check.
917
- **Position seems wrong**: Remember scripted documents use bottom-left origin with Y increasing upward. The `position` property is the top-left of the bounding box.
918
- **Text not appearing**: Ensure the text frame has a non-zero size. For point text, set `position`; for area text, provide a valid path to `areaText()`.
919
- **File paths on Windows**: Use forward slashes (`/`) or double backslashes (`\\`) in path strings, or use the `File` object constructor.
920
- **Dialog boxes interrupting batch scripts**: Set `app.userInteractionLevel = UserInteractionLevel.DONTDISPLAYALERTS` before batch operations.
921
- **Collections use `getByName()`**: Many collection objects support `getByName("name")` which throws an error if not found; wrap in try/catch.
922
- **"Target layer cannot be modified"**: A locked layer, sublayer, or parent group (often a clip group like `Cover_Mask`) is blocking the edit. Recursively clear `locked` and `hidden` across the document before modifying. See [Recursively Unlock Layers and Groups](#recursively-unlock-layers-and-groups-before-editing).
923
- **"Unable to set placed item's file, is the file path provided valid?"**: The file exists and the path is correct, but `PlacedItem.file` does not accept the format. SVG is the most common cause — use the [open / copy / paste pattern](#placing-svg-content-copypaste-pattern) instead.
924
- **`RasterItem.file = newFile` does nothing or throws**: `RasterItem` does not expose a writable `file` property. Add a new `PlacedItem` to the same parent, restore the bounds and name, then `.remove()` the raster.
925
- **`arguments[0]` is `[object BridgeTalk]`** (or empty): The script was launched through ESTK `-run` or a `BridgeTalk` message; positional arguments are not forwarded. Use a sidecar file at a known absolute path. See [External Invocation & Argument Passing](#external-invocation--argument-passing).
926
- **`$.fileName` is empty**: Same external-launcher cause. Do not derive resource paths from `$.fileName` in scripts that may be invoked headlessly — use absolute paths or `Folder.temp`.
927
- **Script appears to do nothing**: Almost always either a locked ancestor, suppressed dialogs swallowing the error, or a missing explicit `saveAs` after edits. Add a top-level `try`/`catch` that logs to an absolute path to confirm execution and capture the error.
928
- **`item.resize(sx, sy)` recentered the artwork unexpectedly**: `resize` defaults to scaling around the item's center (`Transformation.CENTER`). Pass an explicit `scaleAbout` argument or follow with `translate(dx, dy)` to reposition.
929
930
## Scripting Constants Reference
931
932
Common enumeration constants used across the API:
933
934
| Category | Constants |
935
|---|---|
936
| **Color Space** | `DocumentColorSpace.RGB`, `DocumentColorSpace.CMYK` |
937
| **Justification** | `Justification.LEFT`, `Justification.CENTER`, `Justification.RIGHT`, `Justification.FULLJUSTIFY` |
938
| **Point Type** | `PointType.SMOOTH`, `PointType.CORNER` |
939
| **Stroke Cap** | `StrokeCap.BUTTENDCAP`, `StrokeCap.ROUNDENDCAP`, `StrokeCap.PROJECTINGENDCAP` |
940
| **Stroke Join** | `StrokeJoin.MITERENDJOIN`, `StrokeJoin.ROUNDENDJOIN`, `StrokeJoin.BEVELENDJOIN` |
941
| **Blend Mode** | `BlendModes.NORMAL`, `BlendModes.MULTIPLY`, `BlendModes.SCREEN`, `BlendModes.OVERLAY` |
942
| **Save Options** | `SaveOptions.SAVECHANGES`, `SaveOptions.DONOTSAVECHANGES`, `SaveOptions.PROMPTTOSAVECHANGES` |
943
| **Export Type** | `ExportType.PNG24`, `ExportType.PNG8`, `ExportType.JPEG`, `ExportType.SVG`, `ExportType.TIFF`, `ExportType.PHOTOSHOP`, `ExportType.AUTOCAD`, `ExportType.FLASH` |
944
| **Element Placement** | `ElementPlacement.PLACEATBEGINNING`, `ElementPlacement.PLACEATEND`, `ElementPlacement.PLACEBEFORE`, `ElementPlacement.PLACEAFTER`, `ElementPlacement.INSIDE` |
945
| **Z-Order** | `ZOrderMethod.BRINGTOFRONT`, `ZOrderMethod.SENDTOBACK`, `ZOrderMethod.BRINGFORWARD`, `ZOrderMethod.SENDBACKWARD` |
946
| **Gradient Type** | `GradientType.LINEAR`, `GradientType.RADIAL` |
947
| **Text Frame Kind** | `TextType.POINTTEXT`, `TextType.AREATEXT`, `TextType.PATHTEXT` |
948
| **Variable Kind** | `VariableKind.TEXTUAL`, `VariableKind.IMAGE`, `VariableKind.VISIBILITY`, `VariableKind.GRAPH` |
949
| **User Interaction** | `UserInteractionLevel.DISPLAYALERTS`, `UserInteractionLevel.DONTDISPLAYALERTS` |
950
| **Compatibility** | `Compatibility.ILLUSTRATOR10` through `Compatibility.ILLUSTRATOR24` |
951
952
## JavaScript Object Reference (Complete API Object List)
953
954
The Illustrator JavaScript API contains the following objects, grouped by category:
955
956
### Core Objects
957
958
`Application`, `Document`, `Documents`, `DocumentPreset`, `Layer`, `Layers`, `PageItem`, `PageItems`, `View`, `Views`, `Preferences`
959
960
### Path and Shape Objects
961
962
`PathItem`, `PathItems`, `PathPoint`, `PathPoints`, `CompoundPathItem`, `CompoundPathItems`, `GroupItem`, `GroupItems`
963
964
### Text Objects
965
966
`TextFrame`, `TextRange`, `TextRanges`, `TextPath`, `Characters`, `Words`, `Paragraphs`, `Lines`, `InsertionPoint`, `InsertionPoints`, `Story`, `Stories`, `CharacterAttributes`, `ParagraphAttributes`, `CharacterStyle`, `CharacterStyles`, `ParagraphStyle`, `ParagraphStyles`, `TextFont`, `TextFonts`, `TabStopInfo`
967
968
### Color Objects
969
970
`RGBColor`, `CMYKColor`, `GrayColor`, `LabColor`, `NoColor`, `SpotColor`, `Spot`, `Spots`, `PatternColor`, `GradientColor`, `Color`, `Gradient`, `Gradients`, `GradientStop`, `GradientStops`
971
972
### Swatch and Style Objects
973
974
`Swatch`, `Swatches`, `SwatchGroup`, `SwatchGroups`, `GraphicStyle`, `GraphicStyles`, `Pattern`, `Patterns`, `Brush`, `Brushes`
975
976
### Symbol Objects
977
978
`Symbol`, `Symbols`, `SymbolItem`, `SymbolItems`
979
980
### Artboard Objects
981
982
`Artboard`, `Artboards`
983
984
### Placed and Raster Objects
985
986
`PlacedItem`, `PlacedItems`, `RasterItem`, `RasterItems`, `MeshItem`, `MeshItems`, `GraphItem`, `GraphItems`, `PluginItem`, `PluginItems`, `NonNativeItem`, `NonNativeItems`, `LegacyTextItem`, `LegacyTextItems`
987
988
### Data-Driven Objects
989
990
`Variable`, `Variables`, `Dataset`, `Datasets`
991
992
### Matrix and Transform Objects
993
994
`Matrix`
995
996
### Tag Objects
997
998
`Tag`, `Tags`
999
1000
### Tracing Objects
1001
1002
`TracingObject`, `TracingOptions`
1003
1004
### Save and Export Options
1005
1006
`IllustratorSaveOptions`, `EPSSaveOptions`, `PDFSaveOptions`, `FXGSaveOptions`, `ExportOptionsAutoCAD`, `ExportOptionsFlash`, `ExportOptionsGIF`, `ExportOptionsJPEG`, `ExportOptionsPhotoshop`, `ExportOptionsPNG8`, `ExportOptionsPNG24`, `ExportOptionsSVG`, `ExportOptionsTIFF`
1007
1008
### Open Options
1009
1010
`OpenOptions`, `OpenOptionsAutoCAD`, `OpenOptionsFreeHand`, `OpenOptionsPhotoshop`, `PDFFileOptions`, `PhotoshopFileOptions`
1011
1012
### Print Objects
1013
1014
`PrintOptions`, `PrintJobOptions`, `PrintPaperOptions`, `PrintColorManagementOptions`, `PrintColorSeparationOptions`, `PrintCoordinateOptions`, `PrintFlattenerOptions`, `PrintFontOptions`, `PrintPageMarksOptions`, `PrintPostScriptOptions`, `Printer`, `PrinterInfo`, `Paper`, `PaperInfo`, `PPDFile`, `PPDFileInfo`, `Ink`, `InkInfo`, `Screen`, `ScreenInfo`, `ScreenSpotFunction`
1015
1016
### Image and Rasterize Options
1017
1018
`ImageCaptureOptions`, `RasterEffectOptions`, `RasterizeOptions`
1019
1020
## References
1021
1022
- [Changelog](https://ai-scripting.docsforadobe.dev/introduction/changelog/) - Recent scripting API changes (CC 2020 added `Document.getPageItemFromUuid` and `PageItem.uuid`; CC 2017 added `Application.getIsFileOpen`)
1023
- [Illustrator Scripting Guide](https://ai-scripting.docsforadobe.dev/) - Full community-maintained documentation
1024

© GitHub, Inc. · MIT · source · posted by @OpenSourceBuffGuy on promptparty.com

@OpenSourceBuffGuy

I find openly licensed prompts and post them here.

0 followers · 14,621 prompts

More by @OpenSourceBuffGuy

See all
Sea turtle carrying floating film studio island prompt image

Sea turtle carrying floating film studio island

Draws a giant sea turtle carrying a floating island film studio through a starry sky, where fairies polish rough film strips into golden film.

image-prompt, nano-banana, 3d-render, cartoon, fantasy-world, creatures, animals, whimsical, dreamy, cinematic, dramatic-lighting, vibrant-colors, bokeh, miniature, widescreen, night-scene, illustration, concept-art, surreal, storytelling, clay-3d

Desert buggy escapes drones past industrial outpost prompt image

Desert buggy escapes drones past industrial outpost

Builds a 15-second desert chase video where a racer in an armored buggy escapes drones past an industrial outpost, using five reference images with set jobs.

video-prompt, hailuo, action, multi-shot, timed-beats, camera-movement, reference-image, character-consistency, negative-prompt, cinematic, sci-fi, cars, landscape, aerial-view, tracking-shot, photorealistic, sound-effects, structured-output, long-form, widescreen

1 view
Cozy Pixel Art Farm Island Village prompt image

Cozy Pixel Art Farm Island Village

Draws a cozy 16-bit pixel-art farming village across six small islands joined by bridges, with exact counts for buildings, animals and crops.

image-prompt, gpt-image, pixel-art, isometric, game-assets, concept-art, maps, worldbuilding, cozy, vibrant-colors, ocean, landscape, wide-shot, widescreen, game-development, video-games, structured-output, whimsical, summer, high-angle, aerial-view, animals, negative-prompt, cityscape

1 view

Reviews

Loading reviews…

Discussion

Loading comments…