mcpField
A
adobe-illustrator-scripting

adobe-illustrator-scripting

github.com/githubクリエイティブ・メディア40.5k276 回インストール今日更新
リポジトリ

adobe-illustrator-scripting について

Adobe Illustrator Scripting は、Illustrator の自動化に使う ExtendScript の作成とデバッグを支援するスキルです。作品や文書の処理を自動化するユーザー向けに、オブジェクトモデルの資料と、書き出しや一括処理などの例を提供します。

主な機能

  1. 01Illustrator のスクリプティングオブジェクトモデルを解説
  2. 02ExtendScript の作成とデバッグ
  3. 03ドキュメント、レイヤー、パス、テキストの操作
  4. 04書き出しや一括処理のサンプル
  5. 05データ駆動型グラフィックや印刷の自動化

活用シーン

  1. 01Illustrator ドキュメントを編集するスクリプトの作成
  2. 02ファイルの一括処理と形式別書き出し
  3. 03データセットからグラフィックを生成
  4. 04Illustrator DOM を使うスクリプトのデバッグ

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/github/awesome-copilot --skill adobe-illustrator-scripting

インストール後、Claude Code で/adobe-illustrator-scriptingを入力して読み込まれたか確認します。

同梱ファイル

SKILL.md と一緒にインストールされる参考資料やスクリプト。

references/
object-model-quick-reference.md
scripts/
create-color-grid.jsx
batch-export-png.jsx
find-replace-text.jsx

詳細

Adobe Illustrator スクリプティング

ExtendScript(JavaScript/JSX)を使って Adobe Illustrator を自動化するための専門的なガイダンスです。このスキルでは、Illustrator のスクリプティングオブジェクトモデル、主要な API オブジェクトすべて、コードパターン、そして本番品質の .jsx スクリプトを作成するためのベストプラクティスを扱います。

同梱アセット

  • references/object-model-quick-reference.md:スクリプトの作成やデバッグ時に、Illustrator のスクリプティングオブジェクトモデル、一般的なドキュメントやページアイテムの種類、関連する DOM の概念を素早く確認できます。
  • scripts/:ドキュメントの操作、書き出し、バッチ処理、DOM の使用など、一般的なタスクの出発点や実装パターンとして使える Illustrator 自動化スクリプトの例が含まれています。動作する JSX のパターンが必要な場合や、デバッグ中に動作を比較したい場合は、これらの例を確認して応用してください。

このスキルを使用する場面

  • Illustrator の自動化スクリプト(.jsx または .js ファイル)を新規作成する
  • 既存の Illustrator ExtendScript コードをデバッグまたは修正する
  • ドキュメント、レイヤー、ページアイテム、パス、テキスト、色をプログラムで操作する
  • Illustrator ファイルをバッチ処理する、またはデータからアートワークを生成する
  • ドキュメントをさまざまな形式(PDF、SVG、PNG、EPS など)に書き出す
  • Illustrator DOM(Application、Document、Layer、PathItem、TextFrame など)を扱う
  • 変数やデータセットを使ってデータ駆動型のグラフィックを作成する
  • スクリプトによる印刷オプションを使って印刷ワークフローを自動化する

前提条件

  • Adobe Illustrator CC 以降がインストールされていること
  • JavaScript の基本的な知識(ExtendScript は Adobe 独自の拡張を含む ES3 ベースです)
  • スクリプトは、[ファイル]>[スクリプト]>[その他のスクリプト]、[スクリプト]メニュー、または Startup Scripts フォルダーに配置して実行します
  • .jsx ファイルの作成には、ExtendScript Toolkit(ESTK)または任意のテキストエディターを使用できます

スクリプティング環境

言語とファイル拡張子
言語拡張子プラットフォーム
ExtendScript/JavaScript.jsx, .jsWindows, macOS
AppleScript.scptmacOS のみ
VBScript.vbsWindows のみ

このスキルでは、クロスプラットフォームで最も広く使われている ExtendScript/JavaScript に重点を置いています。

スクリプトの実行
  • スクリプトメニュー:[ファイル]>[スクリプト]には、アプリケーションのスクリプトフォルダーにあるスクリプトが表示されます
  • その他のスクリプト:[ファイル]>[スクリプト]>[その他のスクリプト]から、任意の .jsx ファイルを選択して実行します
  • Startup Scripts:スクリプトを Startup Scripts フォルダーに配置すると、起動時に自動実行されます
  • Target ディレクティブ:ESTK または外部ツールから実行する場合は、スクリプトの先頭に #target illustrator を記述します
  • #targetengine ディレクティブ:#targetengine "session" を使うと、スクリプトの実行間で変数を保持できます
  • 外部からの呼び出し:スクリプトは、シェルスクリプト、タスクランナー、CI ジョブ、ExtendScript Toolkit(ExtendScript Toolkit.exe -run script.jsx)、または他の Adobe アプリからの BridgeTalk メッセージなどを通じて、Illustrator の外部から起動されることがよくあります。詳しくは外部からの呼び出しと引数の受け渡しを参照してください。
