你用的是 Mac 吗?如果是这样,您可以将 AppleScript 与osascript
执行 JavaScript 的工具。这里有些例子:
运行 JSX 并返回值
将其保存为 ~/temp/foo.scpt:
tell application "Adobe Illustrator"
-- 'do javascript' runs any arbitrary JS.
-- We're using the #include feature to run another
-- file. (That's an Adobe extension to JS.)
--
-- You have to pass a full, absolute path to #include.
--
-- The documentation alleges that 'do javascript'
-- can be passed an AppleScript file object, but
-- I wasn't able to get that to work.
do javascript "#include ~/temp/foo.jsx"
end tell
并将其保存为 ~/temp/foo.jsx:
var doc = app.activeDocument;
var numLayers = doc.layers.length;
// The last value in the JSX file will be printed out by
// osascript.
numLayers;
现在,从命令行运行osascript ~/temp/foo.scpt
它将打印活动 Illustrator 文档中的图层数。
从 JavaScript 中获取数据是有限制的。您无法从 JavaScript 中打印到标准输出。相反,请将要返回的值作为 JSX 文件的最后一条语句;它将被打印osascript
。 (原因如下:JSX 文件中的最后一个值是do javascript
AppleScript 声明。这也是 AppleScript 文件中的最后一个值,并且osascript
打印最终值。)
从 JavaScript 返回的值可以是数字、字符串、数组或转换为字符串时保留其值的任何其他值。如果你想返回一个复杂的对象,你需要#include一个JSON库并调用.toJSONString()
在物体上。
将参数传递给 JSX
要将参数传递给 JSX 代码,请遵循以下示例:
文件~/temp/args.scpt:
on run argv
tell application "Adobe Illustrator"
set js to "#include '~/temp/args.jsx';" & return
set js to js & "main(arguments);" & return
do javascript js with arguments argv
end tell
end run
文件〜/temp/args.jsx
function main(argv) {
var layer = app.activeDocument.activeLayer;
app.defaultStroked = true;
app.defaultFilled = true;
// Top, left, width, height (in points).
// Note that parameters start at argv[0].
layer.pathItems.rectangle(argv[0], argv[1], argv[2], argv[3]);
}
然后运行osascript args.scpt 50 30 10 80
调试
The do javascript
命令还具有启动 ExtendScript 调试器的选项。有关详细信息,请在 AppleScript 编辑器中打开 Illustrator 词典。