SKILL.md · 24000
s file, is the file path provided valid?`. The reliable way to bring SVG artwork into a document is to open the SVG as a separate document, select all, copy, close, and paste into the working document.
function placeSVG(targetDoc, svgFile, targetLayer) {
var donor = app.open(svgFile);
app.executeMenuCommand("selectall");
app.executeMenuCommand("copy");
donor.close(SaveOptions.DONOTSAVECHANGES);
app.activeDocument = targetDoc;
targetDoc.activeLayer = targetLayer;
app.executeMenuCommand("pasteFront");
var sel = targetDoc.selection;
if (!sel || sel.length === 0) return null;
if (sel.length === 1) return sel[0];
// Multiple pasted items: group them so callers get a single handle.
var group = targetLayer.groupItems.add();
for (var i = sel.length - 1; i >= 0; i--) {
sel[i].move(group, ElementPlacement.PLACEATBEGINNING);
}
return group;
}
Finding a Clipping Path Inside a Mask Group
Clip groups expose their clipping shape as a child PathItem (or, less
commonly, a child of a CompoundPathItem) with clipping === true. The
clip's geometricBounds give the visible frame to size or center content
against.
function findClipPath(group) {
var items = group.pageItems;
for (var i = 0; i < items.length; i++) {
var it = items[i];
try {
if (it.typename === "PathItem" && it.clipping) return it;
if (it.typename === "CompoundPathItem") {
for (var j = 0; j < it.pathItems.length; j++) {
if (it.pathItems[j].clipping) return it;
}
}
} catch (e) {}
}
return null;
}
Cover-Fit and Contain-Fit Sizing
To make an image fully cover a rectangle (any overflow hidden by a mask), use
the larger of the width/height ratios. To make it fit entirely inside, use
the smaller. A bleed factor (e.g. 1.10) lets a cover image extend slightly
past the clip edge.
function fitItemToRect(item, rect, mode, bleed) {
// rect = [L, T, R, B] (Illustrator: T > B)
var rw = rect[2] - rect[0];
var rh = rect[1] - rect[3];
var ib = item.geometricBounds;
var iw = ib[2] - ib[0];
var ih = ib[1] - ib[3];
if (iw <= 0 || ih <= 0) return;
var sx = rw / iw;
var sy = rh / ih;
var s = (mode === "cover" ? Math.max(sx, sy) : Math.min(sx, sy))
* (bleed || 1);
item.resize(s * 100, s * 100);
var cx = (rect[0] + rect[2]) / 2;
var cy = (rect[1] + rect[3]) / 2;
var b = item.geometricBounds;
var w = b[2] - b[0];
var h = b[1] - b[3];
item.position = [cx - w / 2, cy + h / 2];
}
Batch Process Files in a Folder
var folder = Folder.selectDialog("Select folder of .ai files");
if (folder) {
var files = folder.getFiles("*.ai");
for (var i = 0; i < files.length; i++) {
var doc = app.open(files[i]);
// Process each document...
doc.close(SaveOptions.DONOTSAVECHANGES);
}
}
Error Handling
try {
var doc = app.activeDocument;
var layer = doc.layers.getByName("NonExistentLayer");
} catch (e) {
alert("Error: " + e.message);
// e.message, e.line, e.fileName available
}
Troubleshooting
- "undefined is not an object": Usually means the collection is empty or the index is out of bounds. Check
.lengthbefore accessing items. - Script runs but nothing changes visually: Call
app.redraw()to force a screen refresh after modifications. - Color mode mismatch: Document color space (RGB vs CMYK) must match color objects. Use
doc.documentColorSpaceto check. - Position seems wrong: Remember scripted documents use bottom-left origin with Y increasing upward. The
positionproperty is the top-left of the bounding box. - Text not appearing: Ensure the text frame has a non-zero size. For point text, set
position; for area text, provide a valid path toareaText(). - File paths on Windows: Use forward slashes (
/) or double backslashes (\\) in path strings, or use theFileobject constructor. - Dialog boxes interrupting batch scripts: Set
app.userInteractionLevel = UserInteractionLevel.DONTDISPLAYALERTSbefore batch operations. - Collections use
getByName(): Many collection objects supportgetByName("name")which throws an error if not found; wrap in try/catch. - "Target layer cannot be modified": A locked layer, sublayer, or parent group (often a clip group like
Cover_Mask) is blocking the edit. Recursively clearlockedandhiddenacross the document before modifying. See Recursively Unlock Layers and Groups. - "Unable to set placed item's file, is the file path provided valid?": The file exists and the path is correct, but
PlacedItem.filedoes not accept the format. SVG is the most common cause — use the open / copy / paste pattern instead. RasterItem.file = newFiledoes nothing or throws:RasterItemdoes not expose a writablefileproperty. Add a newPlacedItemto the same parent, restore the bounds and name, then.remove()the raster.arguments[0]is[object BridgeTalk](or empty): The script was launched through ESTK-runor aBridgeTalkmessage; positional arguments are not forwarded. Use a sidecar file at a known absolute path. See External Invocation & Argument Passing.$.fileNameis empty: Same external-launcher cause. Do not derive resource paths from$.fileNamein scripts that may be invoked headlessly — use absolute paths orFolder.temp.- Script appears to do nothing: Almost always either a locked ancestor, suppressed dialogs swallowing the error, or a missing explicit
saveAsafter edits. Add a top-leveltry/catchthat logs to an absolute path to confirm execution and capture the error. item.resize(sx, sy)recentered the artwork unexpectedly:resizedefaults to scaling around the item's center (Transformation.CENTER). Pass an explicitscaleAboutargument or follow withtranslate(dx, dy)to reposition.
Scripting Constants Reference
Common enumeration constants used across the API:
| Category | Constants |
|---|---|
| Color Space | DocumentColorSpace.RGB, DocumentColorSpace.CMYK |
| Justification | Justification.LEFT, Justification.CENTER, Justification.RIGHT, Justification.FULLJUSTIFY |
| Point Type | PointType.SMOOTH, PointType.CORNER |
| Stroke Cap | StrokeCap.BUTTENDCAP, StrokeCap.ROUNDENDCAP, StrokeCap.PROJECTINGENDCAP |
| Stroke Join | StrokeJoin.MITERENDJOIN, StrokeJoin.ROUNDENDJOIN, StrokeJoin.BEVELENDJOIN |
| Blend Mode | BlendModes.NORMAL, BlendModes.MULTIPLY, BlendModes.SCREEN, BlendModes.OVERLAY |
| Save Options | SaveOptions.SAVECHANGES, SaveOptions.DONOTSAVECHANGES, SaveOptions.PROMPTTOSAVECHANGES |
| Export Type | ExportType.PNG24, ExportType.PNG8, ExportType.JPEG, ExportType.SVG, ExportType.TIFF, ExportType.PHOTOSHOP, ExportType.AUTOCAD, ExportType.FLASH |
| Element Placement | ElementPlacement.PLACEATBEGINNING, ElementPlacement.PLACEATEND, ElementPlacement.PLACEBEFORE, ElementPlacement.PLACEAFTER, ElementPlacement.INSIDE |
| Z-Order | ZOrderMethod.BRINGTOFRONT, ZOrderMethod.SENDTOBACK, ZOrderMethod.BRINGFORWARD, ZOrderMethod.SENDBACKWARD |
| Gradient Type | GradientType.LINEAR, GradientType.RADIAL |
| Text Frame Kind | TextType.POINTTEXT, TextType.AREATEXT, TextType.PATHTEXT |
| Variable Kind | VariableKind.TEXTUAL, VariableKind.IMAGE, VariableKind.VISIBILITY, VariableKind.GRAPH |
| User Interaction | UserInteractionLevel.DISPLAYALERTS, UserInteractionLevel.DONTDISPLAYALERTS |
| Compatibility | Compatibility.ILLUSTRATOR10 through Compatibility.ILLUSTRATOR24 |
JavaScript Object Reference (Complete API Object List)
The Illustrator JavaScript API contains the following objects, grouped by category:
Core Objects
Application, Document, Documents, DocumentPreset, Layer, Layers, PageItem, PageItems, View, Views, Preferences
Path and Shape Objects
PathItem, PathItems, PathPoint, PathPoints, CompoundPathItem, CompoundPathItems, GroupItem, GroupItems
Text Objects
TextFrame, TextRange, TextRanges, TextPath, Characters, Words, Paragraphs, Lines, InsertionPoint, InsertionPoints, Story, Stories, CharacterAttributes, ParagraphAttributes, CharacterStyle, CharacterStyles, ParagraphStyle, ParagraphStyles, TextFont, TextFonts, TabStopInfo
Color Objects
RGBColor, CMYKColor, GrayColor, LabColor, NoColor, SpotColor, Spot, Spots, PatternColor, GradientColor, Color, Gradient, Gradients, GradientStop, GradientStops
Swatch and Style Objects
Swatch, Swatches, SwatchGroup, SwatchGroups, GraphicStyle, GraphicStyles, Pattern, Patterns, Brush, Brushes
Symbol Objects
Symbol, Symbols, SymbolItem, SymbolItems
Artboard Objects
Artboard, Artboards
Placed and Raster Objects
PlacedItem, PlacedItems, RasterItem, RasterItems, MeshItem, MeshItems, GraphItem, GraphItems, PluginItem, PluginItems, NonNativeItem, NonNativeItems, LegacyTextItem, LegacyTextItems
Data-Driven Objects
Variable, Variables, Dataset, Datasets
Matrix and Transform Objects
Matrix
Tag Objects
Tag, Tags
Tracing Objects
TracingObject, TracingOptions
Save and Export Options
IllustratorSaveOptions, EPSSaveOptions, PDFSaveOptions, FXGSaveOptions, ExportOptionsAutoCAD, ExportOptionsFlash, ExportOptionsGIF, ExportOptionsJPEG, ExportOptionsPhotoshop, ExportOptionsPNG8, ExportOptionsPNG24, ExportOptionsSVG, ExportOptionsTIFF
Open Options
OpenOptions, OpenOptionsAutoCAD, OpenOptionsFreeHand, OpenOptionsPhotoshop, PDFFileOptions, PhotoshopFileOptions
Print Objects
PrintOptions, PrintJobOptions, PrintPaperOptions, PrintColorManagementOptions, PrintColorSeparationOptions, PrintCoordinateOptions, PrintFlattenerOptions, PrintFontOptions, PrintPageMarksOptions, PrintPostScriptOptions, Printer, PrinterInfo, Paper, PaperInfo, PPDFile, PPDFileInfo, Ink, InkInfo, Screen, ScreenInfo, ScreenSpotFunction
Image and Rasterize Options
ImageCaptureOptions, RasterEffectOptions, RasterizeOptions
References
- Changelog - Recent scripting API changes (CC 2020 added
Document.getPageItemFromUuidandPageItem.uuid; CC 2017 addedApplication.getIsFileOpen) - Illustrator Scripting Guide - Full community-maintained documentation