命名規則(JavaScript)
  • オブジェクトとプロパティにはキャメルケースを使います:activeDocument、pathItems、textFrames
  • app グローバルは Application オブジェクトを参照します
  • コレクションのインデックスはゼロ始まりです:documents[0] は最前面のドキュメントです
  • 実行時にオブジェクトの種類を識別するには typename プロパティを使います

オブジェクトモデルの概要

Illustrator DOM は、厳密な包含階層に従います:

Application (app)
├── activeDocument / documents[]
│   ├── layers[]
│   │   ├── pageItems[] (all artwork)
│   │   ├── pathItems[]
│   │   ├── compoundPathItems[]
│   │   ├── textFrames[]
│   │   ├── placedItems[]
│   │   ├── rasterItems[]
│   │   ├── meshItems[]
│   │   ├── pluginItems[]
│   │   ├── graphItems[]
│   │   ├── symbolItems[]
│   │   ├── nonNativeItems[]
│   │   ├── legacyTextItems[]
│   │   └── groupItems[]
│   ├── artboards[]
│   ├── views[]
│   ├── selection (array of selected items)
│   ├── swatches[], spots[], gradients[], patterns[]
│   ├── graphicStyles[], brushes[], symbols[]
│   ├── textFonts[] (via app.textFonts)
│   ├── stories[], characterStyles[], paragraphStyles[]
│   ├── variables[], datasets[]
│   └── inkList[], printOptions
├── preferences
├── printerList[]
└── textFonts[]
トップレベルオブジェクト
  • アプリケーション(app):ルートオブジェクトです。ドキュメント、環境設定、フォント、プリンターにアクセスできます。主なプロパティ:activeDocument、documents、textFonts、printerList、userInteractionLevel、version。
  • ドキュメント:開いている .ai ファイルを表します。主なプロパティ:layers、pageItems、selection、activeLayer、width、height、rulerOrigin、documentColorSpace。主なメソッド:saveAs()、exportFile()、close()、print()。
  • レイヤー:描画レイヤーです。主なプロパティ:pageItems、pathItems、textFrames、visible、locked、opacity、name、zOrderPosition、color。

単位と座標

単位

スクリプティング API の値はすべてポイントです(72 ポイント = 1 インチ)。ほかの単位は次のように変換します。

単位換算
インチ72 を掛ける
センチメートル28.346 を掛ける
ミリメートル2.834645 を掛ける
パイカ12 を掛ける

カーニング、トラッキング、aki プロパティでは、em 単位(フォントサイズに比例する em の千分の一)を使用します。

座標系
  • スクリプトで作成されたドキュメントでは、原点 (0,0) はアートボードの左下にあります
  • X は左から右に増加し、Y は下から上に増加します
  • ページアイテムの position プロパティは、バウンディングボックスの左上隅を [x, y] で表します
  • ページアイテムの幅と高さの上限:16348 ポイント
アートアイテムの境界

各ページアイテムには、次の 3 種類の境界矩形があります。

  • geometricBounds:線幅を含みません [left, top, right, bottom]
  • visibleBounds:線幅を含みます
  • controlBounds:制御点/方向点を含みます

ドキュメントの操作

作成と開く
// Create a new document
var doc = app.documents.add();

// Create with a preset
var preset = new DocumentPreset();
preset.width = 612;  // 8.5 inches
preset.height = 792; // 11 inches
preset.colorMode = DocumentColorSpace.CMYK;
var doc = app.documents.addDocument("Print", preset);

// Open an existing file
var fileRef = new File("/path/to/file.ai");
var doc = app.open(fileRef);
保存と書き出し
// Save as Illustrator format
var saveOpts = new IllustratorSaveOptions();
saveOpts.compatibility = Compatibility.ILLUSTRATOR17; // CC
doc.saveAs(new File("/path/to/output.ai"), saveOpts);

// Export as PDF
var pdfOpts = new PDFSaveOptions();
pdfOpts.compatibility = PDFCompatibility.ACROBAT7;
pdfOpts.preserveEditability = false;
doc.saveAs(new File("/path/to/output.pdf"), pdfOpts);

// Export as PNG
var pngOpts = new ExportOptionsPNG24();
pngOpts.horizontalScale = 300;
pngOpts.verticalScale = 300;
pngOpts.transparency = true;
doc.exportFile(new File("/path/to/output.png"), ExportType.PNG24, pngOpts);

