スクスニップ

AppleScriptの断片をここに書く

InDesign インライングラフィック(文字列を置換) AppleScript

2-2 06 テキストフレーム内の特定の文字列を、画像に置換する(P.107)

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

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

書籍では、ダイアログを開いて挿入する画像を指定しているが、 当ブログでは、画像ファイルのパスを設定しておく。

部品作製

f:id:mikomaya:20141111172232p:plain

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

書籍のスクリプトで文字範囲を取得する部分

… insertionPoints.itemByRange(cFrom,cTo)

AppleScriptでどう書けばいいのか分からなかったので、

  • 検索パターンにヒットした部分の文字列を消去
  • 画像を挿入

という手順で実装した。

-- 追記 -- 2104.11.11 以下のように書けることがわかった。

place myFile on text from character cFrom to character cTo

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

  • on getTextFrames(myPage)
  • on textIndexOf(myStr, myPat, myCount)
  • on textIndexList(myStr, myPat)

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

-- 検索パターン
set myPat to "<<icon_AScript>>"

-- 画像ファイルのパス
set myFile to "Macintosh HD:Users:yourUserName: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
        if insFrom > 0 then replaceStr2Image(myTF, insFrom, insTo, myFile)
    end repeat
end repeat

実行結果

f:id:mikomaya:20141111172325p:plain