使用JXA替换Keynote中的字体

时间:2017-03-21 01:00:53

标签: javascript applescript automator jxa keynote

我试图在Keynote中查找/替换有问题的字体,并发现this script使用JXA更改字体,但需要扫描每个字符和文本对象以查找有问题的字体。

我试过这个开始,但有条件的不起作用。救命啊!

PROBLEM_FONT = 'Arial'
REPLACEMENT_FONT = 'Helvetica'

document = Application('Keynote').documents[0]
for slide in document.slides
  for textItem in slide.textItems
    if textItem.objectText.font == PROBLEM_FONT
        textItem.objectText.font = REPLACEMENT_FONT

1 个答案:

答案 0 :(得分:1)

您提到的GitHub要点是用CoffeeScript编写的,而不是JavaScript。它需要编译(转换)为JavaScript。您的脚本是另一个脚本的摘录,也是用CoffeeScript编写的。

这是一个快速的香草JS版脚本:

var PROBLEM_FONT = 'Arial';
var REPLACEMENT_FONT = 'Helvetica';
var slides = Application('Keynote').documents[0].slides;

for (var i = 0; i < slides.length; i++) {
    var slide = slides[i];
    for (var j = 0; j < slide.textItems.length; j++) {
        var textItem = slide.textItems[j];
        if (textItem.objectText.font === PROBLEM_FONT) {
            textItem.objectText.font = REPLACEMENT_FONT;
        }
    }
}

重要提示:Arial的字体名称不同于&#39;;例如,斜体Arial被列为&#34; Arial-ItalicMT&#34;。您的脚本没有考虑到这一点,这可能是条件语句失败的原因。

您可能希望添加子字符串检查,如下所示:

(未经测试,但希望你能得到这个想法)

var PROBLEM_FONT = 'Arial';
var REPLACEMENT_FONT = 'Helvetica';
var slides = Application('Keynote').documents[0].slides;

for (var i = 0; i < slides.length; i++) {
    var slide = slides[i];
    for (var j = 0; j < slide.textItems.length; j++) {
        var textItem = slide.textItems[j];
        if (textItem.objectText.font.indexOf(PROBLEM_FONT) !== -1) {
            textItem.objectText.font = REPLACEMENT_FONT;
        }
    }
}

如果它有帮助,这里是纯AppleScript版本,其中包括字体名称的子字符串检查。我已经在macOS Sierra上用Keynote 7.0.5成功测试了这个。

tell application "Keynote"

    if (front document exists) then
        tell every slide of front document

            -- Targeting body text
            tell every text item
                if (the font of its object text as text) contains "Arial" then
                    set the font of its object text to "Monaco"
                end if
            end tell

            -- Targeting slide titles
            tell default title item
                if (the font of its object text as text) contains "Arial" then
                    set the font of its object text to "Monaco"
                end if
            end tell

            -- Targeting text boxes within groups
            tell every group

                tell every text item
                    if (the font of its object text as text) contains "Arial" then
                        set the font of its object text to "Monaco"
                    end if
                end tell

            end tell

        end tell
    end if

end tell

(我在这个例子中使用了Monaco,因此您可以快速判断脚本是否有效,因为Helvetica和Arial很难区分。)