// Export as SVG
var svgOpts = new ExportOptionsSVG();
svgOpts.fontType = SVGFontType.OUTLINEFONT;
doc.exportFile(new File("/path/to/output.svg"), ExportType.SVG, svgOpts);

パスと図形の操作

組み込みの図形メソッド

pathItems コレクションには、一般的な図形を作成するための便利なメソッドが用意されています。

var doc = app.activeDocument;
var layer = doc.activeLayer;

// Rectangle: rectangle(top, left, width, height)
var rect = layer.pathItems.rectangle(500, 100, 200, 150);

// Rounded rectangle: roundedRectangle(top, left, width, height, hRadius, vRadius)
var rrect = layer.pathItems.roundedRectangle(500, 100, 200, 150, 20, 20);

// Ellipse: ellipse(top, left, width, height)
var oval = layer.pathItems.ellipse(400, 200, 100, 100);

// Polygon: polygon(centerX, centerY, radius, sides)
var hex = layer.pathItems.polygon(300, 300, 50, 6);

// Star: star(centerX, centerY, radius, innerRadius, points)
var star = layer.pathItems.star(300, 300, 50, 25, 5);
座標配列を使った自由形式のパス
var doc = app.activeDocument;
var path = doc.pathItems.add();
path.setEntirePath([[100, 100], [200, 200], [300, 100]]);
path.closed = false;
path.stroked = true;
path.strokeWidth = 2;
PathPoint オブジェクトを使った自由形式のパス
var doc = app.activeDocument;
var path = doc.pathItems.add();

var point1 = path.pathPoints.add();
point1.anchor = [100, 100];
point1.leftDirection = [100, 100];
point1.rightDirection = [150, 150];
point1.pointType = PointType.SMOOTH;

var point2 = path.pathPoints.add();
point2.anchor = [300, 100];
point2.leftDirection = [250, 150];
point2.rightDirection = [300, 100];
point2.pointType = PointType.SMOOTH;

path.closed = false;
パスのプロパティ
var item = doc.pathItems[0];
item.filled = true;
item.stroked = true;
item.strokeWidth = 1.5;
item.strokeCap = StrokeCap.ROUNDENDCAP;
item.strokeJoin = StrokeJoin.ROUNDENDJOIN;
item.opacity = 80;
item.closed = true;

色の操作

Color オブジェクト
// RGB Color (values 0-255)
var red = new RGBColor();
red.red = 255;
red.green = 0;
red.blue = 0;

// CMYK Color (values 0-100)
var cyan = new CMYKColor();
cyan.cyan = 100;
cyan.magenta = 0;
cyan.yellow = 0;
cyan.black = 0;

// Grayscale (0-100, 0 = black)
var gray = new GrayColor();
gray.gray = 50;

// Lab Color
var lab = new LabColor();
lab.l = 50;
lab.a = 20;
lab.b = -30;

// No color (transparent)
var none = new NoColor();
色の適用
var item = doc.pathItems[0];
item.fillColor = red;
item.strokeColor = cyan;

// Gradient fill
var gradient = doc.gradients.add();
gradient.type = GradientType.LINEAR;
gradient.gradientStops[0].color = red;
gradient.gradientStops[1].color = cyan;

var gradColor = new GradientColor();
gradColor.gradient = gradient;
item.fillColor = gradColor;
スポットカラーとスウォッチ
// Create a spot color
var spot = doc.spots.add();
spot.name = "My Spot Color";
spot.color = red; // Base color definition

var spotColor = new SpotColor();
spotColor.spot = spot;
spotColor.tint = 100;

item.fillColor = spotColor;

// Access a swatch by name
var swatch = doc.swatches.getByName("PANTONE 185 C");
item.fillColor = swatch.color;

テキストの操作

テキストフレームの種類
var doc = app.activeDocument;

// Point text
var pointText = doc.textFrames.add();
pointText.contents = "Hello World!";
pointText.position = [100, 500];

// Area text (text inside a path)
var rectPath = doc.pathItems.rectangle(500, 100, 200, 100);
var areaText = doc.textFrames.areaText(rectPath);
areaText.contents = "Text inside a rectangle shape.";

// Path text (text along a path)
var curvePath = doc.pathItems.add();
curvePath.setEntirePath([[50, 300], [150, 400], [250, 300]]);
var pathText = doc.textFrames.pathText(curvePath);
pathText.contents = "Text on a path";
文字と段落の書式設定
var tf = doc.textFrames[0];
var textRange = tf.textRange;

