スクスニップ

AppleScriptの断片をここに書く

InDesign インライングラフィック(確認しながら文字列を置換) AppleScript

2-2 07 テキストフレーム内の特定の文字列を、確認しながら画像に置換する(P.108)

組版時間を半減する! InDesign自動処理実例集

組版時間を半減する! InDesign自動処理実例集

部品作製

f:id:mikomaya:20141111190417p:plain

-- テキストフレーム内の[cFrom]番目の文字から[cTo]番目の文字を選択する
on selectString(tfObj, cFrom, cTo)
    tell application "Adobe InDesign CS6"
        tell tfObj
            select (text from character cFrom to character cTo)
        end tell
    end tell
end selectString

-- テキストフレームの[cFrom]番目の文字から[cTo]番目の文字数部分に前に画像を挿入する
on replaceStr2Image(tfObj, cFrom, cTo, myFile)
    tell application "Adobe InDesign CS6"
        tell tfObj
            place myFile on text from character cFrom to character cTo
        end tell
    end tell
end replaceStr2Image

他のハンドラは以下のURLで実装済http://scsnip.hatenablog.com/entry/2014/11/11/141330

-- 指定されたページのテキストフレームを返す
on getTextFrames(myPage)
-- 文字列内にある特定の文字列の開始位置を返す JavaScriptのindexOf(出現回数の引数を追加)
on textIndexOf(myStr, myPat, myCount)
-- 文字列内にある特定の文字列の全ての開始位置を返す
on textIndexList(myStr, myPat)

部品が揃ったので、まとめ

-- 検索パターンを指定
display dialog "置換対象のタグ(文字)を入れてください" default answer "<<icon_AScript>>"
set myPat to text returned of result

-- 画像ファイルを指定
set myFile to "Macintosh HD:Users:logox:Desktop:asDocIcon.png" as alias

set myList to getTextFrames(1)

set loop to number of myList
repeat with i from 1 to loop
    set myTF to item i of myList
    tell document 1 of application "Adobe InDesign CS6"
        set myStr to (text of myTF as string)
    end tell
    
    set pList to textIndexList(myStr, myPat) -- [AppleScript]が出現する全ての位置
    set pList to reverse of pList -- 後ろの文字から処理
    set loop to number of pList
    repeat with p from 1 to loop
        set insFrom to item p of pList
        set insTo to insFrom + (length of myPat) - 1
        selectString(myTF, insFrom, insTo)
        display dialog "置換しますか?" buttons {"キャンセル", "NG", "OK"}
        if button returned of result is "OK" then
            if insFrom > 0 then replaceStr2Image(myTF, insFrom, insTo, myFile)
        end if
    end repeat
end repeat

実行結果

f:id:mikomaya:20141111190431p:plain

f:id:mikomaya:20141111190432p:plain

f:id:mikomaya:20141111190434p:plain

f:id:mikomaya:20141111190435p:plain

f:id:mikomaya:20141111190437p:plain

f:id:mikomaya:20141111190439p:plain