// Character attributes
var charAttr = textRange.characterAttributes;
charAttr.size = 24;           // Font size in points
charAttr.textFont = app.textFonts.getByName("ArialMT");
charAttr.fillColor = red;
charAttr.tracking = 50;       // Em units
charAttr.horizontalScale = 100;
charAttr.verticalScale = 100;
charAttr.baselineShift = 0;

// Paragraph attributes
var paraAttr = textRange.paragraphAttributes;
paraAttr.justification = Justification.CENTER;
paraAttr.firstLineIndent = 0;
paraAttr.leftIndent = 0;
paraAttr.spaceBefore = 0;
paraAttr.spaceAfter = 0;
テキストコンテンツへのアクセス
var tf = doc.textFrames[0];

// Access sub-ranges
var firstChar = tf.characters[0];
var firstWord = tf.words[0];
var firstPara = tf.paragraphs[0];
var firstLine = tf.lines[0];

// Modify specific ranges
tf.words[0].characterAttributes.size = 36;
tf.paragraphs[0].paragraphAttributes.justification = Justification.LEFT;
テキストフレームの連結
var frame1 = doc.textFrames.areaText(path1);
var frame2 = doc.textFrames.areaText(path2);

// Link frames so text flows from frame1 to frame2
frame1.nextFrame = frame2;

// Stories represent the full text across threaded frames
var storyCount = doc.stories.length;
var fullText = doc.stories[0].textRange.contents;

レイヤーの操作

var doc = app.activeDocument;

// Create a layer
var newLayer = doc.layers.add();
newLayer.name = "Background";
newLayer.visible = true;
newLayer.locked = false;
newLayer.opacity = 100;

// Access existing layers
var topLayer = doc.layers[0];
var layerByName = doc.layers.getByName("Background");

// Move items between layers
var item = doc.pathItems[0];
item.move(newLayer, ElementPlacement.PLACEATBEGINNING);

// Reorder layers
newLayer.zOrder(ZOrderMethod.SENDTOBACK);

選択範囲の操作

// Get current selection
var sel = app.activeDocument.selection;

// Iterate selected items
for (var i = 0; i < sel.length; i++) {
    var item = sel[i];
    // Check type using typename
    if (item.typename === "PathItem") {
        item.fillColor = red;
    } else if (item.typename === "TextFrame") {
        item.contents = "Modified";
    }
}

// Select an item programmatically
doc.pathItems[0].selected = true;

// Deselect all
doc.selection = null;

シンボルの操作

// Place a symbol instance
var sym = doc.symbols.getByName("MySymbol");
var instance = doc.symbolItems.add(sym);
instance.position = [200, 400];

// Access symbol definition
var symDef = instance.symbol;

// Break link to symbol (expand to regular art)
instance.breakLink();

変形

var item = doc.pathItems[0];

// Rotate 45 degrees around center
item.rotate(45);

// Scale to 50% width, 75% height
item.resize(50, 75);

// Translate (move) by 100 points right and 50 points up
item.translate(100, 50);

// Using a transformation matrix
var matrix = app.getIdentityMatrix();
matrix = app.concatenateRotationMatrix(matrix, 30);
matrix = app.concatenateScaleMatrix(matrix, 150, 150);
item.transform(matrix);

アートボードの操作

var doc = app.activeDocument;

// Access artboards
var ab = doc.artboards[0];
var rect = ab.artboardRect; // [left, top, right, bottom]

// Create a new artboard
var newAB = doc.artboards.add([0, 0, 612, 792]); // Letter size
newAB.name = "Page 2";

// Set active artboard
doc.artboards.setActiveArtboardIndex(1);

データ駆動型グラフィック(変数とデータセット)

// Variables link document items to data fields
var v = doc.variables.add();
v.kind = VariableKind.TEXTUAL;
v.name = "headline";

// Link a text frame to the variable
var tf = doc.textFrames[0];
tf.contentVariable = v;

// Create datasets for batch content
var ds = doc.dataSets.add();
ds.name = "Version 1";
// Dataset captures current variable bindings

// Switch datasets to swap content
doc.dataSets[0].display();

印刷

var doc = app.activeDocument;
var opts = new PrintOptions();

opts.printPreset = "Default";

// Paper options
var paperOpts = new PrintPaperOptions();
paperOpts.name = "Letter";
opts.paperOptions = paperOpts;

// Job options
var jobOpts = new PrintJobOptions();
jobOpts.copies = 1;
jobOpts.designation = PrintArtworkDesignation.VISIBLELAYERS;
opts.jobOptions = jobOpts;

doc.print(opts);

ユーザー操作レベル

スクリプトの実行中に Illustrator のダイアログを表示するかどうかを制御します。

// Suppress all dialogs
app.userInteractionLevel = UserInteractionLevel.DONTDISPLAYALERTS;

// Perform operations that might prompt dialogs...
doc.close(SaveOptions.DONOTSAVECHANGES);

// Restore dialog display
app.userInteractionLevel = UserInteractionLevel.DISPLAYALERTS;

メソッドの使用(JavaScript 固有)

複数の省略可能なパラメーターを持つメソッドを呼び出す場合、途中のパラメーターを省略するには undefined を使用します。

// rotate(angle, [changePositions], [changeFillPatterns], [changeFillGradients], ...)
item.rotate(30, undefined, undefined, true);

外部からの呼び出しと引数の受け渡し

Illustrator スクリプトは、シェルスクリプト、スケジューラー、ビルドパイプライン、ExtendScript Toolkit、ほかの Creative Cloud アプリからの BridgeTalk メッセージなどを通じて、アプリケーションの外部から定期的に起動されます。こうした起動方法での実行環境は、アプリケーション内の ファイル > スクリプト から実行する場合とはいくつかの点で異なり、正しく動作するはずのコードが頻繁に失敗する原因になります。

外部からの起動では arguments[] が信頼できません

ExtendScript Toolkit の -run 呼び出しと BridgeTalk.send() は、起動側から渡された任意の引数をスクリプトのトップレベルの arguments[] 配列に引き渡しません。多くの設定では、下に示すように、配列には呼び出し側が渡した値ではなく、単一の [object BridgeTalk] 要素が含まれます。

// At top of script
var passed = (typeof arguments !== "undefined") ? arguments : [];
for (var i = 0; i < passed.length; i++) {
    $.writeln("arg[" + i + "] = " + passed[i]);
    // Often prints: arg[0] = [object BridgeTalk]
}

スクリプトを外部から起動する場合、必須の入力に arguments[] を使わないでください。 次のような、より信頼性の高い方法を使用してください。

パラメーター用サイドカーファイル

外部ランチャーから実行したときにスクリプトが失敗し、エラーの原因がはっきりしない場合は、サイドカーファイルを使用してください。呼び出し元で既知の絶対パスに小さなテキストファイルを書き込み、起動時に読み込みます。この方法はランチャー固有の挙動に左右されず、実行失敗後に内容を簡単に確認できます。

var SIDECAR_PATH = "C:/Users/userName/job.args.txt";

function readSidecar(path) {
    var f = new File(path);
    if (!f.exists || !f.open("r")) return null;
    var lines = [];
    while (!f.eof) {
        var ln = f.readln();
        if (ln && !/^\s*$/.test(ln)) lines.push(ln);
    }
    f.close();
    return {
        input:  lines[0],
        output: lines[1],
        mode:   lines[2]
    };
}

key=value 形式も同様に使いやすく、位置による不安定さを避けられます。

input=C:/path/to/input.ai
output=C:/path/to/output.pdf
mode=preview
環境変数

$.getenv("NAME") は、ランチャーではなくIllustrator のプロセスから参照できる環境変数を返します。ランチャーから渡す値を Illustrator に認識させるには、起動前にシステム全体、または Illustrator の親プロセスの環境で変数を設定する必要があります。呼び出しごとに異なる値を渡す場合は、サイドカーファイルを使用してください。

$.fileName と File($.fileName).parent

アプリケーション内で実行する場合、$.fileName は実行中のスクリプトの絶対パスで、File($.fileName).parent はスクリプトのフォルダーを返します。一部の外部ランチャー(特に ESTK の -run)では、$.fileName が空になる場合があり、その結果、相対パスの解決がエラーなく失敗することがあります。

// Fragile: returns null under some launchers
var here = $.fileName ? File($.fileName).parent : null;
var sidecar = here ? new File(here.fsName + "/job.args.txt") : null;

// Robust: hardcode a known absolute path or fall back to a stable location
var sidecar = new File("C:/Users/userName/job.args.txt");
if (!sidecar.exists) sidecar = new File(Folder.temp.fsName + "/job.args.txt");
絶対パスへの診断ログ

ダイアログが抑制され、ランチャーが $.writeln の出力を表示しないことがあるため、サイレント失敗はよく起こります。既知の絶対パスにプレーンテキストのログを書き込み、実行後に内容を確認できるようにしてください。最初の呼び出しでディレクトリーが見つからず失敗しないよう、必要に応じて親フォルダーを作成します。

var LOG_PATH = "C:/Users/userName/logs/job.log";

function log(msg) {
    try {
        var f = new File(LOG_PATH);
        try { if (!f.parent.exists) f.parent.create(); } catch (eDir) {}
        if (f.open("a")) {
            f.writeln("[" + new Date() + "] " + msg);
            f.close();
        }
    } catch (e) {}
}
エントリーポイントを try { ... } catch で囲む

外部から起動したスクリプトは、目に見える通知なしに失敗することがよくあります。最上位の try/catch でエラーをログファイルに書き込めば、サイレント失敗を確認可能な1行のメッセージに変換できます。

try {
    main();
} catch (err) {
    log("FATAL: " + err + (err && err.line ? " line=" + err.line : ""));
}
ユーザー操作を抑制する

外部の呼び出し元からダイアログに応答することはできません。DOM の操作を始める前にダイアログを無効にし、ヘッドレスで起動する可能性のあるスクリプトでは alert()/confirm()/prompt() を一切使わないでください。

app.userInteractionLevel = UserInteractionLevel.DONTDISPLAYALERTS;
明示的に保存する

Illustrator を閉じたり、アイドル状態に戻したりしても、作業中のファイルは保存されません。DOM の編集がすべて終わったら、doc.saveAs(...)(または doc.save())を明示的に呼び出し、成功したかどうかをログに記録してください。

var opts = new IllustratorSaveOptions();
opts.compatibility = Compatibility.ILLUSTRATOR17;
doc.saveAs(new File(doc.fullName.fsName), opts);

よく使われるパターン

ドキュメント内のすべてのページアイテムを反復処理する
function processAllItems(doc) {
    for (var i = 0; i < doc.pageItems.length; i++) {
        var item = doc.pageItems[i];
        // Process based on type
        switch (item.typename) {
            case "PathItem":
                // handle path
                break;
            case "TextFrame":
                // handle text
                break;
            case "GroupItem":
                // handle group (may contain nested items)
                break;
        }
    }
}
編集前にレイヤーとグループのロックを再帰的に解除する

ロックされたレイヤー、またはロックされた祖先(親グループ、クリップグループ、サブレイヤー)があると、編集時に Error: Target layer cannot be modified が発生します。DOM を変更する前に、階層全体をたどって locked/hidden フラグを解除してください。

function unlockAll(doc) {
    function visitLayers(layers) {
        for (var i = 0; i < layers.length; i++) {
            var lyr = layers[i];
            try { lyr.locked = false; lyr.visible = true; } catch (e) {}
            visitItems(lyr);
            if (lyr.layers && lyr.layers.length) visitLayers(lyr.layers);
        }
    }
    function visitItems(container) {
        var items = container.pageItems;
        for (var j = 0; j < items.length; j++) {
            var it = items[j];
            try { it.locked = false; it.hidden = false; } catch (e) {}
            if (it.typename === "GroupItem") visitItems(it);
        }
    }
    visitLayers(doc.layers);
}
リンク画像の背後にあるファイルを置き換える(再リンク)

PlacedItem.file = newFile を使うと、親、重なり順、および(再適用後の)境界を維持したままリンク画像を置き換えられます。RasterItem は書き込み可能な file プロパティを公開しません。そのため、プレースホルダーがラスターの場合は、同じ親に新しい PlacedItem を追加し、境界をコピーしてから、元のアイテムを削除する必要があります。

function relinkOrRebuild(item, newFile) {
    var bounds = item.geometricBounds.slice();
    var parent = item.parent;
    var name   = item.name;

    if (item.typename === "PlacedItem") {
        item.file = newFile;
        item.geometricBounds = bounds;
        return item;
    }

    // RasterItem path: rebuild as a linked PlacedItem in the same parent.
    var fresh = parent.placedItems.add();
    fresh.file = newFile;
    fresh.geometricBounds = bounds;
    if (name) try { fresh.name = name; } catch (e) {}
    fresh.move(item, ElementPlacement.PLACEBEFORE);
    item.remove();
    return fresh;
}
SVG コンテンツを配置する(コピー/ペーストパターン)

PlacedItem.file はラスター形式と AI/PDF を受け付けますが、SVG は受け付けません。.svg ファイルを設定すると、Unable to set placed item's file, is the file path provided valid? が発生します。SVG アートワークをドキュメントに取り込む確実な方法は、SVG を別のドキュメントとして開き、すべてを選択してコピーし、そのドキュメントを閉じてから、作業中のドキュメントにペーストすることです。

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;
}
マスクグループ内のクリッピングパスを見つける

クリップグループでは、クリッピング形状が子の PathItem(まれに CompoundPathItem の子)として公開され、その clipping === true で判別できます。クリップの geometricBounds は、コンテンツのサイズ調整や中央揃えの基準となる表示フレームを示します。

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;
}
カバーフィットとコンテインフィットのサイズ調整

画像を長方形全体に表示する(はみ出した部分はマスクで隠す)には、幅と高さの比率のうち大きい方を使います。画像全体を長方形内に収めるには、小さい方を使います。ブリード係数(例:1.10)を指定すると、カバー画像をクリップの端よりわずかに外側まで広げられます。

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];
}
フォルダー内のファイルを一括処理する
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);
    }
}
エラー処理
try {
    var doc = app.activeDocument;
    var layer = doc.layers.getByName("NonExistentLayer");
} catch (e) {
    alert("Error: " + e.message);
    // e.message, e.line, e.fileName available
}

トラブルシューティング

  • 「undefined is not an object」:通常、コレクションが空か、インデックスが範囲外であることを意味します。項目にアクセスする前に .length を確認してください。
  • スクリプトは実行されるが、見た目に変化がない:変更後に画面を強制的に更新するには、app.redraw() を呼び出してください。
  • カラーモードの不一致:ドキュメントのカラースペース(RGB または CMYK)は、カラーオブジェクトと一致している必要があります。doc.documentColorSpace を使って確認してください。
  • 位置がおかしいように見える:スクリプトで扱うドキュメントでは、原点は左下で、Y 軸は上向きに増加することに注意してください。position プロパティは、バウンディングボックスの左上を示します。
  • テキストが表示されない:テキストフレームのサイズがゼロでないことを確認してください。ポイントテキストの場合は position を設定し、エリアテキストの場合は areaText() に有効なパスを指定してください。
  • Windows でのファイルパス:パス文字列ではスラッシュ(/)または二重バックスラッシュ(\\)を使うか、File オブジェクトのコンストラクターを使用してください。
  • ダイアログボックスによってバッチスクリプトが中断される:バッチ処理の前に app.userInteractionLevel = UserInteractionLevel.DONTDISPLAYALERTS を設定してください。
  • コレクションでは getByName() を使用する:多くのコレクションオブジェクトは getByName("name") をサポートしています。見つからない場合はエラーが発生するため、try/catch で囲んでください。
  • 「Target layer cannot be modified」:ロックされたレイヤー、サブレイヤー、または親グループ(Cover_Mask のようなクリッピンググループであることがよくあります)が編集を妨げています。変更前に、ドキュメント全体で locked と hidden を再帰的に解除してください。レイヤーとグループのロックを再帰的に解除するを参照してください。
  • 「Unable to set placed item's file, is the file path provided valid?」:ファイルは存在し、パスも正しいものの、PlacedItem.file がその形式に対応していません。最もよくある原因は SVG です。その場合は、代わりに開く/コピー/ペーストのパターンを使用してください。
  • RasterItem.file = newFile が何もしない、またはエラーを発生させる:RasterItem は書き込み可能な file プロパティを公開していません。同じ親に新しい PlacedItem を追加し、境界と名前を復元してから、ラスター項目を .remove() してください。
  • arguments[0] が [object BridgeTalk](または空)になる:スクリプトは ESTK の -run または BridgeTalk メッセージを通じて起動されており、位置引数は渡されていません。既知の絶対パスにサイドカーファイルを配置してください。外部からの起動と引数の受け渡しを参照してください。
  • $.fileName が空になる:外部ランチャーが原因で、上記と同じ状況です。ヘッドレスで起動される可能性のあるスクリプトでは、$.fileName からリソースパスを導出しないでください。絶対パスまたは Folder.temp を使用してください。
  • スクリプトが何もしていないように見える:ほとんどの場合、ロックされた親要素、エラーを隠してしまうダイアログの抑制、または編集後に明示的な saveAs がないことが原因です。実行を確認してエラーを記録できるよう、絶対パスにログを出力するトップレベルの try/catch を追加してください。
  • item.resize(sx, sy) によってアートワークが予期せず再センタリングされた:resize はデフォルトで項目の中心(Transformation.CENTER)を基準に拡大縮小します。明示的な scaleAbout 引数を渡すか、その後に translate(dx, dy) を使って位置を調整してください。

スクリプト定数リファレンス

API 全体で使用される一般的な列挙定数:

カテゴリ定数
カラースペースDocumentColorSpace.RGB, DocumentColorSpace.CMYK
文字揃えJustification.LEFT, Justification.CENTER, Justification.RIGHT, Justification.FULLJUSTIFY
ポイントの種類PointType.SMOOTH, PointType.CORNER
線端StrokeCap.BUTTENDCAP, StrokeCap.ROUNDENDCAP, StrokeCap.PROJECTINGENDCAP
線の結合StrokeJoin.MITERENDJOIN, StrokeJoin.ROUNDENDJOIN, StrokeJoin.BEVELENDJOIN
描画モードBlendModes.NORMAL, BlendModes.MULTIPLY, BlendModes.SCREEN, BlendModes.OVERLAY
保存オプションSaveOptions.SAVECHANGES, SaveOptions.DONOTSAVECHANGES, SaveOptions.PROMPTTOSAVECHANGES
書き出し形式ExportType.PNG24, ExportType.PNG8, ExportType.JPEG, ExportType.SVG, ExportType.TIFF, ExportType.PHOTOSHOP, ExportType.AUTOCAD, ExportType.FLASH
要素の配置ElementPlacement.PLACEATBEGINNING, ElementPlacement.PLACEATEND, ElementPlacement.PLACEBEFORE, ElementPlacement.PLACEAFTER, ElementPlacement.INSIDE
重ね順ZOrderMethod.BRINGTOFRONT, ZOrderMethod.SENDTOBACK, ZOrderMethod.BRINGFORWARD, ZOrderMethod.SENDBACKWARD
グラデーションの種類GradientType.LINEAR, GradientType.RADIAL
テキストフレームの種類TextType.POINTTEXT, TextType.AREATEXT, TextType.PATHTEXT
変数の種類VariableKind.TEXTUAL, VariableKind.IMAGE, VariableKind.VISIBILITY, VariableKind.GRAPH
ユーザー操作UserInteractionLevel.DISPLAYALERTS, UserInteractionLevel.DONTDISPLAYALERTS
互換性Compatibility.ILLUSTRATOR10 から Compatibility.ILLUSTRATOR24 まで

JavaScript オブジェクトリファレンス(API オブジェクト一覧)

Illustrator JavaScript API には、カテゴリ別に以下のオブジェクトが含まれています。

コアオブジェクト

Application、Document、Documents、DocumentPreset、Layer、Layers、PageItem、PageItems、View、Views、Preferences

パスとシェイプのオブジェクト

PathItem、PathItems、PathPoint、PathPoints、CompoundPathItem、CompoundPathItems、GroupItem、GroupItems

テキストオブジェクト

TextFrame、TextRange、TextRanges、TextPath、Characters、Words、Paragraphs、Lines、InsertionPoint、InsertionPoints、Story、Stories、CharacterAttributes、ParagraphAttributes、CharacterStyle、CharacterStyles、ParagraphStyle、ParagraphStyles、TextFont、TextFonts、TabStopInfo

カラーオブジェクト

RGBColor、CMYKColor、GrayColor、LabColor、NoColor、SpotColor、Spot、Spots、PatternColor、GradientColor、Color、Gradient、Gradients、GradientStop、GradientStops

スウォッチとスタイルのオブジェクト

Swatch、Swatches、SwatchGroup、SwatchGroups、GraphicStyle、GraphicStyles、Pattern、Patterns、Brush、Brushes

シンボルオブジェクト

Symbol、Symbols、SymbolItem、SymbolItems

アートボードオブジェクト

Artboard、Artboards

配置オブジェクトとラスターオブジェクト

PlacedItem、PlacedItems、RasterItem、RasterItems、MeshItem、MeshItems、GraphItem、GraphItems、PluginItem、PluginItems、NonNativeItem、NonNativeItems、LegacyTextItem、LegacyTextItems

データ駆動型オブジェクト

Variable、Variables、Dataset、Datasets

マトリックスと変形のオブジェクト

Matrix

タグオブジェクト

Tag、Tags

トレースオブジェクト

TracingObject、TracingOptions

保存と書き出しのオプション

IllustratorSaveOptions、EPSSaveOptions、PDFSaveOptions、FXGSaveOptions、ExportOptionsAutoCAD、ExportOptionsFlash、ExportOptionsGIF、ExportOptionsJPEG、ExportOptionsPhotoshop、ExportOptionsPNG8、ExportOptionsPNG24、ExportOptionsSVG、ExportOptionsTIFF

開くオプション

OpenOptions、OpenOptionsAutoCAD、OpenOptionsFreeHand、OpenOptionsPhotoshop、PDFFileOptions、PhotoshopFileOptions

印刷オブジェクト

PrintOptions、PrintJobOptions、PrintPaperOptions、PrintColorManagementOptions、PrintColorSeparationOptions、PrintCoordinateOptions、PrintFlattenerOptions、PrintFontOptions、PrintPageMarksOptions、PrintPostScriptOptions、Printer、PrinterInfo、Paper、PaperInfo、PPDFile、PPDFileInfo、Ink、InkInfo、Screen、ScreenInfo、ScreenSpotFunction

画像とラスタライズのオプション

ImageCaptureOptions、RasterEffectOptions、RasterizeOptions

参考資料

  • 変更履歴 - 最近のスクリプティング API の変更(CC 2020 では Document.getPageItemFromUuid と PageItem.uuid が追加され、CC 2017 では Application.getIsFileOpen が追加されました)
  • Illustrator スクリプティングガイド - コミュニティによって保守されている包括的なドキュメント

コメント