Adobe InDesign CS6 desktop publishing software Scripting Guide
광고
광고
ADOBE
®
INDESIGN
®
CS6
ADOBE INDESIGN CS6
スクリプティングガイド:
JAVASCRIPT
2012 Adobe Systems Incorporated. All rights reserved.
Adobe® InDesign® CS6 スクリプティングガイド: JavaScript
CS6
更新
ドキュメントの更新ステータス
(ドキュメント全体。各章の更新ステータスについては、それぞれの章を参照してください)
ドキュメント全体で CS5 から CS6 への変更およびバージョン 7.0 から 8.0 への変更。
If this guide is distributed with software that includes an end user agreement, this guide, as well as the software described in it, is furnished under license and may be used or copied only in accordance with the terms of such license. Except as permitted by any such license, no part of this guide may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, electronic, mechanical, recording, or otherwise, without the prior written permission of Adobe Systems Incorporated. Please note that the content in this guide is protected under copyright law even if it is not distributed with software that includes an end user license agreement.
The content of this guide is furnished for informational use only, is subject to change without notice, and should not be construed as a commitment by Adobe Systems Incorporated. Adobe Systems Incorporated assumes no responsibility or liability for any errors or inaccuracies that may appear in the informational content contained in this guide.
Please remember that existing artwork or images that you may want to include in your project may be protected under copyright law.
The unauthorized incorporation of such material into your new work could be a violation of the rights of the copyright owner. Please be sure to obtain any permission required from the copyright owner.
Any references to company names in sample templates are for demonstration purposes only and are not intended to refer to any actual organization.
Adobe, the Adobe logo, Creative Suite, and InDesign are either registered trademarks or trademarks of Adobe Systems Incorporated in the United States and/or other countries. Microsoft and Windows are either registered trademarks or trademarks of Microsoft
Corporation in the United States and/or other countries. Mac OS is a trademark of Apple Computer, Incorporated, registered in the
United States and other countries. All other trademarks are the property of their respective owners.
Adobe Systems Incorporated, 345 Park Avenue, San Jose, California 95110, USA. Notice to U.S. Government End Users. The Software and Documentation are “Commercial Items,” as that term is defined at 48 C.F.R. §2.101, consisting of “Commercial Computer
Software” and “Commercial Computer Software Documentation,” as such terms are used in 48 C.F.R. §12.212 or 48 C.F.R. §227.7202, as applicable. Consistent with 48 C.F.R. §12.212 or 48 C.F.R. §§227.7202-1 through 227.7202-4, as applicable, the Commercial Computer
Software and Commercial Computer Software Documentation are being licensed to U.S. Government end users (a) only as
Commercial Items and (b) with only those rights as are granted to all other end users pursuant to the terms and conditions herein.
Unpublished-rights reserved under the copyright laws of the United States. Adobe Systems Incorporated, 345 Park Avenue, San Jose,
CA 95110-2704, USA. For U.S. Government End Users, Adobe agrees to comply with all applicable equal opportunity laws including, if appropriate, the provisions of Executive Order 11246, as amended, Section 402 of the Vietnam Era Veterans Readjustment Assistance
Act of 1974 (38 USC 4212), and Section 503 of the Rehabilitation Act of 1973, as amended, and the regulations at 41 CFR Parts 60-1 through 60-60, 60-250, and 60-741. The affirmative action clause and regulations contained in the preceding sentence shall be incorporated by reference.
目次
3
目次
4
目次
5
目次
6
目次
7
目次
8
1
はじめに
CS6 小幅な更新
章の更新ステータス
11 ページの「その他の JavaScript 開発の選択肢」
このマニュアルでは、次の作業を行う方法について説明します。
Adobe® InDesign® のスクリプティング環境の操作
高度なスクリプティング機能の使用
ドキュメントに関連する基本的な作業(マスタースプレッドの設定、プリント、書き出しなど)
ページアイテム(長方形、楕円形、グラフィックの線、多角形、テキストフレーム、グループ)の操作
InDesign ドキュメントのテキストや書式の操作(テキストの検索と変更など)
ダイアログボックスなどのユーザーインターフェイスアイテムの作成
メニューのカスタマイズや追加と、メニューアクションの作成
ユーザーインターフェイスのイベントに対する応答
XML の操作(XML 要素の作成、XML の読み込み、レイアウトへの XML 要素の追加など)
XML ルール(InDesign で XML を高速かつ簡単に操作できる新しいスクリプティング機能)の適用
ここでは、読者が『Adobe InDesign スクリプティングチュートリアル』を既に読んでおり、スクリプトを作
成、インストール、実行する方法を理解しているものとして説明を行います。 スクリプト環境に接続したり、
スクリプトエディターから InDesign スクリプトオブジェクトモデルを表示したりする方法については、
『Adobe InDesign スクリプティングチュートリアル』を参照してください。
このマニュアルに掲載されているスクリプトの使用方法
このマニュアルに掲載されているスクリプトのほとんどは、完全なスクリプトではありません。 このマニュ
アルの説明内容に関連するスクリプトから特定部分のみを抜粋した、断片的なスクリプトです。 このマニュ
アルに掲載されているスクリプト行をコピーして、スクリプトエディタに貼り付けることができますが、ス
クリプトを実行するには、さらに編集が必要になります。 また、このマニュアルからコピーしたスクリプト
には、(マニュアルのレイアウトにより)改行などの文字が含まれている可能性があることに注意してくださ
い。このような文字が含まれていると、スクリプトを正常に実行できません。
このマニュアルに掲載されているすべてのスクリプトの Zip アーカイブは、InDesign のスクリプティング
ホームページ( http://www.adobe.com/jp/products/indesign/scripting/index.html
)で入手できます。 アーカイブ
をダウンロードして展開したら、該当するスクリプト言語に対応するフォルダーを、InDesign フォルダー内
の Scripts フォルダーの下にある Scripts Panel フォルダーに移動します。 これで、InDesign のスクリプトパネル
からスクリプトを実行できます。
9
第 1 章 はじめに スクリプトの構造について 10
スクリプトの構造について
サンプルスクリプトはすべて、main、mySetup、mySnippet、myTeardown(関数)などの共通のテンプレー
トを使用して記述されています。 この記述方式は、自動化テストとパブリケーションを簡略化するためのも
のです。通常はスクリプトをこのように構築する必要はありません。 スクリプト作成者の関心を引くと思わ
れるスクリプトの断片は、mySnippet 関数内に記述されています。
自動 jsxbin 変換
jsxbin 形式(バイナリ JavaScript)を使用すると、ソースコードを公開することなくスクリプトを配布するこ
とができます。 ExtendScript Toolkit には、js(x)ファイルを即座に jsxbin に変換するバイナリ書き出し機能が
含まれています。 jsxbin の書き出し処理は、ユーザーの操作なしで自動的に実行することができます。
次に実行方法を示します。
1.
.jsx ファイルを .jsxbin ファイルにコンパイルするコンパイラースクリプトファイルを作成します。
スクリプトファイルの冒頭には、次のターゲットディレクティブを必ず記述します。
#target estoolkit#dbg
app.compile()
メソッドを使用し、スクリプトファイルのコンテンツを String パラメーターとして渡
します。
スクリプトで、この結果を拡張子が .jsxbin の新規ファイルに格納します。
2.
コマンドラインパラメーター -cmd [ コンパイラースクリプトファイルのパス ] を指定して ExtendScript
ToolKit を起動します。
Windows:
"ExtendScript Toolkit.exe" -cmd compiler.jsx
Mac:
"ExtendScript Toolkit.app/Contents/MacOS/ExtendScript Toolkit" ¥
-cmd compiler.jsx
サンプルのコンパイラースクリプト(compiler.jsx)を次に示します。ソーススクリプトのファイルパスは
ハードコーディングしてあります。
#target estoolkit#dbg var fileIn = File("/c/jsxbin_test/source.jsx"); fileIn.open("r"); var s = fileIn.read(); fileIn.close(); var t = app.compile(s); var fileOut = File( fileIn.absoluteURI + "bin" ) ; fileOut.open("w"); fileOut.write(t); fileOut.close();
第 1 章 はじめに その他の JavaScript 開発の選択肢 11
その他の JavaScript 開発の選択肢
ExtendScript Toolkit を使用して明示的に InDesign 用の JavaScript のスクリプトを作成することもできますが、
Creative Suite Extension Builder(CS Extension Builder)を使用すると、ActionScript で CS エクステンションを開
発できます。 CS エクステンションは Flash ベース(SWF)であるため、潜在的に Creative Suite の様々なアプリ
ケーションで動作する可能性があります。
各アプリケーションは拡張性に優れたインフラストラクチャで構築されており、開発者がアプリケーション
の機能を拡張できるようになっています。インフラストラクチャは、Flash および Flex テクノロジーが基盤に
なっていて、CS の各エクステンションはコンパイルした Flash(SWF)ファイルで配布します。CS に用意さ
れている Extension Manager を使用すると、CS エクステンションのインストールを実行できます。
様々な Creative Suite アプリケーションに対して一貫性のあるユーザーインターフェイスが提供されます。た
だし、ロジックは、各ホストアプリケーションに適応したものがそれぞれ用意されています。
エクステンションのユーザーインターフェイスは、Flex フレームワークを使用して ActionScript で作成されて
項目からアクセスします。 CS Extension Builder では、Flash Builder のデザインビューを使用して、インタラク
ティブにユーザーインターフェイスを設計できます。 また、CS Extension Builder では、CS エクステンション
用のすべてのアプリケーションロジックを ActionScript で開発できます。使い慣れた Flash Builder 環境で、エ
クステンションを開発してデバッグを行うことができます。
アプリケーションロジックの開発には、Creative Suite ActionScript Wrapper Library(
CSAWLib
)の使用をお勧め
します。CSAWLib は、各ホストアプリケーションのスクリプティング DOM を ActionScript ライブラリとして
公開します。 CSAWLib は、CS Extension Builder 環境に緊密に統合されています。CS Extension Builder 環境には、
エクステンションの基本構造を作成したり、Adobe InDesign や Photoshop、Illustrator などの Creative Suite ア
プリケーションに対してコードを実行してデバッグを行ったりする際に役立つウィザードが用意されていま
す。
スクリプティング DOM のメソッド、プロパティ、ビヘイビアーは、ホストアプリケーションの『JavaScript
Creative Suite SDK のマニュアルを参照してください。CS Extension Builder をインストールしている場合は、
Flash Builder または Eclipse のヘルプシステム内からマニュアルにアクセスできます。
詳細情報
InDesign スクリプティングに関するユーザーフォーラム( http://www.adobeforums.com
)でも、InDesign ス
クリプティングに関する情報が入手できます。 このフォーラムでは、質問をしたり、質問に答えたり、新た
に作成したスクリプトを別のユーザーと共有したりできます。 このフォーラムでは、多数のサンプルスクリ
プトが提供されています。
2
スクリプティング機能
CS6 更新
章の更新ステータス
および 3 つの副節を、更新、修正および明確化しました。
この章では、InDesign のスクリプティング環境に関連するスクリプティングテクニックを紹介します。
InDesign のスクリプトモデルを構成するオブジェクトのほとんどは、アプリケーションのデフォルトやド
キュメントを操作するためのオブジェクトですが、 この章ではまず、スクリプトそのものを制御する方法に
ついて説明します。
この章の内容は、次のとおりです。
scriptPreferences
オブジェクトとそのプロパティ
実行中のスクリプトへの参照の取得
以前のバージョンのスクリプトオブジェクトモデルに基づいたスクリプトの実行
doScript
メソッドを使用したスクリプトの実行
スクリプトラベルの操作
InDesign の起動時におけるスクリプトの自動実行
スクリプトを実行する ExtendScript エンジンの制御
ここでは、読者が『Adobe InDesign スクリプティングチュートリアル』を既に読んでおり、該当するスクリ
プト言語で InDesign のスクリプトを作成、インストール、実行する方法を理解しているものとして説明を行
います。
スクリプトの環境設定
scriptPreferences
オブジェクトには、InDesign でのスクリプトの実行方法に関連するオブジェクトやプロ
パティが用意されています。 次の表に、scriptPreferences オブジェクトの各プロパティの詳細を示します。
プロパティ
enableRedraw scriptsFolder scriptsList
説明
スクリプトパネルからスクリプトを実行している最中の画面の再描画をオンま
たはオフにします。
Scripts フォルダーへのパス。
使用可能なスクリプトのリスト。 このプロパティは、次に示すような配列の配
列を返します。
[[fileName, filePath], ...]
fileName
はスクリプトファイルの名前を表し、
filePath
はスクリプトへのフ
ルパスを表します。 この機能を使用すれば、目的のスクリプトがインストール
されているどうかを確認できます。
12
第 2 章 スクリプティング機能 現在のスクリプトの取得 13
プロパティ
userInteractionLevel version
説明
このプロパティは、ユーザーに表示する警告やダイアログボックスを制御しま
す。 このプロパティを
UserInteractionLevels.neverInteract
に設定すると、
警告やダイアログボックスは一切表示されなくなります。
UserInteractionLevels.interactWithAlerts
に設定すると、警告は有効にな
りますが、ダイアログボックスは無効になります。
UserInteractionLevels.interactWithAll
に設定すると、警告とダイアログ
ボックスは通常どおりに表示されます。 警告の表示をオフにする機能は、スク
リプトでドキュメントを開く場合に便利です。InDesign では、フォントやリン
ク先のグラフィックファイルが見つからないと警告が表示されることがありま
す。 このプロパティを
UserInteractionLevels.neverInteract
に設定してから
ドキュメントを開き、スクリプトを終了する直前にプロパティを元に戻せば
(
UserInteractionLevels.interactWithAll
のを避けられます。
プトのバージョン対応」 を参照してください。 このプロパティは、アプリケー
ションのバージョンと同じではないことに注意してください。
現在のスクリプトの取得
現在のスクリプトへの参照を取得するには、アプリケーションオブジェクトの activeScript
プロパティを使
用します。 このプロパティは、現在のスクリプトが保存されている場所を基準にしてファイルやフォルダー
を検索する場合に役立ちます。次のスクリプトにその例を示します(チュートリアルスクリプトの var myScript = app.activeScript; alert("The current script is: " + myScript); var myParentFolder = File(myScript).parent; alert("The folder containing the active script is: " + myParentFolder);
スクリプトエディタでスクリプトをデバッグしている場合は、 activeScript
プロパティを取得しようとする
とエラーが発生します。 activeScript
プロパティで返されるのは、スクリプトパレットから実行したスクリ
プトのみです。
ExtendScript Toolkit を使用してスクリプトをデバッグしている場合は、 activeScript
プロパティを取得しよ
うとするとエラーが発生します。 このエラーを回避して、 activeScript
プロパティが使用されているスクリ
プトをデバックするには、次のエラーハンドラーを使用します(チュートリアルスクリプトの GetScriptPath
より)。 function myGetScriptPath() { try{ return app.activeScript;
} catch(myError){ return File(myError.fileName);
}
}
スクリプトのバージョン対応
InDesign では、以前のバージョンの InDesign スクリプトオブジェクトモデルに基づいて作成されたスクリプ
トを実行できます。 新しいバージョンの InDesign で古いスクリプトを実行する場合は、次の点に注意する必
要があります。
第 2 章 スクリプティング機能 スクリプトのバージョン対応 14
ターゲットの設定 - スクリプトを実行する InDesign のバージョン(現在のバージョン)をターゲットに
は言語によって異なります。
コンパイル - この段階では、スクリプトで使用されている名前が InDesign で認識できるスクリプト ID に
異なります。
インタープリターによる実行 - この段階では、スクリプト ID が InDesign の適切なハンドラーに関連付け
られます。これにより InDesign は、以前のバージョンのスクリプトオブジェクトモデルに基づいて作成
されたスクリプトも正しく解釈できるようになります。 そのためには、スクリプトでアプリケーション
のスクリプト環境設定に古いオブジェクトモデルを明示的に設定するか(
ターによる実行」 に示すとおり)、次のようにスクリプトパネル用のフォルダーからスクリプトを実行し
ます。
フォルダー
Version 8.0 Scripts
Version 7.0 Scripts
Version 6.0 Scripts
Version 5.0 Scripts
Version 2.0 Scripts
スクリプトの InDesign バージョン
CS6
CS5 および CS5.5
CS4
CS3
CS2
ターゲットの設定
スクリプトを実行する InDesign のバージョン(現在のバージョン)が、スクリプトでターゲットとして明示
的または暗黙的に設定されている必要があります。 スクリプトパネルからスクリプトを実行すると暗黙的に
ターゲットが設定されます。
外部(ExtendScript Toolkit)からスクリプトを実行する場合、JavaScript で明示的にターゲットを設定するに
は、 target
ディレクティブを使用します。
//target CS6
#target "InDesign-8.0"
//target the latest version of InDesign
#target "InDesign"
コンパイル
も使用されます。
インタープリターによる実行
インタプリタで使用するスクリプトオブジェクトモデルのバージョンを取得したり設定したりするには、
InDesign アプリケーションオブジェクトの scriptPreferences
オブジェクトを使用します。
アプリケーションの現在のバージョンに設定されており、変更されるまでそのバージョンが使用されます。
例えば、スクリプトオブジェクトモデルのバージョンを CS5(7.0)に変更するには、次のようにします。
//Set to 7.0 scripting object model app.scriptPreferences.version = 7.0;
第 2 章 スクリプティング機能 doScript メソッドの使用 15
doScript メソッドの使用
doScript
このメソッ
ドには、有効なスクリプトコードを表す文字列か、ディスク上のスクリプトファイルを指定できます。 指定
するスクリプトは、現在のスクリプトと同じ言語であっても、異なる言語であってもかまいません。 使用で
きる言語はプラットフォームによって異なります。Mac OS® の場合は AppleScript または JavaScript を実行で
きます。Windows® の場合は VBScript または JavaScript を実行できます。 doScript
メソッドは、次の様々な場合に利用できます。
使用したい機能が、メインのスクリプト言語ではサポートされておらず、別の言語でサポートされてい
る場合。 例えば、VBScript にはファイルブラウザーやフォルダーブラウザーを表示する機能はありません
が、JavaScript にはこの機能が用意されています。 AppleScript では三角関数(サインやコサイン)の計算
に時間がかかる場合がありますが、JavaScript では高速に処理できます。 JavaScript では、Microsoft® Excel
スプレッドシートのセルの内容を照会することはできませんが、AppleScript や VBScript を使用すれば行
うことができます。 どの場合も、別の言語で断片的なスクリプトコードを作成して doScript
メソッドで
実行すれば、メインのスクリプト言語の制約を回避することができます。
スクリプトを動的に生成して実行する場合。 実行時にスクリプトの文字列を動的に生成して、 doScript
メソッドで実行することができます。 この方法は、選択されている内容や作成するオブジェクトの属性
に基づいてダイアログボックスやパネルをカスタマイズしたい場合などに適しています。
オブジェクトにスクリプトを埋め込む場合。 doScript
メソッドを使用すれば、オブジェクトの label
プ
ロパティに文字列として保存されているスクリプトを実行することができます。 このテクニックを利用
すると、特定のパラメーターに基づいてレイアウトプロパティを制御したり内容を更新したりするスク
リプトを、オブジェクト自体に埋め込むことができます。 また、XML 要素にも、属性またはコンテンツ
を
参照してください。
doScript へのパラメーターの渡し方
doScript
で実行するスクリプトにパラメーターを渡すには、次のようにします(チュートリアルスクリプト
の DoScriptParameters より)。 var myParameters = ["Hello from DoScript", "Your message here."]; var myJavaScript = "alert(¥"First argument: ¥" + arguments[0] + ¥"¥¥rSecond argument: ¥" + arguments[1]);"; app.doScript(myJavaScript, ScriptLanguage.javascript, myParameters); if(File.fs == "Windows"){ var myVBScript = "msgbox arguments(1), vbOKOnly, ¥"First argument: ¥" & arguments(0)"; app.doScript(myVBScript, ScriptLanguage.visualBasic, myParameters);
} else{ var myAppleScript = "tell application ¥"Adobe InDesign CS6¥¥rdisplay dialog(¥"First argument¥" & item 1 of arguments & return & ¥"Second argument: ¥"
& item 2 of arguments & return & end tell"; app.doScript(myAppleScript, ScriptLanguage.applescriptLanguage, myParameters);
}
第 2 章 スクリプティング機能 doScript メソッドの使用 16
doScript からの戻り値
次のスクリプトは、 doScript
で実行されるスクリプトから値を返す方法を示しています。
列として実行される JavaScript を使用していますが、スクリプトファイルも同様に使用できます。 また、この
例で返す値は 1 つですが、配列を使用すると複数の値を返すことができます(完全なスクリプトについては、
//To send parameters to a script run using app.doScript(), the doScript
//statement must not appear inside a function. If it does, the parameters
//will not be passed to the script.
var myDocument = app.documents.add(); var myPage = myDocument.pages.item(0); var myTextFrame = myPage.textFrames.add(); myTextFrame.geometricBounds = ["72pt", "72pt", "288pt", "288pt"]; myTextFrame.contents = "Example text frame."; var myDestinationPage = myDocument.pages.add(LocationOptions.after, myPage); var myPageIndex = myDestinationPage.name; var myID = myTextFrame.id; var myJavaScript = "var myDestinationPage = arguments[1];¥r" ; myJavaScript += "myID = arguments[0];¥r"; myJavaScript += "var myX = arguments[2];¥r"; myJavaScript += "var myY = arguments[3]¥r;" myJavaScript += "var myPageItem = app.documents.item(0).pages.item(0).pageItems.itemByID(myID);¥r"; myJavaScript += "myPageItem.duplicate(app.documents.item(0).pages.item(myDestinationPage));¥r"
//Create an array for the parameters we want to pass to the JavaScript.
var myArguments = [myID, myPageIndex, 0, 0]; var myDuplicate = app.doScript(myJavaScript, ScriptLanguage.javascript, myArguments);
//myDuplicate now contains a reference to the duplicated text frame.
//Change the text in the duplicated text frame.
myDuplicate.contents = "Duplicated text frame.";
別の方法として、アプリケーションの scriptArgs
オブジェクトを使用して別のスクリプトから値を取得する
方法があります(この名前は、「script arguments」を縮めたものです)。 次のスクリプトにその例を示します
(完全なスクリプトについては、DoScriptScriptArgs を参照してください)。 var nameA = "ScriptArgumentA"; var nameB = "ScriptArgumentB"; var nAc = nameA + ": "; var nBc = nameB + ": ";
//Create a string to be run as a JavaScript.
var p1 = "app.scriptArgs.setValue(¥"" + nameA + "¥", "; var p2 = "¥"This is the first script argument value.¥");¥r"; var p3 = "app.scriptArgs.setValue(¥"" + nameB + "¥", "; var p4 = "¥"This is the second script argument value.¥")"; var p5, p6; //Used later.
var myJavaScript = p1 + p2 + p3 + p4; var myScriptArgumentA = app.scriptArgs.getValue(nameA); var myScriptArgumentB = app.scriptArgs.getValue(nameB); alert(nameA + ": " + myScriptArgumentA + "¥r" + nameB + ": " + myScriptArgumentB); if(File.fs == "Windows") {
//Create a string to be run as a VBScript.
p1 = "Set myInDesign = CreateObject(¥"InDesign.Application.CS6¥")¥r"; p2 = "myInDesign.ScriptArgs.SetValue ¥"" + nameA + "¥", "; p3 = "¥"This is the first script argument value.¥"¥r"; p4 = "myInDesign.ScriptArgs.SetValue ¥"" + nameB + "¥", "; p5 = "¥"This is the second script argument value.¥""; var myVBScript = p1 + p2 + p3 + p4 + p5; app.doScript(myVBScript, ScriptLanguage.visualBasic);
} else {
第 2 章 スクリプティング機能 doScript を使用した取り消しの制御 17
//Create a string to be run as a AppleScript.
p1 = "tell application ¥"Adobe InDesign CS6¥"¥r"; p2 = "tell script args" +"¥r"; p3 = "set value name¥"" + nameA +"¥" value "; p4 = "¥"This is the firest AppleScript script argument value.¥"" +"¥r"; p5 = "set value name¥"" + nameB +"¥" value "; p6 = "¥"This is the second AppleScript script argument value.¥"" +"¥r"; p7 = "end tell" + "¥r" p8 = "end tell" + "¥r" var myAppleScript = p1 + p2 + p3 + p4 + p5 + p6 + p7 + p8; app.doScript(myAppleScript, ScriptLanguage.applescriptLanguage);
} var myScriptArgumentA = app.scriptArgs.getValue(nameA); var myScriptArgumentB = app.scriptArgs.getValue(nameB); alert(nAc + myScriptArgumentA + nBc + myScriptArgumentB);
doScript
を使用した取り消しの制御
InDesign では、ほとんどすべてのアクションを取り消すことができます。ただし、行ったアクションのほと
んどすべてがディスクに書き出されるので、犠牲も伴います。 ユーザーインターフェイスのツールを使用し
た通常の作業では、取り消しによって問題が発生することはありません。 しかし、短時間に何千ものアク
ションの実行が可能であるスクリプトの場合、ディスクへのアクセスが絶えず繰り返されているので、パ
フォーマンスに深刻な影響を与える場合があります。 doScript
メソッドには、このパフォーマンスの問題を解決するために 2 つのパラメーターが用意されてお
り、InDesign の取り消し動作に関してスクリプトの実行方法を制御することができます。 次の例で、これら
のパラメーターを示します。
//Given a script "myJavaScript" and an array of parameters "myParameters"...
app.doScript(myJavaScript, ScriptLanguage.javascript, myParameters, UndoModes.fastEntireScript,
"Script Action");
//UndoModes can be:
//UndoModes.autoUnto: Add no events to the Undo queue.
//UndoModes.entireScript: Put a single event in the Undo queue.
//UndoModes.fastEntireScript: Put a single event in the Undo queue.
//UndoModes.scriptRequest: Undo each script action as a separate event.
//The last parameter is the text that appears in the Undo menu item.
スクリプトラベルの操作
InDesign の多くのスクリプトオブジェクトには、 label
プロパティが用意されています。例えば、ページア
イテム(長方形、楕円形、グループ、多角形、テキストフレーム、グラフィックの線)、テーブルのセル、ド
キュメント、ストーリー、ページなどのオブジェクトでは、 label
プロパティが使用できます。
ティには、大量のテキストを保存することができます。
ページアイテムのラベルは、スクリプトラベルパネルを使用して表示、入力、編集できます(次の図を参照。
プトを使用して、オブジェクトにラベルを追加したり、スクリプトのラベルを読み取ったりすることもでき
ます。 ストーリー、ページ、段落スタイルなどの多くのオブジェクトは、スクリプトラベルパネルを使用し
てラベルを設定したり表示したりすることはできません。
第 2 章 スクリプティング機能 スクリプトラベルの操作 18 label
プロパティには、タブ区切りやカンマ区切りのテキスト、HTML、XML など、あらゆる形式のテキスト
データを含めることができます。 スクリプトもテキストであるため、 label
プロパティに保存することができ
ます。
名前を持つアイテム(段落スタイル、カラー、レイヤーなど)がその name
を使用して参照できるように、
ページアイテムはその label
を使用して参照することができます。
照する例を、次のスクリプトに示します(完全なスクリプトについては、ScriptLabel を参照してください)。 var myDocument = app.documents.add(); var myPage = myDocument.pages.item(0); var myX1, myX2, myY1, myY2, myRectangle; var myPageWidth = myDocument.documentPreferences.pageWidth; var myPageHeight = myDocument.documentPreferences.pageHeight;
//<fragment>
//Create 10 random page items.
for(var i = 0; i < 10; i++)
{ myX1 = myGetRandom(0, myPageWidth, false); myY1 = myGetRandom(0, myPageHeight, false); myX2 = myGetRandom(0, myPageWidth, false); myY2 = myGetRandom(0, myPageHeight, false); myRectangle = myPage.rectangles.add({geometricBounds:[myY1, myX1, myY2, myX2]}); if(myGetRandom(0, 1, true))
{ myRectangle.label = "myScriptLabel";
}
} var count = 0; for(var i = 0; i < myPage.pageItems.length; i++)
{ if(myPage.pageItems.item(i).label == "myScriptLabel")
{ count++;
}
} alert("Found " + count + " page items with the label.");
//This function gets a random number in the range myStart to myEnd.
function myGetRandom(myStart, myEnd, myInteger)
{ var myRandom; var myRange = myEnd - myStart; if(myInteger == true)
{ myRandom = myStart = Math.round(Math.random());
} else
{ myRandom = myStart + Math.floor(Math.random()*myRange);
} return myRandom;
}
また、 label
プロパティがサポートされているオブジェクトでは、カスタムラベルもサポートされています。
スクリプトでカスタムラベルを設定するには、 insertLabel
メソッドを使用します。カスタムラベルを抽出
するには、 extractLabel
メソッドを使用します。次のスクリプトにその例を示します(チュートリアルスク
リプトの CustomLabel より)。
第 2 章 スクリプティング機能 起動時におけるスクリプトの自動実行 19 var myDocument = app.documents.add(); myDocument.viewPreferences.horizontalMeasurementUnits = MeasurementUnits.points; myDocument.viewPreferences.verticalMeasurementUnits = MeasurementUnits.points; var myPage = myDocument.pages.item(0); var myRectangle = myPage.rectangles.add({geometricBounds:[72, 72, 144, 144]});
//Insert a custom label using insertLabel. The first parameter is the
//name of the label, the second is the text to add to the label.
myRectangle.insertLabel("CustomLabel", "This is some text stored in a custom label.");
//Extract the text from the label and display it in an alert.
var myString = myRectangle.extractLabel("CustomLabel"); alert("Custom label contained: " + myString);
起動時におけるスクリプトの自動実行
InDesign の起動時にスクリプトを自動実行させるには、Scripts フォルダーの下にあるスタートアップ用の
フォルダーである Startup Scripts フォルダーにスクリプトファイルを保存します(詳しくは、『Adobe
注意 : InDesign の起動時に、そのセッションの ExtendScript エンジンでスクリプトを実行した場合、そこで作
成されたオブジェクトや関数は、そのセッションの間、他のスクリプトからも使用することができます。 詳
セッションとメインでのスクリプトの実行
InDesign で JavaScript を実行する方法には、 session
と main
の 2 つがあります。
行時に使用する ExtendScript エンジンの名前に対応しています。
デフォルトでは、InDesign の JavaScript を実行すると、メイン(main)の ExtendScript エンジンでスクリプト
が解釈されて実行されます。このエンジンは、スクリプトの実行が終了すると破棄されます。 このスクリプ
トで作成されたスクリプトオブジェクトは保持されません。
セッション(session)のエンジンでスクリプトを実行した場合、そこで作成されたオブジェクトは、
InDesign を終了するまで保持されます。 session
エンジンで実行される他のスクリプト
からも参照できます。 InDesign JavaScript のターゲットとして session
エンジンを設定するには、スクリプト
の先頭に次の行を追加します。
#targetengine "session"
また、ExtendScript のパーシスタント(永続的)な解釈および実行環境を独自に作成することもできます。 こ
れを行うには、
#targetenging
文を使用して、独自の ExtendScript エンジンの名前を設定します。次のスクリ
プトにその例を示します。
#targetengine "adobe"
3
ドキュメント
CS6 変更
章の更新ステータス
この章で説明する作業実行方法のリストを更新しました。
という副節の追加。
という副節の追加。
39 ページの「ページサイズとレイアウトの調整」 39 ページの「ページのサイズ
および
InDesign で行う作業の多くは、ドキュメントに関連する作業です。例えば、ドキュメントの作成、保存、プ
リント、書き出しを行ったり、ドキュメントにページアイテム、カラー、スタイル、テキストなどを配置し
たりします。 ドキュメントに関連する作業のほとんどは、InDesign スクリプティングを使用して自動化でき
ます。
この章では、次の作業を行う方法について説明します。
基本的なドキュメント管理作業
新規ドキュメントの作成
ドキュメントのオープン
ドキュメントの保存
ドキュメントのクローズ
基本的なページレイアウト操作
ページサイズやドキュメントの長さの設定
裁ち落としと印刷可能領域の定義
ページの段組やマージンの指定
ペーストボードの外観の変更
ガイドやグリッドの使用
測定単位や定規の原点の変更
ドキュメントプリセットの定義と適用
マスターページ(マスタースプレッド)の設定
テキストフォーマットのデフォルトの設定
XMP メタデータ(ファイルに関する情報)の追加
ドキュメントテンプレートの作成
透かしの作成
ページ別に異なるサイズの適用(複数のページサイズ)
20
第 3 章 ドキュメント ドキュメントの基本的な操作 21
様々なデバイスまたはサイズや方向の異なるドキュメントに対応するための、ページに対する柔軟なレ
イアウトフォーマットの適用
ドキュメントのプリント
Adobe PDF としてのドキュメントの書き出し
EPS としてのドキュメントのページごとの書き出し ePub ファイルとしてのドキュメントの書き出し
ここでは、読者が『Adobe InDesign スクリプティングチュートリアル』を既に読んでおり、スクリプトを作
成、インストール、実行する方法を理解しているものとして説明を行います。
ドキュメントの基本的な操作
ドキュメントのオープン、クローズ、保存といった操作は、ドキュメントに対する最も基本的な操作です。
ここでは、スクリプティングでこれらの操作を実行する方法について説明します。
新規ドキュメントの作成
新規ドキュメントを作成する方法を、次のスクリプトに示します (完全なスクリプトについては、 var myDocument = app.documents.add();
ドキュメントプリセットを使用してドキュメントを作成するには、 add
メソッドのオプションのパラメー
ターを使用して、ドキュメントプリセットを指定します。次のスクリプトにその例を示します (完全なスク
リプトについては、MakeDocumentWithPreset を参照してください)。
//Creates a new document using the specified document preset.
//Replace "myDocumentPreset" in the following line with the name
//of the document preset you want to use.
var myDocument = app.documents.add(true, app.documentPresets.item("myDocumentPreset"));
ドキュメントウィンドウを表示せずにドキュメントを作成することもできます。次のスクリプトにその例を
示します(チュートリアルスクリプトの MakeDocumentWithParameters より)。
//Creates a new document without showing the document window.
//The first parameter (showingWindow) controls the visibility of the
//document. Hidden documents are not minimized, and will not appear until
//you add a new window to the document.
var myDocument = app.documents.add(false);
//To show the window: var myWindow = myDocument.windows.add();
スクリプトの処理によっては、ドキュメントウィンドウを非表示にすることで実行速度がより速くなること
があります。
ドキュメントを開く
既存のドキュメントを開く方法を、次のスクリプトに示します (完全なスクリプトについては、 app.open(File("/c/myTestDocument.indd")); open
メソッドの showing window
、
ドキュメントが表示されないように(非表示に)なります。 スクリプトのパフォーマンスを向上させたい場
合は、この方法を利用したいと思うでしょう。 非表示のドキュメントを表示するには、新規ウィンドウを作
第 3 章 ドキュメント ドキュメントの基本的な操作 22
成します。次のスクリプトにその例を示します(チュートリアルスクリプトの OpenDocumentInBackground
より)。
//Opens an existing document in the background, then shows the document.
//You'll have to fill in your own file path.
var myDocument = app.open(File("/c/myTestDocument.indd"), false);
//At this point, you could do things with the document without showing the
//document window. In some cases, scripts will run faster when the document
//window is not visible.
//When you want to show the hidden document, create a new window.
var myLayoutWindow = myDocument.windows.add();
ドキュメントの保存
InDesign のユーザーインターフェイスでは、ファイルを保存するにはファイル/保存を選択し、別の名前で
ファイルを保存するにはファイル/別名で保存を選択します。 InDesign スクリプティングで同じ処理を行う
には、 save
メソッドを使用します。次のスクリプトにその例を示します(チュートリアルスクリプトの
//If the active document has been changed since it was last saved, save it.
if(app.activeDocument.modified == true){ app.activeDocument.save();
} save
メソッドには、オプションのパラメーターが 2 つあります。最初のパラメーター( to
)には、保存先の
ファイルを指定します。2 つ目のパラメーター( stationery
)は、true に設定するとドキュメントがテンプ
レートとして保存されます。次のスクリプトにその例を示します(チュートリアルスクリプトの
//If the active document has not been saved (ever), save it.
if(app.activeDocument.saved == false){
//If you do not provide a file name, InDesign displays the Save dialog box.
app.activeDocument.save(new File("/c/myTestDocument.indd"));
}
ドキュメントをテンプレートとして保存することもできます。次のスクリプトにその例を示します(チュー
トリアルスクリプトの SaveAsTemplate より)。
//Save the active document as a template.
var myFileName; if(app.activeDocument.saved == true){
//Convert the file name to a string.
myFileName = app.activeDocument.fullName + "";
//If the file name contains the extension ".indd", change it to ".indt".
if(myFileName.indexOf(".indd")!=-1){ var myRegularExpression = /.indd/gi myFileName = myFileName.replace(myRegularExpression, ".indt");
}
}
//If the document has not been saved, then give it a default file name/file path.
else{ myFileName = "/c/myTestDocument.indt";
} app.activeDocument.save(File(myFileName), true);
第 3 章 ドキュメント 基本的なページレイアウト 23
ドキュメントを閉じる
close
メソッドはドキュメントを閉じます。次のスクリプトにその例を示します(チュートリアルスクリプ
トの CloseDocument より)。 app.activeDocument.close();
//Note that you could also use:
//app.documents.item(0).close(); close
メソッドには、最大で 2 つのオプションパラメーターを指定できます。次のスクリプトにその例を示
します(チュートリアルスクリプトの CloseWithParameters より)。
//Use SaveOptions.yes to save the document,SaveOptions.no to close the
//document without saving, or SaveOptions.ask to display a prompt. If
//you use SaveOptions.yes, you'll need to provide a reference to a file
//to save to in the second parameter (SavingIn).
//Note that the file path is provided using the JavaScript URI form
//rather than the platform-specific form.
//
//If the file has not been saved, display a prompt.
if(app.activeDocument.saved != true){ app.activeDocument.close(SaveOptions.ask);
//Or, to save to a specific file name:
//var myFile = File("/c/myTestDocument.indd");
//app.activeDocument.close(SaveOptions.yes, myFile);
} else{
//If the file has already been saved, save it.
app.activeDocument.close(SaveOptions.yes);
}
開いているすべてのドキュメントを保存せずに閉じることもできます。次のスクリプトにその例を示します
(チュートリアルスクリプトの CloseAll より)。 for(myCounter = app.documents.length; myCounter > 0; myCounter--){ app.documents.item(myCounter-1).close(SaveOptions.no);
}
基本的なページレイアウト
それぞれのドキュメントでは、デフォルトのページサイズ、割り当てられたページ数、裁ち落としと印刷可
能領域、段組とマージンによって、コンテンツを配置するための領域が定義されます。 これらのパラメー
ターはすべて、スクリプティングで操作することができます。次の各節でその例を示します。
ページサイズとドキュメントの長さの定義
InDesign のユーザーインターフェイスで新規ドキュメントを作成するときには、デフォルトのページサイズ、
ページ数、ページの方向、見開きページにするかどうかなどを指定できます。 InDesign スクリプティングで
ドキュメントを作成するには documents.add
メソッドを使用しますが、上記のような設定は指定できません。
ドキュメントを作成した後で、 documentPreferences
オブジェクトを使用して設定を行います。次のスクリ
プトにその例を示します(チュートリアルスクリプトの DocumentPreferences より)。 var myDocument = app.documents.add(); with(myDocument.documentPreferences){ pageHeight = "800pt"; pageWidth = "600pt"; pageOrientation = PageOrientation.landscape; pagesPerDocument = 16;
}
第 3 章 ドキュメント 基本的なページレイアウト 24
注意 :
app
オブジェクトにも、 documentPreferences
というオブジェクトがあります。
ロパティを設定することで、ページの高さや幅などのアプリケーションデフォルトを設定できます。 また、
個別のページサイズを設定することもできます。詳しくは、 を参照して
ください。
裁ち落としと印刷可能領域の定義
InDesign で使用される裁ち落としまたは印刷可能領域という用語は、プリントしたり PDF に書き出したりす
ることが可能な、ページマージンの外部の領域のことを表します。 一般に、こうした領域は、ページ枠から
はみ出して配置されるオブジェクトがある場合や(裁ち落とし)、ジョブ情報やドキュメント情報を含めてお
きたい場合に(印刷可能領域)使用されます。 この 2 つの領域は、プリントしたり書き出したりするかどう
かを、ページ枠とは独立に設定することができます。例えば、ドキュメントの最終プリントでは、印刷可能
領域に配置した情報を除外してプリントすることができます。 新規ドキュメントの裁ち落としと印刷可能領
域を設定する方法を、次のスクリプトに示します (完全なスクリプトについては、BleedAndSlug を参照して myDocument = app.documents.add();
//The bleed and slug properties belong to the documentPreferences object.
with(myDocument.documentPreferences){
//Bleed documentBleedBottomOffset = "3p"; documentBleedTopOffset = "3p"; documentBleedInsideOrLeftOffset = "3p"; documentBleedOutsideOrRightOffset = "3p";
//Slug slugBottomOffset = "18p"; slugTopOffset = "3p"; slugInsideOrLeftOffset = "3p"; slugRightOrOutsideOffset = "3p";
}
この例のように、裁ち落としの距離がすべて等しい場合は、代わりに documentBleedUniformSize
プロパ
ティを使用することもできます。次のスクリプトにその例を示します(チュートリアルスクリプトの
//Create a new document.
myDocument = app.documents.add();
//The bleed properties belong to the documentPreferences object.
with(myDocument.documentPreferences){
//Bleed documentBleedUniformSize = true; documentBleedTopOffset = "3p";
}
印刷可能領域の距離がすべて等しい場合は、 documentSlugUniformSize
プロパティが使用できます。次のス
クリプトにその例を示します(チュートリアルスクリプトの UniformSlug より)。
//Create a new document.
myDocument = app.documents.add();
//The slug properties belong to the documentPreferences object.
with(myDocument.documentPreferences){
//Slug: documentSlugUniformSize = true; slugTopOffset = "3p";
}
裁ち落としや印刷可能領域は、幅や高さを設定できるだけでなく、その領域を表すガイドのカラーも設定で
きます。 documentPreferences
オブジェクトではなく、 pasteboardPreferences
オブジェ
クトに用意されています。次のスクリプトにその例を示します(チュートリアルスクリプトの
第 3 章 ドキュメント 基本的なページレイアウト 25 with(app.activeDocument.pasteboardPreferences){
//Any of InDesign's guides can use the UIColors constants...
bleedGuideColor = UIColors.cuteTeal; slugGuideColor = UIColors.charcoal;
//...or you can specify an array of RGB values (with values from 0 to 255)
//bleedGuideColor = [0, 198, 192];
//slugGuideColor = [192, 192, 192];
}
ページのマージンと段組の設定
ドキュメントの各ページでは、それぞれ独自のマージンや段組を設定することができます。 InDesign スクリ
プティングでは、各ページの marginPreferences
オブジェクトのプロパティを使用して、それらを設定でき
ます。 次のサンプルスクリプトでは、新規ドキュメントを作成してから、マスタースプレッドのすべての
ページに対してマージンと段組を設定しています (完全なスクリプトについては、PageMargins を参照して myDocument = app.documents.add(); with (myDocument.pages.item(0).marginPreferences){ columnCount = 3;
//columnGutter can be a number or a measurement string.
columnGutter = "1p"; bottom = "6p"
//When document.documentPreferences.facingPages == true,
//"left" means inside; "right" means outside.
left = "6p" right = "4p" top = "4p"
}
特定のページのマージンを設定するには、そのページの margin preferences を使用します。次のスクリプトに
その例を示します(チュートリアルスクリプトの PageMarginsForOnePage より)。 myDocument = app.documents.add(); with (myDocument.pages.item(0).marginPreferences){ columnCount = 3;
//columnGutter can be a number or a measurement string.
columnGutter = "1p"; bottom = "6p"
//When document.documentPreferences.facingPages == true,
//"left" means inside; "right" means outside.
left = "6p" right = "4p" top = "4p"
}
InDesign では、対応するマージンの合計よりも小さなページは作成できません。つまり、ページの幅は、左
右のページマージンの合計よりも大きくする必要があり、ページの高さは、上下のマージンの合計よりも大
きくする必要があります。 InDesign のユーザーインターフェイス(新規ドキュメントダイアログボックス)
を使用して非常に小さなページ(新聞に掲載する広告など)を作成する場合は、ドキュメントのデフォルト
のページマージンフィールドに新しい値を入力することで、正しいマージンサイズが簡単に設定できます。
しかし、スクリプティングで小さなページを作成する場合は、このように簡単にはいきません。なぜなら、
ドキュメントの作成時には、アプリケーションのデフォルトの margin preferences が適用されるからです。 こ
のマージンは、マスターページを含む、ドキュメント内のすべてのページに適用されます。 ドキュメントの margin preferences を変更した場合、影響を受けるのは新規ページのみで、既存のページには影響はありませ
ページサイズは変更されません。
これを解決するには、2 つの方法があります。 1 つは、既存のページのマージンを設定してからページサイズ
を変更する方法です。次のスクリプトにその例を示します(チュートリアルスクリプトの
第 3 章 ドキュメント 基本的なページレイアウト 26 var myDocument = app.documents.add(); myDocument.marginPreferences.top = 0; myDocument.marginPreferences.left = 0; myDocument.marginPreferences.bottom = 0; myDocument.marginPreferences.right = 0;
//The following assumes that your default document contains a single page.
myDocument.pages.item(0).marginPreferences.top = 0; myDocument.pages.item(0).marginPreferences.left = 0; myDocument.pages.item(0).marginPreferences.bottom = 0; myDocument.pages.item(0).marginPreferences.right = 0;
//The following assumes that your default master spread contains two pages.
myDocument.masterSpreads.item(0).pages.item(0).marginPreferences.top = 0; myDocument.masterSpreads.item(0).pages.item(0).marginPreferences.left = 0; myDocument.masterSpreads.item(0).pages.item(0).marginPreferences.bottom = 0; myDocument.masterSpreads.item(0).pages.item(0).marginPreferences.right = 0; myDocument.masterSpreads.item(0).pages.item(1).marginPreferences.top = 0; myDocument.masterSpreads.item(0).pages.item(1).marginPreferences.left = 0; myDocument.masterSpreads.item(0).pages.item(1).marginPreferences.bottom = 0; myDocument.masterSpreads.item(0).pages.item(1).marginPreferences.right = 0; myDocument.documentPreferences.pageHeight = "1p"; myDocument.documentPreferences.pageWidth = "6p";
もう 1 つは、アプリケーションのデフォルトの margin preferences を変更してからドキュメントを作成する方
法です。次のスクリプトにその例を示します(チュートリアルスクリプトの ApplicationPageMargins より)。 with (app.marginPreferences){
//Save the current application default margin preferences.
var myY1 = top; var myX1 = left; var myY2 = bottom; var myX2 = right;
//Set the application default margin preferences.
top = 0; left = 0; bottom = 0; right = 0;
}
//Create a new example document to demonstrate the change.
var myDocument = app.documents.add(); myDocument.documentPreferences.pageHeight = "1p"; myDocument.documentPreferences.pageWidth = "6p";
//Reset the application default margin preferences to their former state.
with (app.marginPreferences){ top = myY1; left = myX1 ; bottom = myY2; right = myX2;
}
ペーストボードの外観の変更
ペーストボードとは、InDesign のページやスプレッドの周囲にある領域のことです。 この領域は、ページア
イテムや作業メモを一時的に置いておく場所として利用できます。 ペーストボードのサイズやカラーは、ス
クリプティングを使用して変更することができます。 previewBackgroundColor
プロパティを使用することで、
プレビューモードでのペーストボードのカラーを設定できます。次のスクリプトにその例を示します
(チュートリアルスクリプトの PasteboardPreferences より)。
第 3 章 ドキュメント 基本的なページレイアウト 27 myDocument = app.documents.add(); with(myDocument.pasteboardPreferences){
//You can use either a number or a measurement string
//to set the space above/below.
minimumSpaceAboveAndBelow = "12p";
//You can set the preview background color to any of
//the predefined UIColor enumerations...
previewBackgroundColor = UIColors.gray;
//...or you can specify an array of RGB values
//(with values from 0 to 255)
//previewBackgroundColor = [192, 192, 192];
}
ガイドとグリッド
ガイドやグリッドを使用すると、ドキュメントページにオブジェクトを簡単に配置できるようになります。
他のユーザーに提供するテンプレートを作成する場合は、これらのアイテムを適切に配置することで、ユー
ザーの作業効率を高めることができます。
ガイドの定義
InDesign のガイドを使用すれば、ドキュメントページでオブジェクトを簡単に配置できるようになります。
ガイドを使用する方法を、次のスクリプトに示します (完全なスクリプトについては、Guides を参照してく var myDocument = app.documents.add(); var myPageWidth = myDocument.documentPreferences.pageWidth; var myPageHeight = myDocument.documentPreferences.pageHeight; with(myDocument.pages.item(0)){
//Place guides at the margins of the page.
guides.add(undefined, {orientation:HorizontalOrVertical.vertical, <lb> location:marginPreferences.left}); guides.add(undefined, {orientation:HorizontalOrVertical.vertical, <lb> location:(myPageWidth - marginPreferences.right)}); guides.add(undefined, {orientation:HorizontalOrVertical.horizontal, <lb> location:marginPreferences.top}); guides.add(undefined, {orientation:HorizontalOrVertical.horizontal, <lb> location:(myPageHeight - marginPreferences.bottom)});
//Place a guide at the vertical center of the page.
guides.add(undefined, {orientation:HorizontalOrVertical.vertical, <lb> location:(myPageWidth/2)});
//Place a guide at the horizontal center of the page.
guides.add(undefined, {orientation:HorizontalOrVertical.horizontal, <lb> location:(myPageHeight/2)});
}
水平方向のガイドは、指定のページにのみ表示するか、スプレッド内のすべてのページにまたがって表示す
るかを設定できます。 InDesign スクリプティングでは、 fitToPage
プロパティを使用してこの設定を制御でき
ます。 このプロパティは、垂直方向のガイドには適用されません。
スクリプティングでも、ユーザーインターフェイスを使用した場合と同様に、ガイドのレイヤー、カラー、
表示/非表示を変更できます。次のスクリプトにその例を示します(チュートリアルスクリプトの
第 3 章 ドキュメント 基本的なページレイアウト 28 var myDocument = app.documents.add(); var myPageWidth = myDocument.documentPreferences.pageWidth; var myPageHeight = myDocument.documentPreferences.pageHeight; with(myDocument.pages.item(0)){
//Place guides at the margins of the page.
guides.add(undefined, {orientation:HorizontalOrVertical.vertical, <lb> location:marginPreferences.left}); guides.add(undefined, {orientation:HorizontalOrVertical.vertical, <lb> location:(myPageWidth - marginPreferences.right)}); guides.add(undefined, {orientation:HorizontalOrVertical.horizontal, <lb> location:marginPreferences.top}); guides.add(undefined, {orientation:HorizontalOrVertical.horizontal, <lb> location:(myPageHeight - marginPreferences.bottom)});
//Place a guide at the vertical center of the page.
guides.add(undefined, {orientation:HorizontalOrVertical.vertical, <lb> location:(myPageWidth/2)});
//Place a guide at the horizontal center of the page.
guides.add(undefined, {orientation:HorizontalOrVertical.horizontal, <lb> location:(myPageHeight/2)});
}
ガイドの作成には、スプレッドやマスタースプレッドの createGuides
メソッドを使用することもできます。
次のスクリプトにその例を示します(チュートリアルスクリプトの CreateGuides より)。 var myDocument = app.documents.add(); with (myDocument.spreads.item(0)){
//Parameters (all optional): row count, column count, row gutter,
//column gutter,guide color, fit margins, remove existing, layer.
//Note that the createGuides method does not take an RGB array
//for the guide color parameter.
createGuides(4, 4, "1p", "1p", UIColors.gray, true, true, myDocument.layers.item(0));
}
grid preferences の設定
ドキュメントグリッドやベースライングリッドのプロパティを制御するには、 gridPreferences
オブジェク
トのプロパティを設定します。次のスクリプトにその例を示します(チュートリアルスクリプトの var myDocument = app.documents.add();
//Set the document measurement units to points.
myDocument.viewPreferences.horizontalMeasurementUnits = MeasurementUnits.points; myDocument.viewPreferences.verticalMeasurementUnits = MeasurementUnits.points;
//Set up grid preferences.
with(myDocument.gridPreferences){ baselineStart = 56; baselineDivision = 14; baselineShown = true; horizontalGridlineDivision = 14; horizontalGridSubdivision = 5 verticalGridlineDivision = 14; verticalGridSubdivision = 5 documentGridShown = true;
}
ガイドやグリッドへのスナップ
ドキュメントのグリッドやガイドのスナップ設定は、すべて guidePreferences
オブジェクトや gridPreferences
ガイドやグリッドのスナッププロパ
ティを設定する方法を、次のスクリプトに示します (完全なスクリプトについては、GuideGridPreferences を
参照してください)。
第 3 章 ドキュメント 基本的なページレイアウト 29 var myDocument = app.activeDocument; with(myDocument.guidePreferences){ guidesInBack = true; guidesLocked = false; guidesShown = true; guidesSnapTo = true;
} with(myDocument.gridPreferences){ documentGridShown = false; documentGridSnapTo = true;
//Objects "snap" to the baseline grid when
//guidePreferences.guideSnapTo is set to true.
baselineGridShown = true;
}
測定単位と定規の変更
これまでのサンプルスクリプトでは、測定文字列(特定の測定単位を InDesign に使用させるための文字列。
例えば、8.5 インチの場合は「8.5i」)を使用してきました。 これは、スクリプトの実行時に別の測定単位系が
使用されている可能性を考慮しているためです。
スクリプトで使用する測定単位系を指定するには、ドキュメントの viewPreferences
オブジェクトを使用し
ます。次のスクリプトにその例を示します(チュートリアルスクリプトの ViewPreferences より)。 var myDocument = app.activeDocument; with(myDocument.viewPreferences){
//Measurement unit choices are:
//* MeasurementUnits.agates
//* MeasurementUnits.picas
//* MeasurementUnits.points
//* MeasurementUnits.inches
//* MeasurementUnits.inchesDecimal
//* MeasurementUnits.millimeters
//* MeasurementUnits.centimeters
//* MeasurementUnits.ciceros
//Set horizontal and vertical measurement units to points.
horizontalMeasurementUnits = MeasurementUnits.points; verticalMeasurementUnits = MeasurementUnits.points;
}
スクリプト全体で特定の測定単位系を使用する場合は、スクリプトの先頭で測定単位を変更し、スクリプト
の最後で元の測定単位に戻します。 次のスクリプトにその例を示します(チュートリアルスクリプトの var myDocument = app.activeDocument
with (myDocument.viewPreferences){ var myOldXUnits = horizontalMeasurementUnits; var myOldYUnits = verticalMeasurementUnits; horizontalMeasurementUnits = MeasurementUnits.points; verticalMeasurementUnits = MeasurementUnits.points;
}
//At this point, you can perform any series of script actions
//that depend on the measurement units you've set. At the end of
//the script, reset the measurement units to their original state.
with (myDocument.viewPreferences){ try{ horizontalMeasurementUnits = myOldXUnits; verticalMeasurementUnits = myOldYUnits;
} catch(myError){ alert("Could not reset custom measurement units.");
}
}
第 3 章 ドキュメント 基本的なページレイアウト 30
ドキュメントプリセットの定義と適用
InDesign のドキュメントプリセットを使用すれば、よく使用するドキュメント設定情報(ページサイズ、
ページマージン、段組、裁ち落としと印刷可能領域など)を保存して、適用することができます。 新規ド
キュメントを作成する際には、ドキュメントプリセットに基づいてドキュメントを作成することができます。
既存の値をコピーしてプリセットを作成する
既存のドキュメントの設定をサンプルとして使用してドキュメントプリセットを作成するには、ドキュメン
トプリセットで使用したいドキュメント設定プロパティが含まれているドキュメントを開き、その後で次の
スクリプトを実行します(チュートリアルスクリプトの DocumentPresetByExample より)。 var myDocumentPreset; if(app.documents.length > 0){ var myDocument = app.activeDocument;
//If the document preset "myDocumentPreset" does not already
//exist, create it.
myDocumentPreset = app.documentPresets.item("myDocumentPreset"); try { var myPresetName = myDocumentPreset.name;
} catch (myError){ myDocumentPreset = app.documentPresets.add({name:"myDocumentPreset"});
}
//Set the application default measurement units to match the document
//measurement units.
app.viewPreferences.horizontalMeasurementUnits = myDocument.viewPreferences.horizontalMeasurementUnits; app.viewPreferences.verticalMeasurementUnits = myDocument.viewPreferences.verticalMeasurementUnits;
//Fill in the properties of the document preset with the corresponding
//properties of the active document.
with(myDocumentPreset){
//Note that the following gets the page margins
//from the margin preferences of the document; to get the margin
//preferences from the active page,replace "app.activeDocument" with
//"app.activeWindow.activePage" in the following line (assuming the
//active window is a layout window).
var myMarginPreferences = app.activeDocument.marginPreferences; left = myMarginPreferences.left; right = myMarginPreferences.right; top = myMarginPreferences.top; bottom = myMarginPreferences.bottom; columnCount = myMarginPreferences.columnCount; columnGutter = myMarginPreferences.columnGutter; documentBleedBottom = app.activeDocument.documentPreferences.documentBleedBottomOffset; documentBleedTop = app.activeDocument.documentPreferences.documentBleedTopOffset; documentBleedLeft = app.activeDocument.documentPreferences.documentBleedInsideOrLeftOffset; documentBleedRight = app.activeDocument.documentPreferences.
documentBleedOutsideOrRightOffset; facingPages = app.activeDocument.documentPreferences.facingPages;
第 3 章 ドキュメント 基本的なページレイアウト 31
}
} pageHeight = app.activeDocument.documentPreferences.pageHeight; pageWidth = app.activeDocument.documentPreferences.pageWidth; pageOrientation = app.activeDocument.documentPreferences.pageOrientation; pagesPerDocument = app.activeDocument.documentPreferences.pagesPerDocument; slugBottomOffset = app.activeDocument.documentPreferences.slugBottomOffset; slugTopOffset = app.activeDocument.documentPreferences.slugTopOffset; slugInsideOrLeftOffset = app.activeDocument.documentPreferences.slugInsideOrLeftOffset; slugRightOrOutsideOffset = app.activeDocument.documentPreferences.slugRightOrOutsideOffset;
ドキュメントプリセットの作成
明示的に値を指定してドキュメントプリセットを作成するには、次のスクリプトを実行します(チュートリ
アルスクリプトの DocumentPreset より)。 var myDocumentPreset;
//If the document preset "myDocumentPreset" does not already exist, create it.
myDocumentPreset = app.documentPresets.item("myDocumentPreset"); try { var myPresetName = myDocumentPreset.name;
} catch (myError){ myDocumentPreset = app.documentPresets.add({name:"myDocumentPreset"});
}
//Fill in the properties of the document preset.
with(myDocumentPreset){ pageHeight = "9i"; pageWidth = "7i"; left = "4p"; right = "6p"; top = "4p"; bottom = "9p"; columnCount = 1; documentBleedBottom = "3p"; documentBleedTop = "3p"; documentBleedLeft = "3p"; documentBleedRight = "3p"; facingPages = true; pageOrientation = PageOrientation.portrait; pagesPerDocument = 1; slugBottomOffset = "18p"; slugTopOffset = "3p"; slugInsideOrLeftOffset = "3p"; slugRightOrOutsideOffset = "3p";
}
第 3 章 ドキュメント 基本的なページレイアウト 32
マスタースプレッドの設定
基本的なドキュメントページのサイズ、印刷可能領域、裁ち落としを設定したら、ドキュメントのマスター
スプレッドを定義するのが一般的です。 次のスクリプトにその例を示します (完全なスクリプトについては、 myDocument = app.documents.add();
//Set up the document.
with(myDocument.documentPreferences){ pageHeight = "11i" pageWidth = "8.5i" facingPages = true; pageOrientation = PageOrientation.portrait;
}
//Set the document's ruler origin to page origin. This is very important
//--if you don't do this, getting objects to the correct position on the
//page is much more difficult.
myDocument.viewPreferences.rulerOrigin = RulerOrigin.pageOrigin; with(myDocument.masterSpreads.item(0)){
//Set up the left page (verso).
with(pages.item(0)){ with(marginPreferences){ columnCount = 3; columnGutter = "1p"; bottom = "6p"
//"left" means inside; "right" means outside.
left = "6p" right = "4p" top = "4p"
}
//Add a simple footer with a section number and page number.
with(textFrames.add()){ geometricBounds = ["61p", "4p", "62p", "45p"]; insertionPoints.item(0).contents = SpecialCharacters.sectionMarker; insertionPoints.item(0).contents = SpecialCharacters.emSpace; insertionPoints.item(0).contents = SpecialCharacters.autoPageNumber; paragraphs.item(0).justification = Justification.leftAlign;
}
}
//Set up the right page (recto).
with(pages.item(1)){ with(marginPreferences){ columnCount = 3; columnGutter = "1p"; bottom = "6p"
//"left" means inside; "right" means outside.
left = "6p" right = "4p" top = "4p"
}
//Add a simple footer with a section number and page number.
with(textFrames.add()){ geometricBounds = ["61p", "6p", "62p", "47p"]; insertionPoints.item(0).contents = SpecialCharacters.autoPageNumber; insertionPoints.item(0).contents = SpecialCharacters.emSpace; insertionPoints.item(0).contents = SpecialCharacters.sectionMarker; paragraphs.item(0).justification = Justification.rightAlign;
}
}
}
第 3 章 ドキュメント 基本的なページレイアウト 33
ドキュメントページにマスタースプレッドを適用するには、ドキュメントページの appliedMaster
プロパ
ティを使用します。次のスクリプトにその例を示します(チュートリアルスクリプトの ApplyMaster より)。
//Assumes that the active document has a master page named "B-Master"
//and at least three pages--page 3 is pages.item(2) because JavaScript arrays are zero-based.
app.activeDocument.pages.item(2).appliedMaster = app.activeDocument.masterSpreads.item("B-Master");
同じプロパティを使用して、マスタースプレッドページにマスタースプレッドを適用します。次のスクリプ
トにその例を示します(チュートリアルスクリプトの ApplyMasterToMaster より)。
//Assumes that the active document has master spread named "B-Master"
//that is not the same as the first master spread in the document.
app.activeDocument.masterSpreads.item(0).pages.item(0).appliedMaster = app.activeDocument.masterSpreads.item("B-Master");
XMP メタデータの追加
メタデータとは、ファイルの内容や作成元などの属性を示す情報のことです。 InDesign のユーザーインター
フェイスでは、ファイル情報ダイアログボックス(ファイル/ファイル情報を選択)を使用して、メタデー
タの入力、編集、表示を行います。 このメタデータには、ドキュメントの作成日、修正日、作成者、著作権
のステータスなどがあります。 こうした情報はすべて、XMP(Adobe Extensible Metadata Platform)を使用し
て保存されます。XMP は、ドキュメントにメタデータを埋め込むためのオープンスタンダードです。
XMP について詳しくは、 http://partners.adobe.com/public/developer/xmp/sdk に掲載されている XMP の仕様を
参照してください。
ての XMP プロパティは、ドキュメントの metadataPreferences
オブジェクトに含まれています。
トの標準 XMP データを入力する例を次に示します。
この例では、XMP 情報を拡張する方法も示されています。 ドキュメントにメタデータを添付する必要があり、
そのデータが metadata preferences オブジェクトで定義されているカテゴリーに該当しない場合は、独自のメ
タデータコンテナを作成できます(この例では email
)
を参照してください) var myDocument = app.documents.add(); with (myDocument.metadataPreferences){ author = "Adobe"; copyrightInfoURL = "http://www.adobe.com"; copyrightNotice = "This document is copyrighted."; copyrightStatus = CopyrightStatus.yes; description = "Example of xmp metadata scripting in InDesign CS"; documentTitle = "XMP Example"; jobName = "XMP_Example_2003"; keywords = ["animal", "mineral", "vegetable"];
//The metadata preferences object also includes the read-only
//creator, format, creationDate, modificationDate, and serverURL
//properties that are automatically entered and maintained by InDesign.
//Create a custom XMP container, "email" var myNewContainer = createContainerItem("http://ns.adobe.com/xap/1.0/", "email"); setProperty("http://ns.adobe.com/xap/1.0/", "email/*[1]", "[email protected]");
}
第 3 章 ドキュメント 基本的なページレイアウト 34
ドキュメントテンプレートの作成
次の例では、新規ドキュメントを作成し、裁ち落としと印刷可能領域を定義し、ドキュメントの XMP メタ
データに情報を追加し、マスターページを設定し、ページフッターを追加し、印刷可能領域の表にジョブ情
報を追加しています (完全なスクリプトについては、DocumentTemplate を参照してください)。
//Set the application default margin preferences.
with (app.marginPreferences){
//Save the current application default margin preferences.
var myY1 = top; var myX1 = left; var myY2 = bottom; var myX2 = right;
//Set the application default margin preferences.
//Document baseline grid will be based on 14 points, and
//all margins are set in increments of 14 points.
top = 14 * 4 + "pt"; left = 14 * 4 + "pt"; bottom = "74pt"; right = 14 * 5 + "pt";
}
//Make a new document.
var myDocument = app.documents.add(); myDocument.documentPreferences.pageWidth = "7i"; myDocument.documentPreferences.pageHeight = "9i"; myDocument.documentPreferences.pageOrientation = PageOrientation.portrait;
//At this point, we can reset the application default margins to their original state.
with (app.marginPreferences){ top = myY1; left = myX1; bottom = myY2; right = myX2;
}
//Set up the bleed and slug areas.
with(myDocument.documentPreferences){
//Bleed documentBleedBottomOffset = "3p"; documentBleedTopOffset = "3p"; documentBleedInsideOrLeftOffset = "3p"; documentBleedOutsideOrRightOffset = "3p";
//Slug slugBottomOffset = "18p"; slugTopOffset = "3p"; slugInsideOrLeftOffset = "3p"; slugRightOrOutsideOffset = "3p";
}
//Create a color.
try{ myDocument.colors.item("PageNumberRed").name;
} catch (myError){ myDocument.colors.add({name:"PageNumberRed", model:ColorModel.process, colorValue:[20, 100,
80, 10]});
}
//Next, set up some default styles.
//Create up a character style for the page numbers.
try{ myDocument.characterStyles.item("page_number").name;
} catch (myError){ myDocument.characterStyles.add({name:"page_number"});
} myDocument.characterStyles.item("page_number").fillColor = myDocument.colors.item("PageNumberRed");
//Create up a pair of paragraph styles for the page footer text.
第 3 章 ドキュメント 基本的なページレイアウト 35
//These styles have only basic formatting.
try{ myDocument.paragraphStyles.item("footer_left").name;
} catch (myError){ myDocument.paragraphStyles.add({name:"footer_left", pointSize:11, leading:14});
}
//Create up a pair of paragraph styles for the page footer text.
try{ myDocument.paragraphStyles.item("footer_right").name;
} catch (myError){ myDocument.paragraphStyles.add({name:"footer_right", basedOn:myDocument.paragraphStyles.item("footer_left"), justification:Justification.rightAlign, pointSize:11, leading:14});
}
//Create a layer for guides.
try{ myDocument.layers.item("GuideLayer").name;
} catch (myError){ myDocument.layers.add({name:"GuideLayer"});
}
//Create a layer for the footer items.
try{ myDocument.layers.item("Footer").name;
} catch (myError){ myDocument.layers.add({name:"Footer"});
}
//Create a layer for the slug items.
try{ myDocument.layers.item("Slug").name;
} catch (myError){ myDocument.layers.add({name:"Slug"});
}
//Create a layer for the body text.
try{ myDocument.layers.item("BodyText").name;
} catch (myError){ myDocument.layers.add({name:"BodyText"});
} with(myDocument.viewPreferences){ rulerOrigin = RulerOrigin.pageOrigin; horizontalMeasurementUnits = MeasurementUnits.points; verticalMeasurementUnits = MeasurementUnits.points;
}
//Document baseline grid and document grid with(myDocument.gridPreferences){ baselineStart = 56; baselineDivision = 14; baselineShown = false; horizontalGridlineDivision = 14; horizontalGridSubdivision = 5 verticalGridlineDivision = 14; verticalGridSubdivision = 5 documentGridShown = false;
}
//Document XMP information.
with (myDocument.metadataPreferences){ author = "Olav Martin Kvern";
第 3 章 ドキュメント 基本的なページレイアウト 36 copyrightInfoURL = "http://www.adobe.com"; copyrightNotice = "This document is not copyrighted."; copyrightStatus = CopyrightStatus.no; description = "Example 7 x 9 book layout"; documentTitle = "Example"; jobName = "7 x 9 book layout template"; keywords = ["7 x 9", "book", "template"]; var myNewContainer = createContainerItem("http://ns.adobe.com/xap/1.0/", "email"); setProperty("http://ns.adobe.com/xap/1.0/", "email/*[1]", "[email protected]");
}
//Set up the master spread.
with(myDocument.masterSpreads.item(0)){ with(pages.item(0)){
//Left and right are reversed for left-hand pages (becoming "inside" and "outside"--
//this is also true in the InDesign user interface).
var myBottomMargin = myDocument.documentPreferences.pageHeight - marginPreferences.bottom; var myRightMargin = myDocument.documentPreferences.pageWidth - marginPreferences.left; guides.add(myDocument.layers.item("GuideLayer"),
{orientation:HorizontalOrVertical.vertical,location:marginPreferences.right}); guides.add(myDocument.layers.item("GuideLayer"),
{orientation:HorizontalOrVertical.vertical, location:myRightMargin}); guides.add(myDocument.layers.item("GuideLayer"),
{orientation:HorizontalOrVertical.horizontal, location:marginPreferences.top, fitToPage:false}); guides.add(myDocument.layers.item("GuideLayer"),
{orientation:HorizontalOrVertical.horizontal, location:myBottomMargin, fitToPage:false}); guides.add(myDocument.layers.item("GuideLayer"),
{orientation:HorizontalOrVertical.horizontal, location:myBottomMargin + 14, fitToPage:false}); guides.add(myDocument.layers.item("GuideLayer"),
{orientation:HorizontalOrVertical.horizontal, location:myBottomMargin + 28, fitToPage:false}); var myLeftFooter = textFrames.add(myDocument.layers.item("Footer"), undefined, undefined,
{geometricBounds:[myBottomMargin+14, marginPreferences.right, myBottomMargin+28, myRightMargin]}) myLeftFooter.parentStory.insertionPoints.item(0).contents =
SpecialCharacters.sectionMarker; myLeftFooter.parentStory.insertionPoints.item(0).contents = SpecialCharacters.emSpace; myLeftFooter.parentStory.insertionPoints.item(0).contents =
SpecialCharacters.autoPageNumber; myLeftFooter.parentStory.characters.item(0).appliedCharacterStyle = myDocument.characterStyles.item("page_number"); myLeftFooter.parentStory.paragraphs.item(0).applyStyle(myDocument.paragraphStyles.item("footer_l eft", false));
//Slug information.
with(myDocument.metadataPreferences){ var myString = "Author:¥t" + author + "¥tDescription:¥t" + description + "¥rCreation
Date:¥t" + new Date +
"¥tEmail Contact¥t" + getProperty("http://ns.adobe.com/xap/1.0/", "email/*[1]");
} var myLeftSlug = textFrames.add(myDocument.layers.item("Slug"), undefined, undefined,
{geometricBounds:[myDocument.documentPreferences.pageHeight+36, marginPreferences.right, myDocument.documentPreferences.pageHeight + 144, myRightMargin], contents:myString}); myLeftSlug.parentStory.tables.add();
//Body text master text frame.
var myLeftFrame = textFrames.add(myDocument.layers.item("BodyText"), undefined, undefined, {geometricBounds:[marginPreferences.top, marginPreferences.right, myBottomMargin, myRightMargin]});
} with(pages.item(1)){ var myBottomMargin = myDocument.documentPreferences.pageHeight - marginPreferences.bottom; var myRightMargin = myDocument.documentPreferences.pageWidth - marginPreferences.right; guides.add(myDocument.layers.item("GuideLayer"),
{orientation:HorizontalOrVertical.vertical,location:marginPreferences.left});
第 3 章 ドキュメント 基本的なページレイアウト 37 guides.add(myDocument.layers.item("GuideLayer"),
{orientation:HorizontalOrVertical.vertical, location:myRightMargin}); var myRightFooter = textFrames.add(myDocument.layers.item("Footer"), undefined, undefined, {geometricBounds:[myBottomMargin+14, marginPreferences.left, myBottomMargin+28, myRightMargin]}) myRightFooter.parentStory.insertionPoints.item(0).contents =
SpecialCharacters.autoPageNumber; myRightFooter.parentStory.insertionPoints.item(0).contents = SpecialCharacters.emSpace; myRightFooter.parentStory.insertionPoints.item(0).contents =
SpecialCharacters.sectionMarker; myRightFooter.parentStory.characters.item(-1).appliedCharacterStyle = myDocument.characterStyles.item("page_number"); myRightFooter.parentStory.paragraphs.item(0).applyStyle(myDocument.paragraphStyles.item("footer_ right", false));
//Slug information.
var myRightSlug = textFrames.add(myDocument.layers.item("Slug"), undefined, undefined, {geometricBounds:[myDocument.documentPreferences.pageHeight+36, marginPreferences.left, myDocument.documentPreferences.pageHeight + 144, myRightMargin], contents:myString}); myRightSlug.parentStory.tables.add(); undefined, {geometricBounds:[marginPreferences.top, marginPreferences.left, myBottomMargin, myRightMargin], previousTextFrame:myLeftFrame});
}
//Body text master text frame.
var myRightFrame = textFrames.add(myDocument.layers.item("BodyText"), undefined,
}
//Add section marker text--this text will appear in the footer.
myDocument.sections.item(0).marker = "Section 1";
//When you link the master page text frames, one of the frames sometimes becomes selected. Deselect it.
app.select(NothingEnum.nothing, undefined);
透かしの作成
InDesign や InDesign Server では、スクリプトを使用してドキュメントに透かしを適用することができます。
現時点では、InDesign に透かしを操作するユーザーインターフェイスは存在しません。
ドキュメントの透かし環境設定は、スクリプトを使用した次の 2 種類の方法で設定できます。
アプリケーションレベルの watermark preferences が設定されている場合、InDesign で作成するすべての
新規ドキュメントに、この透かし環境設定が適用されます。 この設定は、既存のドキュメントには影響
を与えません。
ドキュメントレベルの watermark preferences は、該当のドキュメントにのみ適用されます。 ドキュメン
トの watermark preferences を設定したり変更したりすると、ドキュメントの以前の透かし環境設定が上
書きされます。
ドキュメントレベルおよびアプリケーションレベルの透かし環境設定は、いずれもドキュメントを閉じるか
アプリケーションを終了してから、スクリプトで変更されるまで保持されます。
ドキュメントオブジェクトとアプリケーションオブジェクトの両方に、同じ透かし環境設定のグループがあ
ります。
第 3 章 ドキュメント 基本的なページレイアウト 38
watermark preferences の設定
アプリケーションレベルで透かしを設定する方法を、次のスクリプトに示します。 このコードの実行後は、
作成するドキュメントのすべてに透かしが適用されます (アプリケーションの環境設定を指定する完全なス
クリプトについては、ApplicationWatermark を参照してください)。 app.watermarkPreferences.watermarkVisibility = true; app.watermarkPreferences.watermarkDoPrint = true; app.watermarkPreferences.watermarkDrawInBack = true; app.watermarkPreferences.watermarkText = "Confidential"; app.watermarkPreferences.watermarkFontFamily = "Arial"; app.watermarkPreferences.watermarkFontStyle = "Bold"; app.watermarkPreferences.watermarkFontPointSize = 72; app.watermarkPreferences.watermarkFontColor = UIColors.red; app.watermarkPreferences.watermarkOpacity = 60; app.watermarkPreferences.watermarkRotation = -45; app.watermarkPreferences.watermarkHorizontalPosition =
WatermarkHorizontalPositionEnum.watermarkHCenter; app.watermarkPreferences.watermarkHorizontalOffset = 0; app.watermarkPreferences.watermarkVerticalPosition =
WatermarkVerticalPositionEnum.watermarkVCenter; app.watermarkPreferences.watermarkVerticalOffset = 0;
アプリケーションではなくドキュメントを参照するようにすると、同じ環境設定をドキュメントオブジェク
トに適用できます (ドキュメントの環境設定を指定する完全なスクリプトについては、DocumentWatermark
を参照してください)。 var myDocument = app.documents.item(0); myDocument.watermarkPreferences.watermarkVisibility = true; myDocument.watermarkPreferences.watermarkDoPrint = true; myDocument.watermarkPreferences.watermarkDrawInBack = true; myDocument.watermarkPreferences.watermarkText = "Confidential"; myDocument.watermarkPreferences.watermarkFontFamily = "Arial"; myDocument.watermarkPreferences.watermarkFontStyle = "Bold"; myDocument.watermarkPreferences.watermarkFontPointSize = 72; myDocument.watermarkPreferences.watermarkFontColor = UIColors.blue; myDocument.watermarkPreferences.watermarkOpacity = 60; myDocument.watermarkPreferences.watermarkRotation = -45; myDocument.watermarkPreferences.watermarkHorizontalPosition =
WatermarkHorizontalPositionEnum.watermarkHCenter; myDocument.watermarkPreferences.watermarkHorizontalOffset = 0; myDocument.watermarkPreferences.watermarkVerticalPosition =
WatermarkVerticalPositionEnum.watermarkVCenter; myDocument.watermarkPreferences.watermarkVerticalOffset = 0;
透かしの無効化
透かしのアプリケーション設定をオフにすると、新規ドキュメントの透かし設定はデフォルトではオンにな
らなくなります。 ただし、個々のドキュメントに透かしを設定することは可能です。 アプリケーションレベル
の透かしをオフにする方法を、次のスクリプトに示します。 app.watermarkPreferences.watermarkVisibility = false;
個々のドキュメントの透かしは、いつでもオフにすることができます。次のスクリプトにその例を示します。 app.documents.item(0).watermarkPreferences.watermarkVisibility = false;
第 3 章 ドキュメント
ページサイズとレイアウトの調整
ページサイズとレイアウトの調整 39
また、個々のページに変形を適用することもできます。
ページの選択
ページをサイズ変更したりページに変形を適用するには、まずページを選択する必要があります。 InDesign
のユーザーインターフェイスでページを選択するには、ツールパネルのページツールを使用します。 また、
スクリプトを使用してページを選択することもできます。 次のスクリプトにその例を示します (完全なスク
リプトについては、PageSelect を参照してください)。
//Given a document with four pages (0, 1, 2, 3)...
var myDocument = app.activeDocument; var myPages = myDocument.pages;
//Select page 1 and 2.
myPages.item(1).select(); myPages.item(2).select(SelectionOptions.ADD_TO);
//Select last page.
myDocument.select(myPages.item(-1), SelectionOptions.ADD_TO);
ページのサイズ変更とフレーム調整
スクリプトを使用して、ページ上のページアイテムをサイズ変更したり、フレームを調整したりできます。
また、サイズ変更やフレーム調整の操作を複数のページに適用して各ページをサイズ変更することもできま
す。
resize メソッドを使用してページをサイズ変更する方法を、次のスクリプトに示します (完全なスクリプト
については、PageResize を参照してください)。
//Given a document with four pages (0, 1, 2, 3)...
var myDocument = app.activeDocument; var myPages = myDocument.pages;
//Resize page to two times bigger myPages.item(1).resize(CoordinateSpaces.INNER_COORDINATES,
AnchorPoint.CENTER_ANCHOR,
ResizeMethods.MULTIPLYING_CURRENT_DIMENSIONS_BY,
[2, 2]);
//Resize page to 400 points width and 600 points height.
myPages.item(2).resize(CoordinateSpaces.INNER_COORDINATES,
AnchorPoint.CENTER_ANCHOR,
ResizeMethods.REPLACING_CURRENT_DIMENSIONS_WITH,
[400, 600]);
フレーム調整を行うと、ページのバウンディングボックスが変更されます。そのため、フレーム調整を使用
して、バウンディングボックスを大きくしたり小さくしたりすることで、ページをサイズ変更できます。 reframe メソッドを使用してページをサイズ変更する方法を、次のスクリプトに示します (完全なスクリプ
トについては、PageReframe を参照してください)。
第 3 章 ドキュメント ページサイズとレイアウトの調整 40
//Given a document with four pages (0, 1, 2, 3)...
var myDocument = app.activeDocument; var myPages = myDocument.pages;
//Make the page one inch wider and one inch higher.
var myPage = myPages.item(1); var myBounds = myPage.bounds; var myY1 = myBounds[0]; var myX1 = myBounds[1]; var myY2 = myBounds[2]+72; var myX2 = myBounds[3]+72; myPage.reframe(CoordinateSpaces.INNER_COORDINATES, [[myX1, myY1], [myX2, myY2]]);
ページの変形
オブジェクトの形状を変更する操作は、変形と呼ばれます。 transform メソッドで、ページ上のページアイテ
ムを回転、拡大・縮小、シアーおよび移動(平行移動)して、ページ上で使用できます。 変形アーキテク
ページを変形するには:
1.
変形マトリックスを作成します。
2.
この変形マトリックスを transform メソッドを使用してページに適用します。
スクリプトを使用してページを変形する方法を、次のスクリプトに示します (完全なスクリプトについて
は、PageTransform を参照してください)。
//Given a document with four pages (0, 1, 2, 3)...
var myDocument = app.activeDocument; var myPages = myDocument.pages;
//Rotate a page around its center point.
var myRotateMatrix = app.transformationMatrices.add({counterclockwiseRotationAngle:27}); myTransform(myPages.item(0), myRotateMatrix);
//Scale a page around its center point.
var myScaleMatrix = app.transformationMatrices.add({horizontalScaleFactor:0.8, verticalScaleFactor:0.8}); myTransform(myPages.item(1), myScaleMatrix);
//Shear a page around its center point.
var myShearMatrix = app.transformationMatrices.add({clockwiseShearAngle:30}); myTransform(myPages.item(2), myShearMatrix); function myTransform(myPage, myTransformationMatrix)
{ myPage.transform(CoordinateSpaces.PASTEBOARD_COORDINATES,
AnchorPoint.CENTER_ANCHOR, myTransformationMatrix);
}
マスターページオーバーレイ
ページには複数のサイズが設定できるため、ページとそのマスターページで別々のサイズを設定することが
ジ上に描画されるかを定めるマトリックスも維持されます。 これをマスターページオーバーレイと呼びます。
ツールパネルのページツールを使用してページを選択するときに、コントロールパネルの「マスターページ
オーバーレイを表示」チェックボックスをオンにすると、マスターページの配置仕様を確認できます。 オー
バーレイは、マウスで移動することができます。 これは、マスターオーバーレイのマトリックスに変形を適
用することで実現しています。 ユーザーインターフェイスからは平行移動(x および y の移動)のみ可能です
第 3 章 ドキュメント 調整型レイアウトの作成 41
が、スクリプトではその他の操作も実行できます。 マスターページオーバーレイを変形する方法を、次のス
クリプトに示します (完全なスクリプトについては、MasterPageTransform を参照してください)。
//Given a document with four pages (0, 1, 2, 3)...
var myDocument = app.activeDocument; var myPages = myDocument.pages;
//Rotate master page overlay around its top-left corner.
var myRotateMatrix = app.transformationMatrices.add({counterclockwiseRotationAngle:27}); myPages.item(0).masterPageTransform = myRotateMatrix;
//Scale master page overlay around its top-left corner.
var myScaleMatrix = app.transformationMatrices.add({horizontalScaleFactor:0.5, verticalScaleFactor:0.5}); myPages.item(1).masterPageTransform = myScaleMatrix;
//Shear master page overlay around its top-left corner.
var myShearMatrix =app.transformationMatrices.add({clockwiseShearAngle:30}); myPages.item(2).masterPageTransform = myShearMatrix;
//Translate master page overlay 1 inch right and 2 inches down.
var myTranslateMatrix = app.transformationMatrices.add({horizontalTranslation:72, verticalTranslation:144}); myPages.item(3).masterPageTransform = myTranslateMatrix;
調整型レイアウトの作成
InDesign のレイアウト調整ワークフローを使用して作成した基本レイアウトは、異なる方向、サイズ、縦横
比、またはまったく異なるデバイスクラスに簡単に適応させることができます。基本レイアウトの作成方法
は、プリント用ドキュメントのレイアウトを作成する場合と同じです。 このワークフローには主に 2 つの機
能が関連しています。レイアウトに柔軟性を与えるリキッドレイアウトと、様々な方向およびデバイスクラ
ス用の代替レイアウトを作成する代替レイアウト作成という機能です。
柔軟性のあるレイアウトの作成
レイアウトルールを使用して作成した 1 セットの物理的なページで構成される InDesign ファイルは、サイズ
や方向が異なるデバイス上でも、そのコンテンツがそれぞれのデバイスに適した状態で表示されます。 必要
であれば、サイズおよび方向ごとにページの外観を指定できます。 次のスクリプト例に、その方法を示しま
す (完全なスクリプトについては、LiquidLayout を参照してください)。 var doc = app.documents.add(); var myPage = doc.pages.item(0);
//Set layout rule to LayoutRuleOptions.OBJECT_BASED
//Reposition and resize objects on the page as it resizes.
myPage.layoutRule = LayoutRuleOptions.OBJECT_BASED ;
//Create a text frame on the first page.
var myTextFrame = myPage.textFrames.add({ geometricBounds:myGetBounds(doc, myPage), contents:"This is object-based layoutRule sample doc."
});
//Create a rectangle var myItem = myPage.rectangles.add({geometricBounds:[20,20,70,70]}); myItem.verticalLayoutConstraints =
[DimensionsConstraints.flexibleDimension,
DimensionsConstraints.flexibleDimension,
DimensionsConstraints.flexibleDimension]; myItem.horizontalLayoutConstraints =
[DimensionsConstraints.fixedDimension,
DimensionsConstraints.flexibleDimension,
DimensionsConstraints.flexibleDimension];
第 3 章 ドキュメント var doc2 = app.documents.add(); var myPage2 = doc2.pages.item(0);
//Set layout rule to LayoutRuleOptions.SCALE
//Scale objects on the page as it resizes. myPage2.layoutRule = LayoutRuleOptions.SCALE;
//Create a text frame on the first page.
var myTextFrame2 = myPage2.textFrames.add({ geometricBounds:myGetBounds(doc2, myPage2), contents:"This is scale layoutRule sample doc."
}); var myItem2 = myPage2.rectangles.add({geometricBounds:[20,20,70,70]}); var doc3 = app.documents.add(); var myPage3 = doc3.pages.item(0);
//Set layout rule to LayoutRuleOptions.RECENTER
//Recenter objects on the page as it resizes.
myPage3.layoutRule = LayoutRuleOptions.RECENTER;
//Create a text frame on the first page.
var myTextFrame = myPage3.textFrames.add({ geometricBounds:myGetBounds(doc3, myPage3), contents:"This is recenter layoutRule sample doc."
}); var myItem = myPage3.rectangles.add({geometricBounds:[20,20,70,70]}); var doc4 = app.documents.add(); var myPage4 = doc4.pages.item(0);
//Set layout rule to LayoutRuleOptions.GUIDE_BASED
//Use guide slicing to resize objects on the page as it resizes.
myPage4.layoutRule = LayoutRuleOptions.GUIDE_BASED;
//Create a text frame on the first page.
var myTextFrame4 = myPage4.textFrames.add({ geometricBounds:myGetBounds(doc4, myPage4),
contents:"This is guide-based layoutRule sample doc."
}); var myItem4 = myPage4.rectangles.add({geometricBounds:[20,20,70,70]}); with(doc4)
{ guides.add({ guideType:GuideTypeOptions:LIQUID, location:40, orientation:HorizontalOrVertical.horizontal});
} var doc5 = app.documents.add(); var myPage5 = doc5.pages.item(0);
//Set layout rule to LayoutRuleOptions.USE_MASTER
//Use layout rule from the page's applied master page.
myPage5.layoutRule = LayoutRuleOptions.USE_MASTER;
//Create a text frame on the first page.
var myTextFrame5 = myPage5.textFrames.add(
{geometricBounds:myGetBounds(doc5, myPage5), contents:"This is master page layoutRule sample doc."
}); var myItem5 = myPage5.rectangles.add({geometricBounds:[20,20,70,70]});
調整型レイアウトの作成 42
第 3 章 ドキュメント 調整型レイアウトの作成 43
ガイドベースのレイアウトへのガイドの追加
ガイドベースのレイアウトルールにガイドスライスを追加する方法を、次のスクリプト例に示します (完全
なスクリプトについては、AddGuides を参照してください)。 var doc = app.documents.add(); var myPage = doc.pages.item(0);
//Use guide slicing to resize objects on the page as it resizes.
myPage.layoutRule = LayoutRuleOptions.GUIDE_BASED;
//Create a text frame on the first page.
var myTextFrame = myPage.textFrames.add({ geometricBounds:myGetBounds(doc, myPage), contents:"This is guide-based LayoutRule sample doc."
}); var myItem = myPage.rectangles.add({geometricBounds:[20,20,70,70]}); with(doc)
{
//add guide slice guides.add({
guideType:GuideTypeOptions.LIQUID,
location:20,
orientation:HorizontalOrVertical.horizontal
});
}
オブジェクトベースのレイアウトへの制約の設定
オブジェクトベースのレイアウトルールに制約を設定する方法を、次のスクリプト例に示します (完全なス
クリプトについては、SetConstraints を参照してください)。 var doc = app.documents.add(); var myPage = doc.pages.item(0);
//Reposition and resize objects on the page as it resizes.
myPage.layoutRule = LayoutRuleOptions.OBJECT_BASED ;
//Create a text frame on the first page.
var myTextFrame = myPage.textFrames.add({ geometricBounds:myGetBounds(doc, myPage), contents:"This is object-based layoutRule sample doc."
});
//Create a rectagle var myItem = myPage.rectangles.add({geometricBounds:[20,20,70,70]});
//set constrains myItem.verticalLayoutConstraints =
[DimensionsConstraints.flexibleDimension,
DimensionsConstraints.flexibleDimension,
DimensionsConstraints.flexibleDimension]; myItem.horizontalLayoutConstraints =
[DimensionsConstraints.fixedDimension,
DimensionsConstraints.flexibleDimension,
DimensionsConstraints.flexibleDimension];
第 3 章 ドキュメント コンテンツの収集とドロップ 44
代替レイアウトの作成
代替レイアウト作成は、コンテンツが含まれている既存ページの範囲を取得し、そのコンテンツのリンク付
きコピーを、同じドキュメント内の新しいページセット上に自動的に作成します。 これは、方向およびデバ
イスクラスごとに異なるレイアウトを作成する必要がある場合に使用します (完全なスクリプトについて
は、CreateAlternateLayout を参照してください)。 myDoc = app.documents.add({ documentPreferences:
{ facingPages:false, pagesPerDocument:1, pageWidth:1024, pageHeight:768
}
});
//Reposition and resize objects on the page as it resizes.
myDoc.pages[0].layoutRule = LayoutRuleOptions.OBJECT_BASED ;
with (myDoc)
{ var myItem = pages[0].rectangles.add({ geometricBounds:[50,50,100,100]
});
//create alternate layout myDoc.createAlternateLayout(myDoc.spreads,
"new layout", myDoc.documentPreferences.pageHeight, myDoc.documentPreferences.pageWidth, true, true,
LayoutRuleOptions.PRESERVE_EXISTING);
}
コンテンツの収集とドロップ
コンテンツドロッパーを使用すると、プリント用にデザインしたファイルからコンテンツをコピーし、別の
ドキュメントに貼り付けることができます。
スクリプトを使用してドキュメント内のコンテンツを収集する方法を、次のスクリプトに示します (完全な
スクリプトについては、ContentCollectorAndPlacer を参照してください)。
//Invoke load with full parameters contentPlacer.load(myPage.rectangles, true, true, true, true);
収集したコンテンツを別のドキュメントに配置する方法を、次のスクリプトに示します (完全なスクリプト
については、ContentCollectorAndPlacer を参照してください)。
//Invoke Page.contentPlace with full parameters
myPage1.contentPlace(myPage.rectangles, //One or more page items to place or load true, true,
//Whether to link pageItems in content placer (Optional)
//Whether to link stories in content placer (Optional) true,
[0, 0, 40, 40],
//Whether to map styles in content placer (Optional)
//The point at which to place (Optional) myDocument1.activeLayer, true);
//The layer on which to place (Optional)
//Whether to display the link options dialog (Optional)
第 3 章 ドキュメント ドキュメントのプリント 45
ドキュメントのプリント
次のスクリプトでは、現在の print preferences を使用して、アクティブなドキュメントをプリントします
(完全なスクリプトについては、PrintDocument を参照してください)。 app.activeDocument.print();
ページ範囲を使用したプリント
プリントするページの範囲を指定するには、プリントを行う前に、ドキュメントの print preferences
オブ
ジェクトの pageRange
プロパティを設定します。次のスクリプトにその例を示します(チュートリアルスク
リプトの PrintPageRange より)。
//Prints a page range from the active document.
//Assumes that you have a document open, that it contains a page named "22".
//The page range can be either PageRange.allPages or a page range string.
//A page number entered in the page range must correspond to a page
//name in the document (i.e., not the page index). If the page name is
//not found, InDesign will display an error message.
app.activeDocument.printPreferences.pageRange = "22" app.activeDocument.print(false);
print preferences の設定
print preferences
オブジェクトに保持されているプロパティは、プリントダイアログボックスの各パネルに
含まれているオプションに対応しています。 スクリプティングで print preferences を設定する方法を、次のス
クリプトに示します (完全なスクリプトについては、PrintPreferences を参照してください)。
//PrintPreferences.jsx
//An InDesign CS6 JavaScript
//Sets the print preferences of the active document.
with(app.activeDocument.printPreferences){
//Properties corresponding to the controls in the General panel
//of the Print dialog box. activePrinterPreset is ignored in this
//example--we'll set our own print preferences. printer can be
//either a string (the name of the printer) or Printer.postscriptFile.
printer = Printer.postscriptFile;
//Here's an example of setting the printer to a specific printer.
//printer = "AGFA-SelectSet 5000SF v2013.108";
//If the printer property is the name of a printer, then the ppd property
//is locked (and will return an error if you try to set it).
//ppd = "AGFA-SelectSet5000SF";
//If the printer property is set to Printer.postscript file, the copies
//property is unavailable. Attempting to set it will generate an error.
//copies = 1;
//If the printer property is set to Printer.postscript file, or if the
//selected printer does not support collation, then the collating
//property is unavailable. Attempting to set it will generate an error.
//collating = false; reverseOrder = false;
//pageRange can be either PageRange.allPages or a page range string.
pageRange = PageRange.allPages; printSpreads = false; printMasterPages = false;
//If the printer property is set to Printer.postScript file, then
//the printFile property contains the file path to the output file.
//printFile = "/c/test.ps"; sequence = Sequences.all;
//------------------------------------------------------------------------
//Properties corresponding to the controls in the
//Output panel of the Print dialog box.
第 3 章 ドキュメント ドキュメントのプリント 46
//------------------------------------------------------------------------
//negative = true;
//If a device independent PPD is specified, trying to set the colorOutput
//parameter will result in an error.
try{ colorOutput = ColorOutputModes.separations;
//Note the lowercase "i" in "Builtin" trapping = Trapping.applicationBuiltin; flip = Flip.none;
} catch(myError){}
//If trapping is on, attempting to set the following
//properties will generate an error.
try{ if(trapping == Trapping.off){ printBlack = true; printCyan = true; printMagenta = true; printYellow = true;
}
} catch(myError){}
//Only change the ink angle and frequency when you want to override the
//screening set by the screening specified by the screening property.
//blackAngle = 45;
//blackFrequency = 175;
//cyanAngle = 15;
//cyanFrequency = 175;
//magentaAngle = 75;
//magentaFreqency = 175;
//yellowAngle = 0;
//yellowFrequency = 175;
//The following properties are not needed (because
//colorOutput is set to separations).
//compositeAngle = 45;
//compositeFrequency = 175;
//simulateOverprint = false;
//If trapping is on, setting the following properties will produce an error.
try{ if(trapping == Trapping.off){ printBlankPages = false; printGuidesGrids = false; printNonprinting = false;
}
} catch(myError){}
//------------------------------------------------------------------------
//Properties corresponding to the controls in the
//Setup panel of the Print dialog box.
//-----------------------------------------------------------------------try{ paperSize = PaperSizes.custom;
//Page width and height are ignored if paperSize is not PaperSizes.custom.
//paperHeight = 1200;
//paperWidth = 1200; printPageOrientation = PrintPageOrientation.portrait; pagePosition = PagePositions.centered; paperGap = 0; paperOffset = 0; paperTransverse = false; scaleHeight = 100; scaleWidth = 100; scaleMode = ScaleModes.scaleWidthHeight; scaleProportional = true;
第 3 章 ドキュメント ドキュメントのプリント 47
} catch(myError){}
//If trapping is on, attempting to set the
//following properties will produce an error.
try{ if(trapping == Trapping.off){ textAsBlack = false; thumbnails = false;
//The following properties is not needed because
//thumbnails is set to false.
//thumbnailsPerPage = 4; tile = false;
//The following properties are not needed because tile is set to false.
//tilingOverlap = 12;
//tilingType = TilingTypes.auto;
}
} catch(myError){}
//------------------------------------------------------------------------
//Properties corresponding to the controls in the Marks and Bleed
//panel of the Print dialog box.
//------------------------------------------------------------------------
//Set the following property to true to print all printer's marks.
//allPrinterMarks = true; useDocumentBleedToPrint = false;
//If useDocumentBleedToPrint = false then setting
//any of the bleed properties
//will result in an error.
//Get the bleed amounts from the document's bleed and add a bit.
bleedBottom = app.activeDocument.documentPreferences.
documentBleedBottomOffset+3; bleedTop = app.activeDocument.documentPreferences.documentBleedTopOffset+3; bleedInside = app.activeDocument.documentPreferences.
documentBleedInsideOrLeftOffset+3; bleedOutside = app.activeDocument.documentPreferences.
documentBleedOutsideOrRightOffset+3;
//If any bleed area is greater than zero, then export the bleed marks.
if(bleedBottom == 0 && bleedTop == 0 && bleedInside == 0 && bleedOutside == 0){ bleedMarks = true;
} else{ bleedMarks = false;
} colorBars = true; cropMarks = true; includeSlugToPrint = false; markLineWeight = MarkLineWeight.p125pt
markOffset = 6;
//markType = MarkTypes.default; pageInformationMarks = true; registrationMarks = true;
//------------------------------------------------------------------------
//Properties corresponding to the controls in the
//Graphics panel of the Print dialog box.
//------------------------------------------------------------------------
//If a device independent PPD is specified, trying to set the graphics
//send data will result in an error.
try{ sendImageData = ImageDataTypes.allImageData;
} catch(myError){} fontDownloading = FontDownloading.complete; downloadPPDFOnts = true;
第 3 章 ドキュメント
PDF としてのドキュメントの書き出し 48 try{ dataFormat = DataFormat.binary;
} catch(e){} try{ postScriptLevel = PostScriptLevels.level3;
} catch(e){}
//------------------------------------------------------------------------
//Properties corresponding to the controls in the Color Management
//panel of the Print dialog box.
//------------------------------------------------------------------------
//If the useColorManagement property of app.colorSettings is false,
//attempting to set the following properties will return an error.
try{ sourceSpace = SourceSpaces.useDocument; intent = RenderingIntent.useColorSettings; crd = ColorRenderingDictionary.useDocument; profile = Profile.postscriptCMS;
}
} catch(e){}
//------------------------------------------------------------------------
//Properties corresponding to the controls in the Advanced
//panel of the Print dialog box.
//-----------------------------------------------------------------------opiImageReplacement = false; omitBitmaps = false; omitEPS = false; omitPDF = false;
//The following line assumes that you have a flattener
//preset named "high quality flattener".
try{ flattenerPresetName = "high quality flattener";
} catch(e){} ignoreSpreadOverrides = false;
プリントプリセットを使用したプリント
プリントプリセットを使用してドキュメントをプリントするには、 print
コマンドでプリントプリセットを
指定します。
PDF としてのドキュメントの書き出し
InDesign スクリプティングでは、ページレイアウトドキュメントから PDF ファイルを作成する処理を完全に
制御できます。
PDF の書き出し
次のスクリプトでは、現在の PDF 書き出しオプションを使用して、現在のドキュメントを PDF として書き出
しています (完全なスクリプトについては、ExportPDF を参照してください)。 app.activeDocument.exportFile(ExportFormat.pdfType, File("/c/myTestDocument.pdf"), false);
次のスクリプトでは、PDF 書き出しプリセットを使用して PDF を書き出しています (完全なスクリプトにつ
いては、ExportPDFWithPreset を参照してください)。
第 3 章 ドキュメント
PDF としてのドキュメントの書き出し 49 var myPDFExportPreset = app.pdfExportPresets.item("prepress"); app.activeDocument.exportFile(ExportFormat.pdfType, File("/c/myTestDocument.pdf"), false, myPDFExportPreset);
PDF 書き出しオプションの設定
次のスクリプトでは、PDF 書き出しオプションを設定してから、書き出しを行っています (完全なスクリプ
トについては、ExportPDFWithOptions を参照してください)。 with(app.pdfExportPreferences){
//Basic PDF output options.
pageRange = PageRange.allPages; acrobatCompatibility = AcrobatCompatibility.acrobat6; exportGuidesAndGrids = false; exportLayers = false; exportNonPrintingObjects = false; exportReaderSpreads = false; generateThumbnails = false; try{ ignoreSpreadOverrides = false;
} catch(e){} includeBookmarks = true; includeHyperlinks = true; includeICCProfiles = true; includeSlugWithPDF = false; includeStructure = false; interactiveElementsOption = InteractiveElementsOptions.doNotInclude;
//Setting subsetFontsBelow to zero disallows font subsetting;
//set subsetFontsBelow to some other value to use font subsetting.
subsetFontsBelow = 0;
//
//Bitmap compression/sampling/quality options.
colorBitmapCompression = BitmapCompression.zip; colorBitmapQuality = CompressionQuality.eightBit; colorBitmapSampling = Sampling.none;
//thresholdToCompressColor is not needed in this example.
//colorBitmapSamplingDPI is not needed when colorBitmapSampling
//is set to none.
grayscaleBitmapCompression = BitmapCompression.zip; grayscaleBitmapQuality = CompressionQuality.eightBit; grayscaleBitmapSampling = Sampling.none;
//thresholdToCompressGray is not needed in this example.
//grayscaleBitmapSamplingDPI is not needed when grayscaleBitmapSampling
//is set to none.
monochromeBitmapCompression = BitmapCompression.zip; monochromeBitmapSampling = Sampling.none;
//thresholdToCompressMonochrome is not needed in this example.
//monochromeBitmapSamplingDPI is not needed when
//monochromeBitmapSampling is set to none.
//
//Other compression options.
compressionType = PDFCompressionType.compressNone; compressTextAndLineArt = true; cropImagesToFrames = true; optimizePDF = true;
//
//Printers marks and prepress options.
//Get the bleed amounts from the document's bleed.
bleedBottom = app.activeDocument.documentPreferences.
documentBleedBottomOffset; bleedTop = app.activeDocument.documentPreferences.documentBleedTopOffset; bleedInside = app.activeDocument.documentPreferences.
documentBleedInsideOrLeftOffset;
第 3 章 ドキュメント
PDF としてのドキュメントの書き出し 50 bleedOutside = app.activeDocument.documentPreferences.
documentBleedOutsideOrRightOffset;
//If any bleed area is greater than zero, then export the bleed marks.
if(bleedBottom == 0 && bleedTop == 0 && bleedInside == 0 && bleedOutside == 0){ bleedMarks = true;
} else{ bleedMarks = false;
} colorBars = true; colorTileSize = 128; grayTileSize = 128; cropMarks = true; omitBitmaps = false; omitEPS = false; omitPDF = false; pageInformationMarks = true; pageMarksOffset = 12; pdfColorSpace = PDFColorSpace.unchangedColorSpace;
//Default mark type.
pdfMarkType = 1147563124; printerMarkWeight = PDFMarkWeight.p125pt; registrationMarks = true; try{ simulateOverprint = false;
} catch(e){} useDocumentBleedWithPDF = true;
//Set viewPDF to true to open the PDF in Acrobat or Adobe Reader.
viewPDF = false;
}
//Now export the document. You'll have to fill in your own file path.
app.activeDocument.exportFile(ExportFormat.pdfType, File("/c/myTestDocument.pdf"), false);
グレースケール PDF の書き出し
カラーを含む InDesign ドキュメントは、カラー PDF またはグレースケール PDF に書き出すことができます。
前述の
節のスクリプトを変更し、グレースケールでの書き出
しを行うには、
PDFColorSpace
オプションを、 unchangedColorSpace
から gray に変更します。
す。 with(app.pdfExportPreferences)
{ pdfColorSpace = PDFColorSpace.GRAY;
}
(カラーが含まれている小さいドキュメントを作成し、グレースケールで PDF に書き出す他のスクリプトに
ついては、GreyscalePDFforIDS を参照してください)。
ページ範囲の PDF 書き出し
指定したページ範囲を PDF として書き出す方法を、次のスクリプトに示します (完全なスクリプトについて
は、ExportPageRangeAsPDF を参照してください)。
第 3 章 ドキュメント
PDF としてのドキュメントの書き出し 51 with(app.pdfExportPreferences){
//pageRange can be either PageRange.allPages or a page range string
//(just as you would enter it in the Print or Export PDF dialog box).
pageRange = "1, 3-6, 7, 9-11, 12";
} var myPDFExportPreset = app.pdfExportPresets.item("prepress") app.activeDocument.exportFile(ExportFormat.pdfType, File("/c/myTestDocument.pdf"), false, myPDFExportPreset);
ページごとの PDF 書き出し
次のスクリプトでは、ドキュメントの各ページを個別の PDF ファイルとして書き出しています (完全なスク
リプトについては、ExportEachPageAsPDF を参照してください)。
//Display a "choose folder" dialog box.
if(app.documents.length != 0){ var myFolder = Folder.selectDialog ("Choose a Folder"); if(myFolder != null){ myExportPages(myFolder);
}
} else{ alert("Please open a document and try again.");
} function myExportPages(myFolder){ var myPageName, myFilePath, myFile; var myDocument = app.activeDocument; var myDocumentName = myDocument.name; var myDialog = app.dialogs.add(); with(myDialog.dialogColumns.add().dialogRows.add()){ staticTexts.add({staticLabel:"Base name:"}); var myBaseNameField = textEditboxes.add({editContents:myDocumentName, minWidth:160});
} var myResult = myDialog.show({name:"ExportPages"}); if(myResult == true){ var myBaseName = myBaseNameField.editContents;
//Remove the dialog box from memory.
myDialog.destroy(); for(var myCounter = 0; myCounter < myDocument.pages.length; myCounter++){ myPageName = myDocument.pages.item(myCounter).name; app.pdfExportPreferences.pageRange = myPageName;
//The name of the exported files will be the base name + the
//page name + ".pdf".
//If the page name contains a colon (as it will if the
//document contains sections),
//then remove the colon.
var myRegExp = new RegExp(":","gi"); myPageName = myPageName.replace(myRegExp, "_"); myFilePath = myFolder + "/" + myBaseName + "_" + myPageName + ".pdf"; myFile = new File(myFilePath); myDocument.exportFile(ExportFormat.pdfType, myFile, false);
}
} else{ myDialog.destroy();
}
}
第 3 章 ドキュメント
PDF としてのドキュメントの書き出し 52
インタラクティブ機能を使用した PDF の書き出し
次のスクリプトは、インタラクティブ機能を使用したドキュメントを PDF として書き出します (完全なスク
リプトについては、ExportInteractivePDF を参照してください)。
//Given a document "myDocument," add page transitions...
for(var myCounter = 0; myCounter < myDocument.spreads.length; myCounter++){ myDocument.spreads.item(myCounter).pageTransitionType
PageTransitionTypeOptions.wipeTransition; myDocument.spreads.item(myCounter).pageTransitionDirection =
PageTransitionDirectionOptions.down; myDocument.spreads.item(myCounter).pageTransitionDuration =
PageTransitionDurationOptions.medium;
} app.interactivePDFExportPreferences.flipPages = true; app.interactivePDFExportPreferences.flipPagesSpeed = 5; app.interactivePDFExportPreferences.openInFullScreen = true; app.interactivePDFExportPreferences.interactivePDFInteractiveElementsOption =
InteractivePDFInteractiveElementsOptions.includeAllMedia;
//Export the document to PDF.
myDocument.exportFile(ExportFormat.interactivePDF,File(Folder.desktop + "/InteractivePDF.pdf"), false);
PDF フォームとしての書き出し
フォームフィールドを含む PDF を作成するには、PDF として保存した InDesign ドキュメントを Acrobat で開
いてフォームフィールドを適用するか、テキストフィールド、ラジオボタン、署名フィールドなどを直接
InDesign 上で適用し、Acrobat での編集作業を必要としない状態で PDF にフォームとして書き出します。
次のスクリプトでは、フォーム要素を InDesign ドキュメントに適用し、ドキュメントを PDF フォームとして
書き出しています (完全なスクリプトについては、ExportInteractivePDFForm を参照してください)。 var myTextFrame = myDocument.pages.item(0).textFrames.add
(
{geometricBounds:[15, 15, 20, 35], contents:"FirstName: "}
);
//Create a textbox as firstname input box var myTextBox = myDocument.pages.item(0).textBoxes.add
(
{geometricBounds:[15, 40, 20, 75], contents:SpecialCharacters.autoPageNumber}
);
//Create another textframe as lastname label var myTextFrame1 = myDocument.pages.item(0).textFrames.add
(
{geometricBounds:[30, 15, 25, 35], contents:"LastName: "}
);
//Create another textbox as lastname input box var myTextBox = myDocument.pages.item(0).textBoxes.add
(
{geometricBounds:[30, 40, 25, 75], contents:SpecialCharacters.autoPageNumber}
);
//Create a TextFrame to introduce the following checkbox
var myTextFrame2 = myDocument.pages.item(0).textFrames.add
(
{geometricBounds:[15, 80, 20, 95], contents:"Hobby: "}
);
//Create some CheckBoxes
var myCheckBox = myDocument.pages.item(0).checkBoxes.add
(
{geometricBounds:[15, 100, 20, 105], name:"Football "}
);
var myTextFrame3 = myDocument.pages.item(0).textFrames.add
第 3 章 ドキュメント
PDF としてのドキュメントの書き出し 53
(
{geometricBounds:[15, 107, 20, 125], contents:"Football "}
);
var myCheckBox1 = myDocument.pages.item(0).checkBoxes.add
(
{geometricBounds:[15, 130, 20, 135], name:"Basketball "}
);
var myTextFrame4 = myDocument.pages.item(0).textFrames.add
(
{geometricBounds:[15, 137, 20, 160], contents:"Basketball "}
);
var myCheckBox2 = myDocument.pages.item(0).checkBoxes.add
(
{geometricBounds:[15, 165, 20, 170], name:"Pingpong "}
);
var myTextFrame5 = myDocument.pages.item(0).textFrames.add
(
{geometricBounds:[15, 172, 20, 193], contents:"Pingpong "}
);
//Create a button for submit var submitButton = myDocument.pages.item(0).buttons.add
(
{geometricBounds:[45, 15, 35, 35], name:"Submit"}
);
//Fill contents to the button var myRightArrow1 = submitButton.states.item(0).polygons.add
(
{fillColor:myDocument.colors.item("Green")}
); myRightArrow1.paths.item(0).entirePath = [[15, 35],[35,40],[15, 45]];
//Add the Rollover state.
var myRolloverState1 = submitButton.states.add();
//Add a shadow to the polygon in the Rollover state.
var myRolloverArrow1 = myRolloverState1.polygons.add
(
{fillColor:myDocument.colors.item("Green")}
); myRolloverArrow1.paths.item(0).entirePath = [[15, 35],[35,40],[15, 45]]; var myFillTransparencySettings1 = myRolloverArrow1.fillTransparencySettings; myFillTransparencySettings1.dropShadowSettings.mode = ShadowMode.drop; myFillTransparencySettings1.dropShadowSettings.angle = 90; myFillTransparencySettings1.dropShadowSettings.xOffset = 0; myFillTransparencySettings1.dropShadowSettings.yOffset = 0; myFillTransparencySettings1.dropShadowSettings.size = 6;
//Add a shadow to the polygon in the Click state.
var myClickState1 = submitButton.states.add(); var myClickArrow1 = myClickState1.polygons.add
(
{fillColor:myDocument.colors.item("Blue")}
); myClickArrow1.paths.item(0).entirePath = [[15, 35],[35,40],[15,45]];
//Set the behavior for the button.
var SubmitForm = submitButton.submitFormBehaviors.add
(
{behaviorEvent:BehaviorEvents.mouseUp}
);
//Create a button for print var printButton = myDocument.pages.item(0).buttons.add
(
{geometricBounds:[45, 40, 35, 60], content:"Print"}
);
//Fill contents to the button
第 3 章 ドキュメント
EPS としてのページの書き出し 54 var myRightArrow2 = printButton.states.item(0).polygons.add
(
{fillColor:myDocument.colors.item("Red")}
); myRightArrow2.paths.item(0).entirePath = [[40, 35],[60,40],[40, 45]];
//Add the Rollover state.
var myRolloverState2 = printButton.states.add();
//Add a shadow to the polygon in the Rollover state.
var myRolloverArrow2 = myRolloverState2.polygons.add
(
{fillColor:myDocument.colors.item("Red")}
); myRolloverArrow2.paths.item(0).entirePath = [[40, 35],[60,40],[40, 45]]; var myFillTransparencySettings2 = myRolloverArrow2.fillTransparencySettings; myFillTransparencySettings2.dropShadowSettings.mode = ShadowMode.drop; myFillTransparencySettings2.dropShadowSettings.angle = 90; myFillTransparencySettings2.dropShadowSettings.xOffset = 0; myFillTransparencySettings2.dropShadowSettings.yOffset = 0; myFillTransparencySettings2.dropShadowSettings.size = 6;
//Add a shadow to the polygon in the Click state.
var myClickState2 = printButton.states.add(); var myClickArrow2 = myClickState2.polygons.add
(
{fillColor:myDocument.colors.item("Blue")}
); myClickArrow2.paths.item(0).entirePath = [[40, 35],[60,40],[40,45]];
//Set the behavior for the button.
var PrintForm = printButton.printFormBehaviors.add
(
{behaviorEvent:BehaviorEvents.mouseUp}
);
//Export the document to interactive PDF.
myDocument.exportFile(ExportFormat.interactivePDF,File(Folder.desktop + "/SubmitForm.pdf"), false)
EPS としてのページの書き出し
ドキュメントを EPS として書き出すと、ファイルの各ページが個別の EPS グラフィックとして保存されます
(1 つの EPS には 1 ページしか書き出せないようになっています)。 複数のページを書き出した場合、ファイル
名にはページのインデックスが付加されます。 ドキュメント内のページのインデックスが、ページの名前に
なるとは限りません(ページが含まれているセクションのセクションオプションによって定義されます)。
すべてのページの EPS 書き出し
次のスクリプトでは、アクティブなドキュメントのページが、1 つまたは複数の EPS ファイルに書き出され
ます (完全なスクリプトについては、ExportAsEPS を参照してください)。 var myFile = new File("/c/myTestFile.eps"); app.activeDocument.exportFile(ExportFormat.epsType, myFile, false);
ページ範囲の EPS 書き出し
EPS として書き出すページを制御するには、書き出しを行う前に、EPS export preferences の page range
プロ
パティに、書き出すページのページ範囲を示す文字列を指定します (完全なスクリプトについては、
第 3 章 ドキュメント
EPS としてのページの書き出し 55
//Enter the name of the page you want to export in the following line.
//Note that the page name is not necessarily the index of the page in the
//document (e.g., the first page of a document whose page numbering starts
//with page 21 will be "21", not 1).
app.epsExportPreferences.pageRange = "1-3, 6, 9"; var myFile = new File("/c/myTestFile.eps"); app.activeDocument.exportFile(ExportFormat.epsType, myFile, false);
ファイル名を指定した EPS 書き出し
次のスクリプトでは、前述の例と比べてファイル名を細かく制御しながら各ページを EPS として書き出して
います (完全なスクリプトについては、ExportEachPageAsEPS を参照してください)。
//Display a "choose folder" dialog box.
if(app.documents.length != 0){ var myFolder = Folder.selectDialog ("Choose a Folder"); if(myFolder != null){ myExportPages(myFolder);
}
} else{ alert("Please open a document and try again.");
} function myExportPages(myFolder){ var myFilePath, myPageName, myFile; var myDocument = app.activeDocument; var myDocumentName = myDocument.name; var myDialog = app.dialogs.add({name:"ExportPages"}); with(myDialog.dialogColumns.add().dialogRows.add()){ staticTexts.add({staticLabel:"Base name:"}); var myBaseNameField = textEditboxes.add({editContents:myDocumentName, minWidth:160});
} var myResult = myDialog.show(); if(myResult == true){
//The name of the exported files will be the base name +
//the page name + ".eps".
var myBaseName = myBaseNameField.editContents;
//Remove the dialog box from memory.
myDialog.destroy();
//Generate a file path from the folder name, the base document name,
//page name.
for(var myCounter = 0; myCounter < myDocument.pages.length; myCounter++){ myPageName = myDocument.pages.item(myCounter).name; app.epsExportPreferences.pageRange = myPageName;
//The name of the exported files will be the base name +
//the page name + ".eps".
//If the page name contains a colon (as it will if the
//document contains sections),
//then remove the colon.
var myRegExp = new RegExp(":","gi"); myPageName = myPageName.replace(myRegExp, "_"); myFilePath = myFolder + "/" + myBaseName + "_" + myPageName + ".eps"; myFile = new File(myFilePath); app.activeDocument.exportFile(ExportFormat.epsType, myFile, false);
}
} else{ myDialog.destroy();
}
}
第 3 章 ドキュメント
EPub の書き出し 56
EPub の書き出し
InDesign スクリプティングでは、ページレイアウトドキュメントから EPub ファイルを作成する処理を完全に
制御できます。
現在のドキュメントの書き出し
次のスクリプトでは、デフォルトのオプションを使用して、現在のドキュメントを EPub として書き出して
います (完全なスクリプトについては、ExportEPub を参照してください)。 var myDocument = app.documents.item(0); myDocument.exportFile(ExportFormat.EPUB, File("C:/test/ExportEPub.epub"), false);
EPub ファイルの作成をユーザーがさらに細かく制御できるようにするには、3 番目のパラメーターに true を
指定します。 これにより、EPub 書き出しオプションダイアログボックスが表示されます。
EPub 書き出しオプションの設定
次のスクリプトでは、EPub 書き出しオプションを設定してから、書き出しを行っています (完全なスクリ
プトについては、ExportEPubWithOptions を参照してください)。
//Sets EPub export options, then exports the active document as EPub.
with (myDocument.epubExportPreferences)
{
//Apply image alignment to anchored object settings.
applyImageAlignmentToAnchoredObjectSettings = false;
//The unit of space.
spaceUnit = SpaceUnitType.CSS_EM;
//The unit of margin.
marginUnit = SpaceUnitType.CSS_EM;
//Bottom margin of the epub.
bottomMargin = 5;
//Left margin of the epub.
leftMargin = 5;
//Right margin of the epub.
rightMargin = 5;
//Top margin of the epub.
topMargin = 5;
//If true, break InDesign document into smaller pieces when generating epub.
breakDocument = false;
//The name of paragraph style to break InDesign document.
//paragraphStyleName = "";
//The bullet export option.
bulletExportOption = BulletListExportOption.AS_TEXT; cssExportOption = StyleSheetExportOption.EMBEDDED_CSS; customImageSizeOption = ImageSizeOption.SIZE_RELATIVE_TO_PAGE_WIDTH; embedFont = true; epubCover = EpubCover.FIRST_PAGE;
//This will take effect only when epubCover is set to EXTERNAL_IMAGE.
//coverImageFile = "/c/cover.jpg"; epubPublisher = "Adobe Devtech";
//The export order.
exportorder = ExportOrder.LAYOUT_ORDER;
第 3 章 ドキュメント
EPub の書き出し 57
//If true, output footnote immediately after its paragraph.
footnoteFollowParagraph = false;
//If true, export epub in XHTML format. Otherwise, in DTBook format.
format = true; gifOptionsInterlaced = true; gifOptionsPalette = GIFOptionsPalette.WINDOWS_PALETTE;
//The epub unique identifier, like ISBN.
id = "123";
//Ignore object level image conversion settings.
ignoreObjectConversionSettings = true;
//Alignment applied to images.
imageAlignment = ImageAlignmentType.ALIGN_CENTER;
//The file format to use for converted images.
//Valid only when copy optimized images and/or copy formatted images is true.
imageConversion = ImageConversion.AUTOMATIC; imageExportResolution = ImageResolution.PPI_150;
//Image page break settings to be used with objects.
imagePageBreak = ImagePageBreakType.PAGE_BREAK_AFTER;
//Space After applied to images.
imageSpaceAfter = 2;
//Space Before applied to images.
imageSpaceBefore = 2;
//If true, include CSS definition.
includeCSSDefinition = true;
//If true, output document metadata into epub.
includeDocumentMetadata = true; jpegOptionsFormat = JPEGOptionsFormat.BASELINE_ENCODING; jpegOptionsQuality = JPEGOptionsQuality.HIGH;
//The PNG compression level.
level = 5; numberedListExportOption = NumberedListExportOption.AS_TEXT;
//If true, format image based on layout appearence.
preserveLayoutAppearence = true;
//If true, output local style override.
preserveLocalOverride = true; stripSoftReturn = true;
//If true, image page break settings will be used in objects.
useImagePageBreak = true;
//Use InDesign TOC style to generate epub TOC.
useTocStyle = true; viewDocumentAfterExport = false;
} myDocument.exportFile(ExportFormat.EPUB, File("C:/test/ExportEPubWithOptions.epub"), false);
4
レイヤーの操作
CS6
章の更新ステータス
変更なし
InDesign のレイヤーは、レイアウト内のオブジェクトの重なり順を制御する上で重要な役割を果たします。
レイヤーは、互いに上へと重ね合わせられている複数枚の透明な水平面と考えることができます。 また、同
じ種類のコンテンツを特定のレイヤーや一連のレイヤーに配置して、レイヤーを構成用のツールとして使用
することもできます。
ドキュメントには 1 つ以上のレイヤーを含めることができますが、各ドキュメントには少なくとも 1 つのレ
イヤーが含まれます。 レイヤーはドキュメントと同じ幅で、特定のページやスプレッドに関連付けられるこ
とはありません。
この章では、InDesign レイアウトのレイヤーに関連するスクリプティングテクニックと、レイヤーに関する
一般的な操作について説明します。
レイヤーオブジェクトモデルについて
次の図に、レイヤーオブジェクトモデルを示します。 図を参照するにあたって、次の点に注意してください。
図は、ドキュメントのオブジェクト階層におけるレイヤーの位置と内容に焦点を合わせています。スク
リプトでレイヤーの中身を操作するその他の方法についてすべてを図式化しようとしていません(例え
ば、レイヤーオブジェクト内にテキストフレームオブジェクトがあることがわかりますが、ストーリー
やテキストオブジェクト、ページ、スプレッドからもテキストフレームオブジェクトへの参照を取得す
ることができます)。
オブジェクト名は JavaScript 形式のものですが、オブジェクト階層はすべてのスクリプト言語で同じで
す。
左側の列にレイヤーの基本的なプロパティを、右側にレイヤーオブジェクトに含めることができるオブ
ジェクトを示しています。
重要な点として、ページアイテムのコレクションと allPageItems
のコレクションの違いに注意してくださ
ションです。 例えば、ページアイテムがグループに含まれている場合、 pageItems
のコレクションにこのペー
ジアイテムは現れません。 これに対し、 allPageItems
のコレクションは、レイヤーに割り当てられたすべて
のページアイテムが統合されたコレクションです。オブジェクト階層における位置は関係ありません。 レイ
ヤー上のグループに含まれるページアイテムは、 allPageItems
のコレクションには現れます。
同様に、 allGraphics
プロパティには、オブジェクト階層における位置にかかわらず、レイヤーに割り当て
られたページアイテムに含まれているすべてのグラフィックが含まれます。
58
第 4 章 レイヤーの操作 レイヤーのスクリプト操作 59
レイヤーのスクリプト操作
InDesign のユーザーインターフェイスでは、レイヤーパネルを使用して、レイヤーの追加、削除、並べ替え、
複製、結合を行います。 また、レイヤーパネルのレイヤープロキシをドラッグ&ドロップして、選択してい
るページアイテムを割り当てるレイヤーを変更することもできます (オブジェクトをレイヤーに割り当てる
方法について詳しくは、InDesign ヘルプを参照してください)。 ここでは、InDesign スクリプティングでこれ
らの操作を実行する方法について説明します。
レイヤーの作成
新規レイヤーを作成する方法を、次のスクリプトに示します (完全なスクリプトについては、AddLayer を参
照してください)。
//Given a document "myDocument"...
var myLayer = myDocument.layers.add();
新規レイヤーを作成した場合、ドキュメント内のすべてのレイヤーの一番上に配置されます。
第 4 章 レイヤーの操作
レイヤーの参照
レイヤーのスクリプト操作 60
ヤーを参照する一般的な方法について説明します。
アクティブなレイヤーの取得
アクティブなレイヤーとは、新しいオブジェクトが作成されるレイヤーです。 スクリプトを使用してアク
ティブなレイヤーを取得できます。次のスクリプトにその例を示します (完全なスクリプトについては、
//Given a document "myDocument"...
var myDocument = app.documents.item(0); var myLayer = myDocument.activeLayer;
レイヤーインデックスによるレイヤーの参照
ドキュメントのレイヤーコレクションに含まれるレイヤーのインデックスを使用して、レイヤーへの参照を
取得できます。 レイヤーのインデックスを使用して、レイヤーに対して繰り返し処理を行う方法を、次のス
クリプトに示します (完全なスクリプトについては、HideOtherLayers を参照してください)。
//Given a document "myDocument"...
var myTargetLayer = myDocument.activeLayer; for(var myCounter = 0; myCounter < myDocument.layers.length; myCounter++){
//If the layer is not the target layer, hide it.
if(myDocument.layers.item(myCounter).name != myTargetLayer.name){ myDocument.layers.item(myCounter).visible = false;
}
}
ドキュメントのレイヤーコレクションに含まれるレイヤーを参照するときには、負の数も使用できます。 レ
イヤー -1 は、コレクション内の最後(一番下)のレイヤーを参照します。
レイヤー名によるレイヤーの参照
レイヤーの名前を使用してレイヤーへの参照を取得することもできます。次のスクリプトにその例を示しま
す (完全なスクリプトについては、LayerName を参照してください)。 var myLayer = app.documents.item(0).layers.item("Text Layer");
相対参照の使用
あるレイヤーを基準として、 previousItem
メソッドを使用してその上のレイヤーを参照したり、 nextItem
メ
ソッドを使用してその下のレイヤーを参照したりできます。次のスクリプトにその例を示します (完全なス
クリプトについては、RelativeLayerReferences を参照してください)。 いずれのメソッドも、参照レイヤーをパ
ラメーターで指定します。
//Given a document "myDocument"...
var myLayer = myDocument.layers.item(4); myDocument.activeLayer = myLayer; var myNextLayer = myDocument.layers.nextItem(myLayer); var myPreviousLayer = myDocument.layers.previousItem(myLayer); var myString = "The layer below the target layer is " + myNextLayer.name + "¥r"; myString += "The layer above the target layer is " + myPreviousLayer.name; alert(myString);
第 4 章 レイヤーの操作 レイヤーのスクリプト操作 61 previousItem
および nextItem
メソッドで、指定したレイヤー(次または前のレイヤー)が存在しなかった
場合、無効なレイヤーの参照が返されます。エラーは発生しません。
範囲内のレイヤーの参照
一連のレイヤーを参照するには、 itemByRange
後、範囲内のすべてのレイヤーのプロパティを設定する方法を、次のスクリプトに示します (完全なスクリ
プトについては、HideLayersAbove を参照してください)。
//Given a document "myDocument"...
var myLayer = myDocument.layers.item(4); myDocument.activeLayer = myLayer;
//Now hide all of the layers above the current layer.
var myLayers = myDocument.layers.itemByRange(0, myLayer.index -1);
//Even though the result contains multiple layers, you can
//set a property on all of the layers without iterating.
myLayers.visible = false;
レイヤーの削除
特定のドキュメントからレイヤーを削除するには、remove メソッドを使用します。次のスクリプトにその例
を示します (完全なスクリプトについては、DeleteLayer を参照してください)。 ドキュメント内の最後に
残ったレイヤーは削除できません。
//Given a document "myDocument" containing a layer named "Delete This Layer"...
var myLayer = myDocument.layers.item("Delete This Layer"); myLayer.remove();
レイヤーの移動
ドキュメント内のレイヤーの重なり順を変更するには、 move
メソッドを使用します。次のスクリプトにその
例を示します (完全なスクリプトについては、MoveLayer を参照してください)。
//Given a document "myDocument" containing at least two layers...
var myLayerA = myDocument.layers.item(0); var myLayerB = myDocument.layers.item(1); myLayerA.move(LocationOptions.AFTER, myLayerB);
レイヤーの複製
レイヤーのコピーを作成するには、 duplicate
メソッドを使用します。次のスクリプトにその例を示します
(完全なスクリプトについては、DuplicateLayer を参照してください)。
//Given a layer "myLayer"...
ar myNewLayer = myLayer.duplicate();
レイヤーの結合
2 つ以上のレイヤーを、レイヤーに割り当てられているページアイテムも含めて 1 つのレイヤーに結合する
方法を、次のスクリプトに示します (完全なスクリプトについては、MergeLayers を参照してください)。
//Given the layers "myLayer1" and "myLayer2"...
myLayer1.merge(myLayer2);
第 4 章 レイヤーの操作 レイヤーのスクリプト操作 62
レイヤーへのページアイテムの割り当て
レイヤーにページアイテムを割り当てるには、ページアイテムを作成するときにレイヤーを参照するか(す
べてのページアイテムの add
メソッドは、レイヤーをパラメーターで指定できます)
の itemLayer
プロパティを設定します。
次のスクリプトに示します (完全なスクリプトについては、AssignPageItemsToLayers を参照してください)。
//Given a reference to a page "myPage," and a document "myDocument,"
//create a text frame on a layer named "TextFrames" var myTextFrame = myPage.textFrames.add(myDocument.layers.item("TextFrames")); myTextFrame.geometricBounds = [72, 72, 144, 144];
//Create a rectangle on the current target layer.
var myRectangle = myPage.rectangles.add({geometricBounds:[72, 144, 144, 216]});
//Move the rectangle to a specific layer.
myRectangle.itemLayer = myDocument.layers.item("Rectangles");
//Create a series of ovals.
for(var myCounter = 72; myCounter < 172; myCounter+=10){ myPage.ovals.add({geometricBounds:[216, myCounter, 226, myCounter+10]});
}
//Move all of the ovals on the page to a specific layer.
myPage.ovals.everyItem().itemLayer = myDocument.layers.item("Ovals");
レイヤーのプロパティの設定
レイヤーのプロパティは、レイヤーのレイヤー名、カラー、表示/非表示などの属性を制御します。 ここで
は、レイヤーのプロパティを操作する方法について説明します。
レイヤーの基本的なプロパティの設定
レイヤーの基本的なプロパティには、レイヤーの名前、レイヤーのハイライトカラー、レイヤーの表示/非
表示、レイヤー上のテキストオブジェクトがテキストの回り込み設定を無視するかどうかの設定などがあり
ます。 これらの基本的なレイヤーのプロパティを設定する方法を、次のスクリプトに示します (完全なスク
リプトについては、BasicLayerProperties を参照してください)。
//Given a document "myDocument"...
var myLayer = myDocument.layers.add(); myLayer.name = "myLayer"; myLayer.layerColor = UIColors.CHARCOAL; myLayer.ignoreWrap = false; myLayer.visible = true;
レイヤーガイドの操作
ページアイテムと同じように、特定のレイヤーにガイドを割り当てることができます。 レイヤーのガイドは、
表示/非表示を選択でき、さらにロックをかけたり解除したりすることもできます。 レイヤーのガイドを操
作する方法を、次のスクリプトに示します (完全なスクリプトについては、LayerGuides を参照してくださ
//Given a document "myDocument" and a page "myPage" containing at least one guide...
//Create a new layer.
var myLayer = myDocument.layers.add();
//Move all of the guides on the page to the new layer.
myPage.guides.everyItem().itemLayer = myLayer; myLayer.lockGuides = true; myLayer.showGuides = true;
第 4 章 レイヤーの操作 レイヤーのスクリプト操作 63
レイヤーのプリントと表示/非表示の制御
レイヤー上のオブジェクトのプリントと表示/非表示を制御できます。次のスクリプトにその例を示します
(完全なスクリプトについては、LayerControl を参照してください)。
//Given a document "myDocument" containing layers named "Background,"
//"Language A,", "Language B," and "Language C," export the "Background"
//layer and each "Language" layer to PDF as separate PDF files...
var myVersion, myLanguageCounter, myFileName; var myFolder = Folder.desktop; for(var myCounter = 0; myCounter < 3; myCounter ++){ switch(myCounter){ case 0: myVersion = "Language A"; break; case 1: myVersion = "Language B"; break; case 2: myVersion = "Language C"; break;
} for(myLanguageCounter = 0; myLanguageCounter < myDocument.layers.length; myLanguageCounter ++){ if((myDocument.layers.item(myLanguageCounter).name == myVersion)||
(myDocument.layers.item(myLanguageCounter).name == "Background")){ myDocument.layers.item(myLanguageCounter).visible = true; myDocument.layers.item(myLanguageCounter).printable = true;
} else{ myDocument.layers.item(myLanguageCounter).visible = false; myDocument.layers.item(myLanguageCounter).printable = false;
}
} myFileName = myFolder + "/" + myVersion + ".pdf"; myDocument.exportFile(ExportFormat.pdfType, File(myFileName));
}
レイヤーのロック
レイヤーにはロックをかけることができます。ロックをかけると、レイヤー上のページアイテムは編集でき
なくなります。 レイヤーのロックをかける方法と解除する方法を、次のスクリプトに示します (完全なスク
リプトについては、LockLayersBelow を参照してください)。
//Given a document "myDocument"...
var myTargetLayer = myDocument.activeLayer; var myLayers = myDocument.layers.itemByRange(myDocument.layers.length-1, myTargetLayer.index +1); myLayers.locked = true;
5
ページアイテムの操作
CS6
章の更新ステータス
変更なし
この章では、InDesign レイアウトに表示されるページアイテム(長方形、楕円形、グラフィックの線、多角
形、テキストフレーム、ボタン、グループなど)に関連するスクリプティングテクニックを紹介します。
この章の内容は、次のとおりです。
ページアイテムの作成
ページアイテムの形状
パスとパスポイントの操作
グループの作成
ページアイテムの複製と移動
ページアイテムの変形
アーティクルの使用
ページアイテムの作成
InDesign レイアウトのページアイテムは階層的に配置され、なんらかのコンテナオブジェクト内に表示され
ます。 例えば、スプレッド、ページ、その他のページアイテム、グループおよびテキスト文字はすべて、
ページアイテムを格納できるコンテナオブジェクトです。 InDesign スクリプトオブジェクトモデルにあるコ
ンテナのこの階層は、InDesign のユーザーインターフェイスの階層と同じです。つまり、あるページ上で長
方形ツールをドラッグして長方形を作成する操作は、そのページが、作成する長方形のコンテナ(親)にな
るよう指定していることになります。 楕円形を多角形の中に貼り付ける操作は、多角形が楕円形の親になる
よう指定していることになります。多角形は親でもありますが、その親であるページにとっては子オブジェ
クトとなります。
MakeRectangle スクリプトに示すように、一般に、新しいページアイテムの作成は簡単です。ページアイテ
ムを作成するには、そのページアイテムを格納するオブジェクトを指定します。
//Given a page "myPage", create a new rectangle at the default size and location...
var myRectangle = myPage.rectangles.add();
前述のスクリプトでは、新規ドキュメントの最初のページに新しい長方形が作成されます。 この長方形は、
デフォルトの位置(ページの左上隅付近)に、デフォルトのサイズ(1 辺が約 10 ポイントの正方形)で表示
されます。 MakeRectangleWithProperties スクリプトに示すように、長方形の移動や大きさの変更は、いずれ
もその境界線のプロパティに新しい値を指定することで実行されます。
//Given a page "myPage", create a new rectangle and specify its size and location...
var myRectangle = myPage.rectangles.add({geometricBounds:[72, 72, 144, 144]});
ページアイテムの種類
「汎用的な」ページアイテムは作成できない点に注意することが重要です。特定の種類(長方形、楕円形、グ
ラフィックの線、多角形、テキストフレームまたはボタン)のページアイテムを作成する必要があります。
64
第 5 章 ページアイテムの操作 ページアイテムの作成 65
ページアイテムの種類は、そのページアイテムの形状を変更したときにも、変化することに注意してくださ
は多角形に変化します。 パスを開いて、4 つのパスポイントの 2 つを削除すると、ページアイテムの種類はグ
ラフィックの線に変化します。 長方形、楕円形、グラフィックの線、多角形などの種類は、次の要素のみで
定義されます。
オブジェクトにあるパスの数。 複数のパスがあるページアイテムは多角形です。
オブジェクトの最初のパスにあるポイントの数と位置。
ページアイテムの種類を判断するには、次の例を使用します。 var myPageItemType = myPageItem.constructor.name;
前述の結果は、ページアイテムの種類を表す文字列になります。
ページアイテムの種類の取得
汎用的なページアイテムへの参照があるときに、そのページアイテムの種類を確認する場合は、 constructor.name を使用して特定の種類を取得します。
//Given a generic page item "myPageItem"...
var myType = myPageItem.constructor.name; alert(myType);
ページアイテムの参照
特定のコンテナ(ドキュメント、レイヤー、ページ、スプレッド、グループ、テキストフレーム、ページア
イテムなど)の内部にあるページアイテムを参照する場合は、コンテナオブジェクトの pageItems
コレク
ションを使用します。 これによって、オブジェクトの内部にある最上レベルのページアイテムのコレクショ
ンを参照できます。 次に例を示します。 var myPageItems = app.documents.item(0).pages.item(0).pageItems;
結果のコレクション( myPageItems
)に含まれないものとしては、グループ内部のオブジェクト(コレク
ションにグループが格納されている場合)、他のページアイテムの内部にあるオブジェクト(コレクションに
親ページアイテムが格納されている場合)またはテキストフレーム内のページアイテムがあります。 他の
ページアイテムの内部にネストされているアイテムなど、所定のコンテナにあるすべてのアイテムについて
参照を取得するには、 allPageItems
プロパティを使用します。 var myAllPageItems = app.documents.item(0).pages.item(0).pageItems;
結果のコレクション( myAllPageItems
)には、階層内の位置に関係なく、ページ上のすべてのオブジェクト
が含まれます。
ページアイテムを参照するもう 1 つの方法は、そのアイテムの label プロパティを使用する方法です。これ
は、他のオブジェクトの name プロパティ(段落スタイルやレイヤーなど)を使用するのと同じです。 次のス
クリプトに、ラベルが myLabel
に設定されているページアイテムの配列を取得する例を示します。 var myPageItems = app.documents.item(0).pages.item(0).pageItems("myLabel");
ページ上のページアイテムに指定されたラベルがない場合は、空の配列が返されます。
ページアイテムの形状
ページアイテムに関する作業を行うときは、InDesign のページアイテムの位置とシェイプの指定において、
定規と測定値がどのように相互に機能するかを理解している必要があります。 InDesign のユーザーインター
第 5 章 ページアイテムの操作 ページアイテムの作成 66
フェイスのコントロールパネルを使用する場合、InDesign の座標系を既に理解していると想定されますが、
要約を簡潔に示しておきます。
オブジェクトは、定規に表示される座標との相対位置で形成されます。
原点をドラッグしたり、定規の基点を変更して原点の位置を変更したりすると、定規の座標は変化しま
す。
ページアイテムは 1 つ以上のパスで構成され、パスは 2 つ以上のパスポイントで構成されます。 パスは、
開いた状態または閉じた状態の場合があります。
パスポイントには、1 つのアンカーポイント(ポイント自体の位置)と、2 つのコントロールハンドル
(パスポイントの前にある線区分のカーブを制御する左方向線と、ポイントの後にある線区分のカーブを
制御する右方向線)があります。 これらの各プロパティには、( x
, y
)形式の配列があります( x
はポイン
トの水平方向の位置、 y
置が、現在の定規の座標で格納されます。
前述の内容は、スクリプトでページアイテムを形成する必要がある場合は、原点の位置も制御する必要があ
り、場合によっては使用時の測定単位を設定する必要があることを意味します。
パスとパスポイントの操作
簡単なページアイテムでは、ほとんどの場合、オブジェクトのシェイプを定義するパスとパスポイントにつ
いて考慮する必要はありません。 長方形、楕円形、テキストフレームは、この章で前述した例が示すように、
それぞれの境界線を指定することで作成できます。
ただし、パスポイントの位置を指定してパスのシェイプを形成または変更することが必要になる場合があり
ます。この場合は、パスの各パスポイントのアンカーポイント、左方向線および右方向線を個別に設定する
か(DrawRegularPolygon_Slow スクリプトを参照してください)、パスの entirePath プロパティを使用してパ
スポイントのすべての位置を一度に設定できます(DrawRegularPolygon_Fast スクリプトを参照してくださ entirePath プロパティに使用する配列のアイテムには、アンカーポイントのみを指定するか、アンカーポイン
トとコントロールハンドルを指定できます。 次に、アンカーポイントの位置のみが指定されている配列の例
を示します。
[[x1, y1], [x2, y2], ...] x
と y
には、アンカーの位置を指定します。
次に、パスポイントがすべて指定されている配列(つまり、左方向線、アンカー、右方向線が、順に指定さ
れている配列)の例を示します。
[[xL1, YL1], [x1, y1], [xR1, yR1]], [[xL2, YL2], [x2, y2], [xR2, yR2]], ...] xL
と yL
には左方向線を、 x
と y
にはアンカーポイントを、 xR
と yR
には右方向線を指定します。
次の例のように、2 つのアプローチを組み合わせることもできます。
[[[xL1, YL1], [x1, y1], [xR1, yR1]], [x2, y2], ...]
対象となるパスのポイントの数と、配列に指定するポイントの数は、同じである必要はありません。 entirePath プロパティに配列が適用される際は、パスに対してポイントが自動的に追加または削除されます。
次の AddPathPoint スクリプトは、entirePath プロパティを使用せずにパスポイントをパスに追加する方法を
示しています。
//Given a graphic line "myGraphicLine"...
var myPathPoint = myGraphicLine.paths.item(0).pathPoints.add();
//Move the path point to a specific location.
myPathPoint.anchor = [144, 144];
第 5 章 ページアイテムの操作 ページアイテムのグループ化 67
次の DeletePathPoint スクリプトは、パスからパスポイントを削除する方法を示しています。
//Given a polygon "myPolygon", remove the
//last path point in the first path.
myPolygon.paths.item(0).pathPoints.item(-1).remove();
ページアイテムのグループ化
InDesign のユーザーインターフェイスでページアイテムのグループを作成するには、ページアイテムを選択
し、次に、オブジェクトメニューから「グループ」を選択します(または、対応するキーボードショート
ジアイテムを格納しているオブジェクト(通常はページやスプレッド)に指示をして、ページアイテムをグ
ループ化します。
//Given a page "myPage" containing at least two ovals and two rectangles...
var myArray = new Array;
//Add the items to the array.
myArray.push(myPage.rectangles.item(0)); myArray.push(myPage.ovals.item(0)); myArray.push(myPage.rectangles.item(1)); myArray.push(myPage.ovals.item(1));
//Group the items.
myPage.groups.add(myArray);
グループを解除するには、次の Ungroup スクリプトのように、グループ解除するグループ自体に指示をしま
す。
//Given a group "myGroup"...
myPageItems = myGroup.ungroup();
グループ内のページアイテムのシェイプやフォーマット、コンテンツを変更する際、グループの解除は不要
です。 代わりに、他のページアイテムの場合と同様に、変更するページアイテムへの参照を取得するだけで
す。
ページアイテムの複製と移動
InDesign のユーザーインターフェイスでは、ページアイテムを選択して新しい位置にドラッグすることで、
ページアイテムを移動できます。 ページアイテムのコピーは、コピーして貼り付ける方法や、Option または
または「繰り返し複製」を選択する方法で作成することもできます。 InDesign スクリプティングでは、ペー
ジアイテムの位置を変更する場合は move メソッドを使用し、ページアイテムのコピーを作成する(必要な
場合はそのコピーを別の位置に移動する)場合は duplicate メソッドを使用できます。
この move メソッドには、オプションの 2 つのパラメーター moveTo と moveBy のいずれかを指定できます。
この 2 つのパラメーターは、水平値と垂直値の 2 つの測定単位の配列で構成されています。moveTo には、原
点の現在の位置と相対的で、配列に指定されている位置への絶対的な移動を指定します。moveBy には、現
在のページアイテム自体の位置から相対的に、ページアイテムをどの程度移動するか(距離)を指定します。
次の Move スクリプトに、これらの 2 つのアプローチの相違を示します。
//Given a reference to a rectangle "myRectangle"...
//Move the rectangle to the location (12, 12).
//Absolute move: myRectangle.move([12, 12]);
//Move the rectangle *by* 12 points horizontally, 12 points vertically.
//Relative move (note undefined first parameter): myRectangle.move(undefined, [12, 12]);
//Move the rectangle to another page (rectangle appears at (0,0); var myPage = app.documents.item(0).pages.add(); myRectangle.move(myPage);
//To move a page item to another document, use the duplicate method.
第 5 章 ページアイテムの操作 ページアイテムの複製と移動 68 move メソッドによってオブジェクトが実際に移動することに注意してください。別のドキュメントに移動
したページアイテムは、元のドキュメントから削除されます。 元のオブジェクトを残したままオブジェクト
を別の位置に動かすには、duplicate メソッドを使用します(次の例を参照してください)。
ページアイテムのコピーを作成するには、duplicate メソッドを使用します。 デフォルトでは、duplicate メ
ソッドによって、元のオブジェクトと同じ位置にオブジェクトの「クローン」が作成されます。 複製したオ
ブジェクトを新しい位置に移動(同じドキュメント内の他のページへの移動や完全に別のドキュメントへの
移動など)するには、duplicate メソッドでオプションのパラメーターを使用します。
//Given a reference to a rectangle "myRectangle"...
//Duplicate the rectangle and move the
//duplicate to the location (12, 12).
//Absolute move: var myDuplicate = myRectangle.duplicate([12, 12]);
//Duplicate the rectangle and move the duplicate *by* 12
//points horizontally, 12 points vertically.
//Relative move (note undefined first parameter): var myDuplicate = myRectangle.duplicate(undefined, [12, 12]);
//Duplicate the rectangle to another page (rectangle appears at (0,0).
var myPage = app.documents.item(0).pages.add(); var myDuplicate = myRectangle.duplicate(myPage);
//Duplicate the rectangle to another document.
var myDocument = app.documents.add(); var myDuplicate = myRectangle.duplicate(myDocument.pages.item(0));
InDesign スクリプティングではコピーして貼り付ける方法も使用できますが、この方法を使用するスクリプ
貼り付け対象要素の位置を設定する必要があります。 これは、コピーして貼り付ける方法を使用するスクリ
プトは、複製して移動する方法を使用するスクリプトよりも確実性が低い(失敗する可能性が高い)ことを
意味します。 可能な限り、現在の表示や選択状態に依存しないスクリプトを記述してください。
複合パスの作成
InDesign では、オブジェクト/パス/複合パスを作成メニューオプションを使用して、2 つ以上のページア
イテムのパスを、複数のパスが含まれる単一のページアイテムに結合することができます。 InDesign スクリ
プティングでこの処理を行うには、ページアイテムの makeCompoundPath メソッドを使用します。次のスク
リプトにその例を示します(完全なスクリプトについては、MakeCompoundPath スクリプトを参照してくだ
さい)。
//Given a rectangle "myRectangle" and an Oval "myOval"...
myRectangle.makeCompoundPath(myOval);
複合パスを作成すると、複合パスの作成に使用したオブジェクトの種類に関係なく、結果として形成される
オブジェクトの種類は多角形になります。
複合パスを解除して、複合パスの各パスを個別のページアイテムに変換するには、ページアイテムの releaseCompoundPath メソッドを使用します。次のスクリプトにその例を示します(完全なスクリプトにつ
いては、ReleaseCompoundPath スクリプトを参照してください)。
//Given a polygon "myPolygon"...
var myPageItems = myPolygon.releaseCompoundPath();
パスファインダー機能の使用
InDesign のパスファインダー機能には、InDesign ページの複数ページアイテム間の関係を操作する方法が用
意されています。 ページアイテムのパスを結合したり、あるページアイテムの領域を別のページアイテムか
ら取り除いたり、2 つ以上のページアイテムが交差している領域から新しいページアイテムを作成したりす
ることができます。 すべてのページアイテムでは、パスファインダー機能に関連する AddPath、
ExcludeOverlapPath、IntersectPath、MinusBack および SubtractPath の各メソッドがサポートされています。
第 5 章 ページアイテムの操作 ページアイテムの複製と移動 69
パスファインダーのすべてのメソッドは同じように機能します。ユーザーは、操作の基本として使用する
ページアイテムの配列を用意します(ユーザーインターフェイスでパスファインダー操作を選択する前に、
一連のページアイテムを選択する場合と同様です)。
いずれかのパスファインダー操作を適用すると、オブジェクトの種類が変更される可能性が非常に高いこと
に注意してください。 操作の結果、1 つまたは複数のパスに存在するポイントの数が幾つになるか、そしてど
の位置に来るかによって、オブジェクトの種類が決まります。
2 つのページアイテムを 1 つのページアイテムに結合するには、例えば、次のスクリプトに示すようなアプ
ローチを使用します(完全なスクリプトについては、AddPath を参照してください)。
//Given a rectangle "myRectangle" and an Oval "myOval"...
myRectangle.addPath(myOval); excludeOverlapPath メソッドは、重なり合った 2 つ以上のページアイテムの交差していない領域に基づいて新
しいパスを作成します。次のスクリプトにその例を示します(完全なスクリプトについては、
//Given a rectangle "myRectangle" and an Oval "myOval"...
myRectangle.excludeOverlapPath(myOval); intersectPath メソッドは、2 つ以上のページアイテムの交差している領域から新しいページアイテムを作成し
ます。次のスクリプトにその例を示します(完全なスクリプトについては、IntersectPath を参照してくださ
//Given a rectangle "myRectangle" and an Oval "myOval"...
myRectangle.intersect(myOval); minusBack メソッドは、最背面のオブジェクトの前面にある 1 つまたは複数のページアイテムから、最背面
のオブジェクトと交差している領域を取り除きます。次のスクリプトにその例を示します(完全なスクリプ
トについては、MinusBack を参照してください)。
//Given a rectangle "myRectangle" and an Oval "myOval"...
myRectangle.minusBack(myOval); subtractPath メソッドは、最前面のオブジェクトの背面にある 1 つまたは複数のページアイテムから、最前面
のオブジェクトと交差している領域を取り除きます。次のスクリプトにその例を示します(完全なスクリプ
トについては、SubtractPath を参照してください)。
//Given a rectangle "myRectangle" and an Oval "myOval"...
myOval.subtractPath(myRetangle);
ページアイテムのシェイプの変換
InDesign のページアイテムは、オブジェクト/シェイプを変換メニューで表示されるオプションを使用する
か、パスファインダーパネル(ウィンドウ/オブジェクトとレイアウト/パスファインダー)を使用して、
他のシェイプに変換できます。 InDesign スクリプティングのページアイテムでは、convertShape メソッドが
サポートされています。次のスクリプトにその例を示します(完全なスクリプトについては、ConvertShape
を参照してください)。
//Given a rectangle "myRectangle"...
myRectangle.convertShape(ConvertShapeOptions.convertToRoundedRectangle); convertShape メソッドには、反転パスの開閉方法も用意されています。次のスクリプトにその例を示します
(完全なスクリプトについては、OpenPath を参照してください)。
//Given a rectangle "myRectangle"...
myRectangle.convertShape(ConvertShapeOptions.convertToOpenPath);
第 5 章 ページアイテムの操作 ページアイテムの変形 70
ページアイテムの配置
InDesign レイアウトのページアイテムは、レイヤー内での重なり順を調整することによって、前面または背
面に相互に配置したり、別のレイヤーに配置したりできます。 次のスクリプトに、レイヤー内でオブジェク
トを前面または背面に移動する方法と、オブジェクトの相対的な重なり順を制御する方法を示します(完全
なスクリプトについては、StackingOrder を参照してください)。
//Given a rectangle "myRectangle" and an oval "myOval",
//where "myOval" is in front of "myRectangle", bring
//the rectangle to the front...
myRectangle.bringToFront();
ページアイテムを作成する場合は、そのページアイテムのレイヤーを指定できますが、レイヤー間でページ
アイテムを移動することもできます。 これを実行する場合は、ページアイテムの itemLayer プロパティが重要
な役割を果たします。次のスクリプトにその例を示します(完全なスクリプトについては、ItemLayer を参照
してください)。
//Given a rectangle "myRectangle" and a layer "myLayer",
//send the rectangle to the layer...
myRectangle.itemLayer = app.Documents.item(0).layers.item("myLayer");
ドキュメント内でのレイヤーの重なり順は、レイヤー自体の move メソッドを使用して変更することもでき
ます。次のスクリプトにその例を示します(完全なスクリプトについては、MoveLayer を参照してくださ
//Given a layer "myLayer", move the layer behind
//the default layer (the lowest layer in the document
//is layers.item(-1).
myLayer.move(LocationOptionsafter, app.documents.item(0).layers.item(-1));
ページアイテムの変形
変形には、拡大・縮小、回転、シアー(歪み)、移動(または変換)があります。 スクリプティングでは、 transform
InDesign CS3(5.0)より前の InDesign バージョンで使用さ
れていた resize
、 rotate
、 shear
の各メソッドは、この 1 つのメソッドに置き換えられました。
transform メソッドの使用
transform
メソッドには、オブジェクトに適用する変形または一連の変形を定義する変形マトリックス
( transformationMatrix
)オブジェクトが必要です。 変形マトリックスには、定規、回転、シアー、変換など
の操作の組み合わせを指定できます。
オブジェクトに変形を適用する順序は重要です。 異なる順序で変形を適用すると、まったく異なる結果とな
る可能性があります。
オブジェクトを変形するには、次の 2 つの手順に従います。
1.
変形マトリックスを作成します。
2.
この変形マトリックスを transform
メソッドを使用してオブジェクトに適用します。
を参照して
ください。 さらに、変形の中心、つまり変形の基点を指定します。 変形の基点について詳しくは、
を参照してください。
次のスクリプトに、ページアイテムを変形する基本的なプロセスの例を示します (完全なスクリプトについ
ては、TransformExamples を参照してください)。
第 5 章 ページアイテムの操作 ページアイテムの変形 71
//Rotate a rectangle "myRectangle" around its center point.
var myRotateMatrix = app.transformationMatrices.add({counterclockwiseRotationAngle:27}); myRectangle.transform(CoordinateSpaces.pasteboardCoordinates, AnchorPoint.centerAnchor, myRotateMatrix);
//Scale a rectangle "myRectangle" around its center point.
var myScaleMatrix = app.transformationMatrices.add({horizontalScaleFactor:.5, verticalScaleFactor:.5}); myRectangle.transform(CoordinateSpaces.pasteboardCoordinates, AnchorPoint.centerAnchor, myScaleMatrix);
//Shear a rectangle "myRectangle" around its center point.
var myShearMatrix =app.transformationMatrices.add({clockwiseShearAngle:30}); myRectangle.transform(CoordinateSpaces.pasteboardCoordinates, AnchorPoint.centerAnchor, myShearMatrix);
//Rotate a rectangle "myRectangle" around a specified ruler point ([72, 72]).
var myRotateMatrix = app.transformationMatrices.add({counterclockwiseRotationAngle:27}); myRectangle.transform(CoordinateSpaces.pasteboardCoordinates, [[72, 72],
AnchorPoint.topLeftAnchor], myRotateMatrix, undefined, true);
//Scale a rectangle "myRectangle" around a specified ruler point ([72, 72]).
var myScaleMatrix = app.transformationMatrices.add({horizontalScaleFactor:.5, verticalScaleFactor:.5}); myRectangle.transform(CoordinateSpaces.pasteboardCoordinates, [[72, 72],
AnchorPoint.topLeftAnchor], myScaleMatrix, undefined, true);
変形関数を、簡単に使用できる一連の関数に「ラップ」するスクリプトについては、Transform スクリプトを
参照してください。
変形マトリックスの操作
一度作成した変形マトリックスは変更できませんが、様々な方法で変形マトリックスを操作して、既存の変
形マトリックスに基づいて新規の変換マトリックスを作成できます。 次のスクリプトに、変形マトリックス
に複数の変形を適用し、元のマトリックスを置き換える方法の例を示します (完全なスクリプトについて
は、TransformMatrix を参照してください)。
//Scale a transformation matrix by 50% in both horizontal and vertical dimensions.
var myTransformationMatrix = myTransformationMatrix.scaleMatrix(.5, .5);
//Rotate a transformation matrix by 45 degrees.
myTransformationMatrix = myTransformationMatrix.rotateMatrix(45);
//Shear a transformation matrix by 15 degrees.
myTransformationMatrix = myTransformationMatrix.shearMatrix(15); rotateMatrix
メソッドを使用する場合は、次の RotateMatrix スクリプトのように、角度ではなくサイン値ま
たはコサイン値を使用してマトリックスを変形できます。
//The following statements are equivalent
//(0.25881904510252 is the sine of 15 degrees; 0.96592582628907, the cosine).
myTransformationMatrix = myTransformationMatrix.rotateMatrix(15); myTransformationMatrix = myTransformationMatrix.rotateMatrix(undefined, 0.96592582628907); myTransformationMatrix = myTransformationMatrix.rotateMatrix(undefined, undefined,
0.25881904510252); shearMatrix
メソッドを使用する場合は、次の ShearMatrix スクリプトのように、角度ではなく傾斜を使用で
きます。
//The following statements are equivalent. slope = rise/run--so
//the slope of 45 degrees is 1.
myTransformationMatrix = myTransformationMatrix.shearMatrix(45); myTransformationMatrix = myTransformationMatrix.shearMatrix(undefined, 1); invertMatrix
メソッドを使用すると、変形マトリックスの逆マトリックスを取得できます。次のスクリプト
にその例を示します (完全なスクリプトについては、InvertMatrix を参照してください)。 マトリックスの効
果は、反転させた変形マトリックスを使用して元に戻すことができます。
第 5 章 ページアイテムの操作 ページアイテムの変形 72 var myRectangle = app.documents.item(0).pages.item(0).rectangles.item(0); var myTransformationMatrix = app.transformationMatrices.add({counterclockwiseRotationAngle:30, horizontalTranslation:12, verticalTranslation:12}); myRectangle.transform(CoordinateSpaces.pasteboardCoordinates, AnchorPoint.centerAnchor, myTransformationMatrix); var myNewRectangle = myRectangle.duplicate();
//Move the duplicated rectangle to the location of the original
//rectangle by inverting, then applying the transformation matrix.
myTransformationMatrix = myTransformationMatrix.invertMatrix(); myRectangle.transform(CoordinateSpaces.pasteboardCoordinates, AnchorPoint.centerAnchor, myTransformationMatrix); catenateMatrix
メソッドを使用すると、変形マトリックスを追加できます。次のスクリプトにその例を示し
ます (完全なスクリプトについては、CatenateMatrix を参照してください)。 var myTransformationMatrixA = app.transformationMatrices.add({counterclockwiseRotationAngle:30}); var myTransformationMatrixB = app.transformationMatrices.add({horizontalTranslation:12, verticalTranslation:12}); var myRectangle = app.documents.item(0).pages.item(0).rectangles.item(-1); var myNewRectangle = myRectangle.duplicate();
//Rotate the duplicated rectangle.
myNewRectangle.transform(CoordinateSpaces.pasteboardCoordinates, AnchorPoint.centerAnchor, myTransformationMatrixA); myNewRectangle = myRectangle.duplicate();
//Move the duplicate (unrotated) rectangle.
myNewRectangle.transform(CoordinateSpaces.pasteboardCoordinates, AnchorPoint.centerAnchor, myTransformationMatrixB);
//Merge the two transformation matrices.
myTransformationMatrix = myTransformationMatrixA.catenateMatrix(myTransformationMatrixB); myNewRectangle = myRectangle.duplicate();
//The duplicated rectangle will be both moved and rotated.
myNewRectangle.transform(CoordinateSpaces.pasteboardCoordinates, AnchorPoint.centerAnchor, myTransformationMatrix);
オブジェクトが変形されている場合は、 transformValuesOf
メソッドを使用して、そのオブジェクトに適用
された変形マトリックスを取得できます。次のスクリプトにその例を示します (完全なスクリプトについて
は、TransformValuesOf を参照してください)。
//Note that transformValuesOf() always returns an array
//containing a single transformationMatrix.
var myTransformArray = myRectangle.transformValuesOf(CoordinateSpaces.parentCoordinates); var myTransformationMatrix = myTransformArray[0]; var myRotationAngle = myTransformationMatrix.counterclockwiseRotationAngle; var myShearAngle = myTransformationMatrix.clockwiseShearAngle; var myXScale = myTransformationMatrix.horizontalScaleFactor; var myYScale = myTransformationMatrix.verticalScaleFactor; var myXTranslate = myTransformationMatrix.horizontalTranslation; var myYTranslate = myTransformationMatrix.verticalTranslation; var myString = "Rotation Angle: " + myRotationAngle + "¥r"; myString += "Shear Angle: " + myShearAngle + "¥r"; myString += "Horizontal Scale Factor: " + myXScale + "¥r"; myString += "Vertical Scale Factor: " + myYScale + "¥r"; myString += "Horizontal Translation: " + myXTranslate + "¥r"; myString += "Vertical Translation: " + myYTranslate + "¥r"; alert(myString);
注意 : このメソッドで返された変形マトリックスの水平変形フィールド値と垂直変形フィールド値は、ペー
ストボードの座標におけるオブジェクトの左上アンカーの位置です。
第 5 章 ページアイテムの操作 ページアイテムの変形 73
座標スペース
前述の変形スクリプトでは、transform メソッドのパラメーターに
CoordinateSpaces.pasteboardCoordinates
このパラメーターによって、変形操
作が発生する座標系、つまり座標スペースが決まります。 座標スペースの値は、次のいずれかです。
CoordinateSpaces.pasteboardCoordinates
この座
標スペースは、ドキュメント内のすべてのスプレッドにわたって適用されます。 InDesign の定規または原
点には対応しておらず、InDesign のユーザーインターフェイスでページの周囲に表示されるペースト
ボードの領域とも関係ありません。 オブジェクトに適用した変形による、この座標スペースへの影響は
ありません(例えば、水平軸と垂直軸の角度は変化しません)。
CoordinateSpaces.parentCoordinates
親に適用した変形は、
親座標に影響を与えます。例えば、親オブジェクトを回転させると、この座標スペースの水平軸と垂直
軸の角度が変化します。 この場合、親オブジェクトとはオブジェクトを格納しているグループまたは
ページアイテムを指します。オブジェクトの親がページまたはスプレッドの場合、親座標はスプレッド
の座標と同じです。
CoordinateSpaces.innerCoordinates
は、オブジェクト自体が作成された座標スペースです。
CoordinateSpaces.spreadCoordinates
この座標スペースの基点は、
スプレッドの中心にあり、ユーザーインターフェイスに表示される定規には対応していません。
次のスクリプトは、座標スペース間の相違を示します (完全なスクリプトについては、CoordinateSpaces を
参照してください)。 var myRectangle = app.documents.item(0).pages.item(0).groups.item(-1).rectangles.item(0); alert("The page contains a group which has been¥rrotated 45 degrees (counterclockwise).¥rThe rectangle inside the group was¥rrotated 45 degrees counterclockwise¥rbefore it was added to the group.¥r¥rWatch as we apply a series of scaling¥roperations in different coordinate spaces."); var myTransformationMatrix = app.transformationMatrices.add({horizontalScaleFactor:2});
//Transform the rectangle using inner coordinates.
myRectangle.transform(CoordinateSpaces.innerCoordinates, AnchorPoint.centerAnchor, myTransformationMatrix);
//Select the rectangle and display an alert.
app.select(myRectangle); alert("Transformed by inner coordinates.");
//Undo the transformation.
app.documents.item(0).undo();
//Transform using parent coordinates.
myRectangle.transform(CoordinateSpaces.parentCoordinates, AnchorPoint.centerAnchor, myTransformationMatrix); app.select(myRectangle); alert("Transformed by parent coordinates."); app.documents.item(0).undo();
//Transform using pasteboard coordinates.
myRectangle.transform(CoordinateSpaces.pasteboardCoordinates, AnchorPoint.centerAnchor, myTransformationMatrix); app.select(myRectangle); alert("Transformed by pasteboard coordinates."); app.documents.item(0).undo();
変形の基点
変形の基点は、変形の中心点です。 変形の基点は様々な方法で指定できます。
境界線スペース:
アンカー - オブジェクト自体のアンカーポイント。
AnchorPoint.centerAnchor
第 5 章 ページアイテムの操作 ページアイテムの変形 74
アンカー、境界線の種類 - オブジェクトの境界線(
BoundingBoxLimits.geometricPathBounds
)また
はオブジェクトの表示可能な境界線(
BoundingBoxLimits.outerStrokeBounds
)との相対位置で指定
されたアンカーポイント。
[AnchorPoint.bottomLeftAnchor, BoundingBoxLimits.outerStrokeBounds]
アンカー、境界線の種類、座標系 - 特定の座標スペースにおいて、オブジェクトの境界線
(
BoundingBoxLimits.geometricPathBounds
)またはオブジェクトの表示可能な境界線
(
BoundingBoxLimits.outerStrokeBounds
)として指定されたアンカーポイント。
[AnchorPoint.bottomLeftAnchor, BoundingBoxLimits.outerStrokeBounds,
CoordinateSpaces.pasteboardCoordinates]
(x,y)、境界線の種類 - オブジェクトの境界線(
BoundingBoxLimits.geometricPathBounds
)またはオ
ブジェクトの表示可能な境界線(
BoundingBoxLimits.outerStrokeBounds
)との相対位置で指定され
たポイント。 この場合、バウンディングボックスの左上角は(0, 0)、右下角は(1, 1)です。 中心の
アンカーは(.5, .5)に配置されます。
[[.5, .5], BoundingBoxLimits.outerStrokeBounds]
(x, y)、境界線の種類、座標スペース - 特定の座標スペースにおける、オブジェクトの境界線
(
BoundingBoxLimits.geometricPathBounds
)またはオブジェクトの表示可能な境界線
(
BoundingBoxLimits.outerStrokeBounds
)との相対位置で指定されたポイント。 この場合、バウン
ディングボックスの左上角は(0, 0)、右下角は(1, 1)です。 中心のアンカーは(.5, .5)に配置され
ます。
[[.5, .5], BoundingBoxLimits.outerStrokeBounds,
CoordinateSpaces.pasteboardCoordinates]
定規スペース:
(x, y)、ページインデックス - スプレッドの指定ページ上にある定規基点との相対位置で指定された
ポイント。
[[72, 144], 0]
(x, y)、位置 - オブジェクトの指定された位置の親ページとの相対位置で指定されたポイント。 位置
は、アンカーポイントまたは 1 組の座標として指定できます。 位置は、オブジェクトの境界線または
表示可能な境界線との相対位置で指定でき、特定の座標スペースに指定できます。
[[72, 144], AnchorPoint.centerAnchor]
変形スペース:
(x, y)- ペーストボードの座標スペース内のポイント。
[72, 72]
(x, y)、座標系 - 指定した座標スペース内のポイント。
[[72, 72], CoordinateSpaces.parentCoordinates]
((x, y))- transform
メソッドの in
パラメーターとして指定された座標スペース内のポイント。
[[72, 72]]
変形の基点オプションを使用する方法について、次のスクリプトにいくつかの例を示します (完全なスクリ
プトについては、TransformationOrigin を参照してください)。
第 5 章 ページアイテムの操作 ページアイテムの変形 75
//Rotate around the duplicated rectangle's center point.
myNewRectangle.transform(CoordinateSpaces.pasteboardCoordinates, AnchorPoint.centerAnchor, myTransformationMatrix);
//Rotate the rectangle around the ruler location [-100, -100].
//Note that the anchor point specified here specifes the page
//containing the point--*not* that transformation point itself.
//The transformation gets the ruler coordinate [-100, -100] based
//on that page. Setting the considerRulerUnits parameter to true makes
//certain that the transformation uses the current ruler units.
myNewRectangle.transform(CoordinateSpaces.pasteboardCoordinates, [[-100, -100],
AnchorPoint.topLeftAnchor], myTransformationMatrix, undefined, true);
位置の解決
ある座標スペースに指定したポイントの位置を、別の座標スペースのコンテキストで取得することが必要に
なる場合があります。 取得するには、 resolve
メソッドを使用します。次のスクリプトにその例を示します
(完全なスクリプトについては、ResolveLocation を参照してください)。 var myPageLocation = myRectangle.resolve([[72, 72], AnchorPoint.topRightAnchor],
CoordinateSpaces.pasteboardCoordinates, true);
//resolve() returns an array containing a single item.
alert("X: " + myPageLocation[0][0] + "¥rY: " + myPageLocation[0][1]);
ポイントの変形
ポイントもオブジェクトと同様に変形することができます。つまり、スクリプト自体に計算を組み込まなく
てもスクリプトで様々な算術演算を処理できます。 次の ChangeCoordinates サンプルスクリプトは、このアプ
ローチを使用して一連の正多角形を描画する方法を示しています。
//General purpose routine for drawing regular polygons from their center point.
function myDrawPolygon(myParent, myCenterPoint, myNumberOfPoints, myRadius, myStarPolygon, myStarInset){ var myTransformedPoint; var myPathPoints = new Array; var myPoint = [0,0]; if(myStarPolygon == true){ myNumberOfPoints = myNumberOfPoints * 2;
} var myInnerRadius = myRadius * myStarInset; var myAngle = 360/myNumberOfPoints; var myRotateMatrix = app.transformationMatrices.add({ counterclockwiseRotationAngle:myAngle}); var myOuterTranslateMatrix = app.transformationMatrices.add({ horizontalTranslation:myRadius}); var myInnerTranslateMatrix = app.transformationMatrices.add({ horizontalTranslation:myInnerRadius}); for (var myPointCounter = 0; myPointCounter < myNumberOfPoints; myPointCounter ++){
//Translate the point to the inner/outer radius.
if ((myStarInset == 1)||(myIsEven(myPointCounter)==true)){ myTransformedPoint = myOuterTranslateMatrix.changeCoordinates(myPoint);
} else{ myTransformedPoint = myInnerTranslateMatrix.changeCoordinates(myPoint);
} myTransformedPoint = myRotateMatrix.changeCoordinates(myTransformedPoint); myPathPoints.push(myTransformedPoint); myRotateMatrix = myRotateMatrix.rotateMatrix(myAngle);
}
//Create a new polygon.
var myPolygon = myParent.polygons.add();
//Set the entire path of the polygon to the array we've created.
第 5 章 ページアイテムの操作 ページアイテムの変形 76 myPolygon.paths.item(0).entirePath = myPathPoints;
//If the center point is somewhere other than [0,0],
//translate the polygon to the center point.
if((myCenterPoint[0] != 0)||((myCenterPoint[1] != 0))){ var myTranslateMatrix = app.transformationMatrices.add({ horizontalTranslation:myCenterPoint[0], verticalTranslation:myCenterPoint[1]}); myPolygon.transform(CoordinateSpaces.pasteboardCoordinates,
AnchorPoint.centerAnchor, myTranslateMatrix);
}
}
//This function returns true if myNumber is even, false if it is not.
function myIsEven(myNumber){ var myResult = (myNumber%2)?false:true; return myResult;
}
FunWithTransformations サンプルスクリプトに示すように、 changeCoordinates
メソッドを使用して、カーブ
を制御するポイントの位置を変更することもできます。
変形の繰り返し
ユーザーインターフェイスでは変形または一連の変形を繰り返し適用できますが、同じことがスクリプティ
ングでも可能です。 変形を繰り返し適用するメソッドは、4 種類あります。
transformAgain
transformAgainIndividually
transformSequenceAgain
transformSequenceAgainIndividually transformAgain
の使用方法を、次のスクリプトに示します (完全なスクリプトについては、TransformAgain
を参照してください)。 var myRectangle = myPage.rectangles.item(0); var myBounds = myRectangle.geometricBounds; var myX1 = myBounds[1]; var myY1 = myBounds[0]; var myRectangleA = myPage.rectangles.add({geometricBounds:[myY1-12, myX1-12, myY1+12, myX1+12]}); var myTransformationMatrix = app.transformationMatrices.add({counterclockwiseRotationAngle:45}); myRectangleA.transform(CoordinateSpaces.pasteboardCoordinates, AnchorPoint.centerAnchor, myTransformationMatrix); var myRectangleB = myRectangleA.duplicate(); myRectangleB.transform(CoordinateSpaces.pasteboardCoordinates, [[0,0],
AnchorPoint.topLeftAnchor], myTransformationMatrix, undefined, true); var myRectangleC = myRectangleB.duplicate(); myRectangleC.transformAgain(); var myRectangleD = myRectangleC.duplicate(); myRectangleD.transformAgain(); var myRectangleE = myRectangleD.duplicate(); myRectangleE.transformAgain(); var myRectangleF = myRectangleE.duplicate(); myRectangleF.transformAgain(); var myRectangleG = myRectangleF.duplicate(); myRectangleG.transformAgain(); var myRectangleH = myRectangleG.duplicate(); myRectangleH.transformAgain(); myRectangleB.transform(CoordinateSpaces.pasteboardCoordinates, AnchorPoint.centerAnchor, myTransformationMatrix); myRectangleD.transformAgain(); myRectangleF.transformAgain(); myRectangleH.transformAgain();
第 5 章 ページアイテムの操作 サイズ変更とフレーム調整 77
サイズ変更とフレーム調整
transform メソッドを使用したページアイテムの拡大・縮小に加え、他の 2 つのメソッド resize と reframe を
使用してシェイプのサイズを変更することもできます。 これらのメソッドでは、ページアイテムのコンテン
ツや線幅を拡大・縮小せずに、ページアイテムのパスポイントの位置が変更されます。 resize メソッドの使用
方法を、次のスクリプトに示します。 完全なスクリプトについては、Resize を参照してください。
//Given a reference to a rectangle "myRectangle"...
var myDuplicate = myRectangle.duplicate(); myDuplicate.resize(CoordinateSpaces.innerCoordinates, AnchorPoint.centerAnchor,
ResizeMethods.multiplyingCurrentDimensionsBy, [2, 2]);
してください。
//Given a reference to a rectangle "myRectangle"...
var myBounds = myRectangle.geometricBounds; var myX1 = myBounds[1]-72; var myY1 = myBounds[0]-72; var myX2 = myBounds[3]+72; var myY2 = myBounds[2]+72; myDuplicate = myRectangle.duplicate(); myDuplicate.reframe(CoordinateSpaces.innerCoordinates, [[myY1, myX1],[myY2, myX2]]);
アーティクルの使用
アーティクルを使用することで、デザイナーや制作アーティストはページアイテム間の関係を簡単に作成す
ることができます。 関係を使用することで、ePub、HTML またはアクセシブル PDF への書き出しに使用するコ
ンテンツや、コンテンツの順序を定義できます。 画像、グラフィック、テキストなど、レイアウトに含まれ
ている既存のページアイテムを組み合わせてアーティクルを作成することができます。 アーティクルを作成
した後は、ページアイテムを追加または削除したり、ページアイテムの順序を変更したりできます。
アーティクルリストの取得
ドキュメント内のアーティクルを取得するには、次のスクリプトを使用します(完全なスクリプトについて
は、CreateArticle を参照してください)。 var myDocument = app.documents.item(0); var articles = myDocument.articles;
新しいアーティクルの追加
ドキュメントに新しいアーティクルを追加するには、次のスクリプトを使用します(完全なスクリプトにつ
いては、CreateArticle を参照してください)。 var article1 = myDocument.articles.add("Article1", true);
アーティクルの削除
アーティクルを削除するには、次のスクリプトに示すように、削除対象のアーティクル自体に対して削除を
指示します(完全なスクリプトについては、RemoveArticle を参照してください)。 article.remove();
第 5 章 ページアイテムの操作 アーティクルの使用 78
アーティクルの順序変更
アーティクルの順序を変更するには、次のスクリプトに示すように、移動対象のアーティクルに対して参照
アーティクルと参照アーティクルを基準にした相対位置を指示します(完全なスクリプトについては、 var article1 = articles.add("Article1", true); var article2 = articles.add("Article2", true); var article3 = articles.add("Article3", true); var article4 = articles.add("Article4", true);
//Reverse the order of articles.
//Move article4 to the first.
article4.move(LocationOptions.AT_BEGINNING);
//Move article1 to the end.
article1.move(LocationOptions.AT_END);
//Move article3 to the second place.
article3.move(LocationOptions.AFTER, article4);
//Move article2 to the third place.
article2.move(LocationOptions.BEFORE, article1);
アーティクルへの新規メンバーの追加
アーティクルに新規メンバーを追加するには、次のスクリプトを使用します(完全なスクリプトについては、 var myDocument = app.documents.item(0);
//Retrieve the articles for the document.
var articles = myDocument.articles;
//Create new articles var article1 = articles.add("Article1", true); var article2 = articles.add("Article2", true); var article3 = articles.add("Article3", true); var myPage = myDocument.pages.item(0); var article1Members = article1.articleMembers; article1Members.add(myPage.rectangles.item(0)); article1Members.add(myPage.ovals.item(0)); var article2Members = article2.articleMembers; article2Members.add(myPage.rectangles.item(1)); article2Members.add(myPage.ovals.item(1)); var article3Members = article3.articleMembers; var myGroup = myPage.groups.item(0);
//Add group as article member.
article3Members.add(myGroup);
アーティクルのメンバーの順序変更
アーティクルのメンバーの順序を変更するには、次のスクリプトに示すように、移動対象のメンバーに対し
て参照オブジェクトと参照オブジェクトを基準にした相対位置を指示します(完全なスクリプトについては、
第 5 章 ページアイテムの操作 アーティクルの使用 79
//Assume there are four members in the article in the following order: rectangle, oval, text frame, group var articleMembers = article.articleMembers; articleMembers.add(myPage.rectangles.item(0)); articleMembers.add(myPage.ovals.item(0)); articleMembers.add(myPage.textFrames.item(0)); articleMembers.add(myPage.groups.item(0)); articleMembers.item(0).move(LocationOptions.AT_END); articleMembers.item(2).move(LocationOptions.AT_BEGINNING); articleMembers.item(1).move(LocationOptions.AFTER, articleMembers.item(2));
アーティクルからのメンバーの削除
アーティクルからメンバーを削除するには、次のスクリプトに示すように、削除対象のアーティクルメン
バー自体に対して削除を指示します(完全なスクリプトについては、AddRemoveArticleMember を参照して var articleMember = article1Members.item(0); articleMember.remove();
6
テキストと組版
CS6 更新
章の更新ステータス
という節の追加。
テキストの入力、編集、フォーマットといった作業は、InDesign ドキュメントの製作工程の中でも、最も時
間のかかる作業の 1 つです。 したがって、テキストや書式に関する作業を自動化できれば、生産性の大幅な
向上が期待できます。
この章では、テキストや書式に関する一般的な操作をスクリプトで実行する方法について説明します。 最初
は簡単なサンプルスクリプトから始めて、徐々に複雑なスクリプトへと進んでいきます。
ここでは、読者が『Adobe InDesign スクリプティングチュートリアル』を既に読んでおり、スクリプトを作
成、インストール、実行する方法を理解しているものとして説明を行います。 また、InDesign でテキストを
操作する方法や、組版に関する基本的な用語を理解しているものとしています。
テキストの入力と読み込み
ここでは、InDesign ドキュメントにテキストを配置する方法について説明します。 InDesign のユーザーイン
ターフェイスを使用してテキストフレームにテキストを入力したり、テキストファイルを配置したりするの
と同じように、スクリプトを使用してテキストフレームを作成し、ストーリーにテキストを挿入し、ページ
上にテキストファイルを配置することができます。
テキストフレームの作成
次のスクリプトでは、テキストフレームを作成し、フレームの境界(サイズ)を設定し、フレームにテキス
トを入力しています(完全なスクリプトについては、MakeTextFrame というチュートリアルスクリプトを参
照してください)。 var myDocument = app.documents.item(0); var myPage = myDocument.pages.item(0); var myTextFrame = myPage.textFrames.add();
//Set the bounds of the text frame.
myTextFrame.geometricBounds = [72, 72, 288, 288];
//Enter text in the text frame.
myTextFrame.contents = "This is some example text."
//Note that you could also use a properties record to
//create the frame and set its bounds and contents in one line:
//var myTextFrame = myDocument.pages.item(0).textFrames.add(
{geometricBounds:[72, 72, 288, 288], contents:"This is some example text."});
次のスクリプトでは、ページマージンによって定義される領域と同じサイズのテキストフレームを作成して
います。ここで使用している myGetBounds
は、様々なスクリプトで活用できる便利な関数であり、この章の
多くの例でも使用されています (完全なスクリプトについては、MakeTextFrameWithinMargins を参照してく
ださい)。
80
第 6 章 テキストと組版 テキストの入力と読み込み 81 var myDocument = app.documents.item(0); var myPage = myDocument.pages.item(0);
//Create a text frame on the current page.
var myTextFrame = myPage.textFrames.add();
//Set the bounds of the text frame.
myTextFrame.geometricBounds = myGetBounds(myDocument, myPage);
//Enter text in the text frame.
myTextFrame.contents = "This is some example text."
次のスクリプトに myGetBounds 関数を示します。 function myGetBounds(myDocument, myPage){ var myPageWidth = myDocument.documentPreferences.pageWidth; var myPageHeight = myDocument.documentPreferences.pageHeight
if(myPage.side == PageSideOptions.leftHand){ var myX2 = myPage.marginPreferences.left; var myX1 = myPage.marginPreferences.right;
} else{ var myX1 = myPage.marginPreferences.left; var myX2 = myPage.marginPreferences.right;
} var myY1 = myPage.marginPreferences.top; var myX2 = myPageWidth - myX2; var myY2 = myPageHeight - myPage.marginPreferences.bottom; return [myY1, myX1, myY2, myX2];
}
テキストの追加
ストーリーにテキストを追加するには、テキストを挿入する箇所で挿入点の contents
プロパティを使用しま
す。 次のサンプルスクリプトでは、この方法を使用して、ストーリーの末尾にテキストを追加しています
(完全なスクリプトについては、AddText を参照してください)。
//Add text at the end of the text in the text frame.
//To do this, we'll use the last insertion point in the story.
//("¥r" is a return character.) var myNewText = "¥rThis is a new paragraph of example text."; myTextFrame.parentStory.insertionPoints.item(-1).contents = myNewText;
ストーリーとテキストフレーム
InDesign レイアウトの中にあるテキストは、すべてストーリーの中に含まれています。どのストーリーにも
作成されます。ストーリーには複数のテキストフレームを含めることができます。
前述のスクリプトでは、テキストフレームの末尾ではなく、親ストーリーの末尾にテキストを追加しました。
これは、テキストの長さやフォーマットによっては、テキストフレームの末尾がストーリーの末尾ではない
ことがあるからです。 親ストーリーの末尾にテキストを追加することによって、テキストフレームの状態に
関係なく、確実にテキストが追加されるようにしています。
テキストフレームの親ストーリーを取得するには、テキストフレームの parentTextFrame
プロパティを使用
します。 多くの場合、テキストフレームのテキストを操作するよりも、ストーリーのテキストを操作するほ
うが便利です。この違いを次のスクリプトに示します。 表示される警告を見ると、テキストフレームには
オーバーセットテキストが含まれておらず、ストーリーには含まれていることがわかります(完全なスクリ
プトについては、StoryAndTextFrame を参照してください)。
第 6 章 テキストと組版 テキストの入力と読み込み 82 var myDocument = app.activeDocument;
//Set the measurement units to points.
myDocument.viewPreferences.horizontalMeasurementUnits = MeasurementUnits.points; myDocument.viewPreferences.verticalMeasurementUnits = MeasurementUnits.points;
//Create a text frame on the current page.
var myTextFrame = app.activeWindow.activePage.textFrames.add();
//Set the bounds of the text frame.
myTextFrame.geometricBounds = [72, 72, 96, 288];
//Fill the text frame with placeholder text.
myTextFrame.contents = TextFrameContents.placeholderText;
//Now add text beyond the end of the text frame.
myTextFrame.insertionPoints.item(-1).contents = "¥rThis is some overset text"; alert("The last paragraph in this alert should be ¥"This is some overset text¥". Is it?¥r" + myTextFrame.contents); alert("The last paragraph in this alert should be ¥"This is some overset text¥". Is it?¥r" + myTextFrame.parentStory.contents);
InDesign ドキュメントの中にあるテキストオブジェクトの関係について詳しくは、 90 ページの「テキストオ
を参照してください。
テキストの置換
次のスクリプトでは、適当なオブジェクトの内容を変更することで、1 つの単語をある語句に置換していま
す(完全なスクリプトについては、ReplaceWord を参照してください)。 var myDocument = app.activeDocument;
//Set the measurement units to points.
myDocument.viewPreferences.horizontalMeasurementUnits = MeasurementUnits.points; myDocument.viewPreferences.verticalMeasurementUnits = MeasurementUnits.points;
//Create a text frame on the current page.
var myTextFrame = app.activeWindow.activePage.textFrames.add({geometricBounds:[72, 72, 288, 288], contents:"This is some example text."});
//Replace the third word "some" with the phrase
//"a little bit of".
myTextFrame.parentStory.words.item(2).contents = "a little bit of";
次のスクリプトでは、段落内のテキストを置換しています(完全なスクリプトについては、ReplaceText を参
照してください)。
//Replace the text in the second paragraph without replacing
//the return character at the end of the paragraph. To do this,
//we'll use the ItemByRange method.
var myStartCharacter = myTextFrame.parentStory.paragraphs.item(1).characters.item(0); var myEndCharacter = myTextFrame.parentStory.paragraphs.item(1).characters.item(-2); myTextFrame.texts.itemByRange(myStartCharacter, myEndCharacter).contents = "This text replaces the text in paragraph 2."
このスクリプトでは、改行文字を除外しています。改行を削除してしまうと、段落に適用されている段落ス
タイルが変更される可能性があるからです。 したがって、
ItemByRange
メソッドを使用して、そのパラメー
ターに 2 つの文字(段落の先頭の文字と、末尾の文字(改行文字)の直前にある文字)を指定しています。
特殊文字の挿入
ExtendScript Toolkit では Unicode がサポートされているので、InDesign に渡すテキスト文字列に Unicode 文字
を簡単に入力できます。 JavaScript では、Unicode 文字の字形の識別番号を指定する
¥unnnn
という表記法
(
nnnn
は、目的の文字の Unicode コード)を使用することもできます。
つかの方法で入力しています (ここでは、 myGetBounds
関数は省略しています。この関数については、
または SpecialCharacters というチュートリアルスクリプトを参照し
てください)。
第 6 章 テキストと組版 テキストの配置とテキスト読み込み環境設定の指定 83 var myDocument = app.documents.item(0);
//Create a text frame on the current page.
var myTextFrame = myDocument.pages.item(0).textFrames.add();
//Set the bounds of the text frame.
myTextFrame.geometricBounds = myGetBounds(myDocument, myDocument.pages.item(0));
//Entering special characters directly.
myTextFrame.contents = "Registered trademark: ®¥rCopyright: ©¥rTrademark: ™¥r";
//Entering special characters by their Unicode glyph ID value: myTextFrame.parentStory.insertionPoints.item(-1).contents = "Not equal to: ¥u2260¥rSquare root:
¥u221A¥rParagraph: ¥u00B6¥r";
//Entering InDesign special characters by their enumerations: myTextFrame.parentStory.insertionPoints.item(-1).contents = "Automatic page number marker:"; myTextFrame.parentStory.insertionPoints.item(-1).contents = SpecialCharacters.autoPageNumber; myTextFrame.parentStory.insertionPoints.item(-1).contents = "¥r"; myTextFrame.parentStory.insertionPoints.item(-1).contents = "Section symbol:"; myTextFrame.parentStory.insertionPoints.item(-1).contents = SpecialCharacters.sectionSymbol; myTextFrame.parentStory.insertionPoints.item(-1).contents = "¥r"; myTextFrame.parentStory.insertionPoints.item(-1).contents = "En dash:"; myTextFrame.parentStory.insertionPoints.item(-1).contents = SpecialCharacters.enDash; myTextFrame.parentStory.insertionPoints.item(-1).contents = "¥r";
特定の文字の Unicode ID を調べたい場合は、InDesign の字形パレットを使用するのが最も簡単です。 パレッ
ト内で文字の上にカーソルを移動すると、その文字の Unicode 値が表示されます。 Unicode について詳しく
は、 http://www.unicode.org
を参照してください。
テキストの配置とテキスト読み込み環境設定の指定
テキスト文字列の入力だけでなく、ワードプロセッサーやテキストエディターで作成したテキストファイル
を配置することもできます。 ドキュメントページにテキストファイルを配置する方法を、次のスクリプトに
示します(完全なスクリプトについては、PlaceTextFile を参照してください)。 var myDocument = app.documents.item(0);
//Set the measurement units to points.
myDocument.viewPreferences.horizontalMeasurementUnits = MeasurementUnits.points; myDocument.viewPreferences.verticalMeasurementUnits = MeasurementUnits.points;
//Get the current page.
var myPage = myDocument.pages.item(0);
//Get the top and left margins to use as a place point.
var myX = myPage.marginPreferences.left; var myY = myPage.marginPreferences.top;
//Autoflow a text file on the current page.
//Parameters for Page.place():
//File as File object,
//[PlacePoint as Array [x, y]]
//[DestinationLayer as Layer object]
//[ShowingOptions as Boolean = False]
//[Autoflowing as Boolean = False]
//You'll have to fill in your own file path.
var myStory = myPage.place(File("/c/test.txt"), [myX, myY], undefined, false, true)[0];
//Note that if the PlacePoint parameter is inside a column, only the vertical (y)
//coordinate will be honored--the text frame will expand horizontally to fit the column.
既存のテキストフレームにテキストファイルを配置する方法を、次のスクリプトに示します (ここでは、 myGetBounds
関数は省略しています。この関数については、 80 ページの「テキストフレームの作成」
または
第 6 章 テキストと組版 テキストの配置とテキスト読み込み環境設定の指定 84 var myDocument = app.documents.item(0); var myPage = myDocument.pages.item(0); var myTextFrame = myPage.textFrames.add({geometricBounds:myGetBounds(myDocument,myPage)});
//Place a text file in the text frame.
//Parameters for TextFrame.place():
//File as File object,
//[ShowingOptions as Boolean = False]
//You'll have to fill in your own file path.
myTextFrame.place(File("/c/test.txt"));
テキスト内の特定の場所にテキストファイルを挿入する方法を、次のスクリプトに示します (ここでは、 myGetBounds
関数は省略しています。この関数については、 80 ページの「テキストフレームの作成」
または var myDocument = app.documents.item(0); var myPage = myDocument.pages.item(0); var myTextFrame = myPage.textFrames.item(0);
//Place a text file at the end of the text.
//Parameters for InsertionPoint.place():
//File as File object,
//[ShowingOptions as Boolean = False]
//You'll have to fill in your own file path.
myTextFrame.parentStory.insertionPoints.item(-1).place(File("/c/test.txt"));
配置するテキストファイルの種類に応じた読み込みオプションを指定するには、対応する読み込み環境設定
オブジェクトを使用します。 テキスト読み込み環境設定の指定方法を、次のスクリプトに示します(完全な
スクリプトについては、TextImportPreferences を参照してください)。 スクリプトのコメントに、各プロパ
ティに指定可能な値を示します。 with(app.textImportPreferences){
//Options for characterSet: TextImportCharacterSet.
characterSet = TextImportCharacterSet.UTF8; convertSpacesIntoTabs = true; spacesIntoTabsCount = 3;
//The dictionary property can take many values, such as French, Italian.
dictionary = "English: USA";
//platform options: ImportPlatform platform = ImportPlatform.macintosh; stripReturnsBetweenLines = true; stripReturnsBetweenParagraphs = true; useTypographersQuotes = true;
}
タグ付きテキスト読み込み環境設定の指定方法を、次のスクリプトに示します(完全なスクリプトについて
は、TaggedTextImportPreferences を参照してください)。 with(app.taggedTextImportPreferences){ removeTextFormatting = false;
//styleConflict property can be:
//StyleConflict.publicationDefinition
//StyleConflict.tagFileDefinition
styleConflict = StyleConflict.publicationDefinition; useTypographersQuotes = true;
}
Word および RTF 読み込み環境設定の指定方法を、次のスクリプトに示します(完全なスクリプトについて
は、WordRTFImportPreferences を参照してください)。
第 6 章 テキストと組版 テキストの書き出しとテキスト書き出し環境設定の指定 85 with(app.wordRTFImportPreferences){
//convertPageBreaks property can be:
//ConvertPageBreaks.columnBreak
//ConvertPageBreaks.none
//ConvertPageBreaks.pageBreak
convertPageBreaks = ConvertPageBreaks.none;
//convertTablesTo property can be:
//ConvertTablesOptions.unformattedTabbedText
//ConvertTablesOptions.unformattedTable
convertTablesTo = ConvertTablesOptions.unformattedTable; importEndnotes = true; importFootnotes = true; importIndex = true; importTOC = true; importUnusedStyles = false; preserveGraphics = false; preserveLocalOverrides = false; preserveTrackChanges = false; removeFormatting = false;
//resolveCharacterSytleClash and resolveParagraphStyleClash properties can be:
//ResolveStyleClash.resolveClashAutoRename
//ResolveStyleClash.resolveClashUseExisting
//ResolveStyleClash.resolveClashUseNew
resolveCharacterStyleClash = ResolveStyleClash.resolveClashUseExisting; resolveParagraphStyleClash = ResolveStyleClash.resolveClashUseExisting; useTypographersQuotes = true;
}
Excel 読み込み環境設定の指定方法を、次のスクリプトに示します(完全なスクリプトについては、 with(app.excelImportPreferences){
//alignmentStyle property can be:
//AlignmentStyleOptions.centerAlign
//AlignmentStyleOptions.leftAlign
//AlignmentStyleOptions.rightAlign
//AlignmentStyleOptions.spreadsheet
alignmentStyle = AlignmentStyleOptions.spreadsheet; decimalPlaces = 4; preserveGraphics = false;
//Enter the range you want to import as "start cell:end cell".
rangeName = "A1:B16"; sheetIndex = 1; sheetName = "pathpoints"; showHiddenCells = false;
//tableFormatting property can be:
//TableFormattingOptions.excelFormattedTable
//TableFormattingOptions.excelUnformattedTabbedText
//TableFormattingOptions.excelUnformattedTable
tableFormatting = TableFormattingOptions.excelFormattedTable; useTypographersQuotes = true; viewName = "";
}
テキストの書き出しとテキスト書き出し環境設定の指定
で書き出すには、テキストオブジェクトやストーリーオブジェクトを使用する必要があることに注意してく
ださい。1 つの操作でドキュメント内のすべてのテキストを書き出すことはできません (ここでは、 myGetBounds
関数は省略しています。この関数については、 80 ページの「テキストフレームの作成」
または
第 6 章 テキストと組版 テキストの書き出しとテキスト書き出し環境設定の指定 86 var myDocument = app.documents.item(0); var myPage = myDocument.pages.item(0); var myTextFrame = myPage.textFrames.item(0);
//Text exportFile method parameters:
//Format as ExportFormat
//To As File
//[ShowingOptions As Boolean = False]
//Format parameter can be:
//ExportFormat.inCopy
//ExportFormat.inCopyCS2Story
//ExportFormat.rtf
//ExportFormat.taggedText
//ExportFormat.textType
//Export the story as text. You'll have to fill in a valid file path on your system.
myTextFrame.parentStory.exportFile(ExportFormat.textType, File("/c/test.txt"));
指定したテキスト範囲を書き出す方法を、次の例に示します (ここでは、 myGetBounds
関数は省略していま
リアルスクリプトを参照してください)。 var myDocument = app.documents.item(0); var myStory = myDocument.stories.item(0); var myStart = myStory.characters.item(0); var myEnd = myStory.paragraphs.item(0).characters.item(-1); myText = myStory.texts.itemByRange(myStart, myEnd);
//Text exportFile method parameters:
//Format as ExportFormat
//To As File
//[ShowingOptions As Boolean = False]
//Format parameter can be:
//ExportFormat.inCopy
//ExportFormat.inCopyCS2Story
//ExportFormat.rtf
//ExportFormat.taggedText
//ExportFormat.textType
//Export the text range. You'll have to fill in a valid file path on your system.
myText.exportFile(ExportFormat.textType, File("/c/test.txt"));
書き出すテキストファイルの種類に応じた書き出しオプションを指定するには、対応する書き出し環境設定
オブジェクトを使用します。 テキスト書き出し環境設定を指定する方法を、次のスクリプトに示します(完
全なスクリプトについては、TextExportPreferences を参照してください)。 with(app.textExportPreferences){
//Options for characterSet: TextExportCharacterSet characterSet = TextExportCharacterSet.UTF8;
//platform options: ImportPlatform platform = ImportPlatform.macintosh;
}
タグ付きテキスト書き出し環境設定を指定する方法を、次のスクリプトに示します(完全なスクリプトにつ
いては、TaggedTextExportPreferences を参照してください)。 with(app.taggedTextExportPreferences){
//Options for characterSet:
//TagTextExportCharacterSet.ansi
//TagTextExportCharacterSet.ascii
//TagTextExportCharacterSet.gb18030
//TagTextExportCharacterSet.ksc5601
//TagTextExportCharacterSet.shiftJIS
//TagTextExportCharacterSet.unicode
characterSet = TagTextExportCharacterSet.unicode;
//tagForm options:
//TagTextForm.abbreviated
//TagTextForm.verbose
tagForm = TagTextForm.verbose;
}
第 6 章 テキストと組版 テキストの書き出しとテキスト書き出し環境設定の指定 87
ドキュメント内のすべてのテキストを 1 ステップの操作で書き出すことはできません。 すべてのテキストを
まとめたい場合は、ドキュメント内のテキストを 1 つのストーリーに結合してからそのストーリーを書き出
すか、または、生成された複数のファイルをスクリプトで読み込んで 1 つのファイルに書き出す必要があり
ます。 次のスクリプトでは、前者の方法を使用しています (ここでは、 myGetBounds
関数は省略しています。
または ExportAllText というチュートリアルス
クリプトを参照してください)。 書き出す形式が単純なテキスト形式でない場合、後者の方法はかなり複雑に
なることがあります。 if(app.documents.length != 0){ if(app.documents.item(0).stories.length != 0){ myExportAllText(app.documents.item(0).name);
}
}
このスクリプトで参照されている ExportAllText 関数を次に示します。 function myExportAllText(myDocumentName){ var myStory;
//File name for the exported text. Fill in a valid file path on your system.
var myFileName = "/c/test.txt";
//If you want to add a separator line between stories, set myAddSeparator to true.
var myAddSeparator = true; var myNewDocument = app.documents.add(); var myDocument = app.documents.item(myDocumentName); var myTextFrame = myNewDocument.pages.item(0).textFrames.add(
{geometricBounds:myGetBounds(myNewDocument, myNewDocument.pages.item(0))}); var myNewStory = myTextFrame.parentStory; for(myCounter = 0; myCounter < myDocument.stories.length; myCounter++){ myStory = myDocument.stories.item(myCounter);
//Export the story as tagged text.
myStory.exportFile(ExportFormat.taggedText, File(myFileName));
//Import (place) the file at the end of the temporary story.
myNewStory.insertionPoints.item(-1).place(File(myFileName));
//If the imported text did not end with a return, enter a return
//to keep the stories from running together.
if(myCounter != myDocument.stories.length -1){ if(myNewStory.characters.item(-1).contents != "¥r"){ myNewStory.insertionPoints.item(-1).contents = "¥r";
} if(myAddSeparator == true){ myNewStory.insertionPoints.item(-1).contents =
"----------------------------------------¥r";
}
}
} myNewStory.exportFile(ExportFormat.taggedText, File("/c/test.txt")); myNewDocument.close(SaveOptions.no);
}
既存の書き出しフィルターを使用しないでテキストを書き出すこともできます。 JavaScript には、テキスト
ファイルをディスクに書き出す機能が用意されています。この機能を利用すれば、スクリプトでドキュメン
ト内のテキストをスキャンして、任意のテキストマークアップスキームを使用して任意の順序でテキストを
書き出すことができます。 HTML 形式で InDesign テキストを書き出す簡単な例を次に示します (ここでは、 myGetBounds
関数は省略しています。この関数については、 80 ページの「テキストフレームの作成」
または
第 6 章 テキストと組版 テキストの書き出しとテキスト書き出し環境設定の指定 88 var myStory, myParagraph, myString, myTag, myStartTag; var myEndTag, myTextStyleRange, myTable;
//Use the myStyleToTagMapping array to set up your paragraph style to tag mapping.
var myStyleToTagMapping = new Array;
//For each style to tag mapping, add a new item to the array.
myStyleToTagMapping.push(["body_text", "p"]); myStyleToTagMapping.push(["heading1", "h1"]); myStyleToTagMapping.push(["heading2", "h2"]); myStyleToTagMapping.push(["heading3", "h3"]);
//End of style to tag mapping.
if(app.documents.length !=0){ if(app.documents.item(0).stories.length != 0){
//Open a new text file.
var myTextFile = File.saveDialog("Save HTML As", undefined);
//If the user clicked the Cancel button, the result is null.
if(myTextFile != null){
//Open the file with write access.
myTextFile.open("w");
//Iterate through the stories.
for(var myCounter = 0; myCounter < app.documents.item(0).stories.length; myCounter ++){ myStory = app.documents.item(0).stories.item(myCounter); for(var myParagraphCounter = 0; myParagraphCounter < myStory.paragraphs.length; myParagraphCounter ++){ myParagraph = myStory.paragraphs.item(myParagraphCounter); if(myParagraph.tables.length == 0){ if(myParagraph.textStyleRanges.length == 1){
//If the paragraph is a simple paragraph--no tables, no local
//formatting--then simply export the text of the pararaph with
//the appropriate tag.
myTag = myFindTag(myParagraph.appliedParagraphStyle.name, myStyleToTagMapping);
//If the tag comes back empty, map it to the
//basic paragraph tag.
if(myTag == ""){ myTag = "p";
} myStartTag = "<" + myTag + ">"; myEndTag = "</" + myTag + ">";
//If the paragraph is not the last paragraph in the story,
//omit the return character.
if(myParagraph.characters.item(-1).contents == "¥r"){ myString = myParagraph.texts.itemByRange( myParagraph.characters.item(0),myParagraph.
characters.item(-2)).contents;
} else{ myString = myParagraph.contents;
}
//Write the paragraphs' text to the text file.
myTextFile.writeln(myStartTag + myString + myEndTag);
} else{
//Handle text style range export by iterating through the text
//style ranges in the paragraph..
for(var myRangeCounter = 0; myRangeCounter < myParagraph.textStyleRanges.length; myRangeCounter ++){ myTextStyleRange = myParagraph.textStyleRanges.item
(myRangeCounter); if(myTextStyleRange.characters.item(-1)=="¥r"){ myString = myTextStyleRange.texts.itemByRange( myTextStyleRange.characters.item(1), myTextStyleRange.characters.item(-2)).contents;
} else{ myString = myTextStyleRange.contents;
第 6 章 テキストと組版 テキストの書き出しとテキスト書き出し環境設定の指定 89
} switch(myTextStyleRange.fontStyle){ case "Bold": myString = "<b>" + myString + "</b>" break; case "Italic": myString = "<i>" + myString + "</i>" break;
} myTextFile.write(myString);
} myTextFile.write("¥r");
}
} else{
//Handle table export (assumes that there is only one table per
//paragraph, and that the table is in the paragraph by itself).
myTable = myParagraph.tables.item(0); myTextFile.writeln("<table border = 1>"); for(var myRowCounter = 0; myRowCounter < myTable.rows.length; myRowCounter ++){ myTextFile.writeln("<tr>"); for(var myColumnCounter = 0; myColumnCounter < myTable.columns.length; myColumnCounter++){ if(myRowCounter == 0){ myString = "<th>" + myTable.rows.item(myRowCounter).cells.
item(myColumnCounter).texts.item(0).contents + "</th>";
} else{ myString = "<td>" + myTable.rows.item(myRowCounter).
cells.item(myColumnCounter).texts.item(0).contents +
"</td>";
} myTextFile.writeln(myString);
} myTextFile.writeln("</tr>");
} myTextFile.writeln("</table>");
}
}
}
//Close the text file.
myTextFile.close();
}
}
}
このスクリプトで参照されている myFindTag
関数を次に示します。 function myFindTag (myStyleName, myStyleToTagMapping){ var myTag = ""; var myDone = false; var myCounter = 0; do{ if(myStyleToTagMapping[myCounter][0] == myStyleName){ myTag = myStyleToTagMapping[myCounter][1]; break;
} myCounter ++;
} while((myDone == false)||(myCounter < myStyleToTagMapping.length)) return myTag;
}
第 6 章 テキストと組版 テキストオブジェクト 90
テキストオブジェクト
次の図は、InDesign のテキストオブジェクトモデルを図式化したものです。 この図にもあるように、テキス
トオブジェクトには レイアウトオブジェクト(テキストフレーム)とテキストストリームオブジェクト(ス
トーリー、挿入点、文字、単語など)の 2 つの種類があります。 document story spread, page, layer insertion points characters words lines paragraphs text columns text style ranges texts notes text containers text frame insertion points characters words lines paragraphs text columns text style ranges texts notes
特定のテキストオブジェクトへの参照を取得するには、様々な方法があります。 次の図に、新規ドキュメン
トの最初のページの最初のテキストフレームにある最初の文字を参照する方法をいくつか示します。
第 6 章 テキストと組版 テキストオブジェクト 91 document pages.item(0) textFrames.item(0) characters.item(0) textFrames.item(0) paragraphs.item(0) characters.item(0) stories.item(0) characters.item(0) stories.item(0) paragraphs.item(0) characters.item(0)
テキストストリームオブジェクトの parent
は、そのオブジェクトが含まれているストーリーです。
オブジェクトが含まれているテキストフレーム(またはテキストフレームのコレクション)への参照を取得
するには、 parentTextFrames
プロパティを使用します。
テキストフレームの parent
は、通常、そのテキストフレームが含まれているページまたはスプレッドです。
グループ内にあるテキストフレームや、別のページアイテム内にペーストされたテキストフレームの parent
は、そのテキストフレームが含まれているページアイテムです。 アンカー付きフレームに変換されたテキス
トフレームの parent
は、そのアンカー付きフレームが含まれている文字です。
テキスト選択の操作
テキスト関連のスクリプトでよく行われる操作の 1 つが、テキスト選択に対する操作です。 現在の選択がテ
キスト選択かどうかを調べる方法を、次のスクリプトに示します。 他の多くのサンプルスクリプトと異なり、
このスクリプトは実際には何も行いません。このスクリプトでは、選択をフィルタリングする方法のみが示
されています(完全なスクリプトについては、TextSelection を参照してください)。 if (app.documents.length != 0){
//If the selection contains more than one item, the selection
//is not text selected with the Type tool.
if (app.selection.length == 1){
//Evaluate the selection based on its type.
switch (app.selection[0].constructor.name){ case "InsertionPoint": case "Character": case "Word": case "TextStyleRange": case "Line": case "Paragraph": case "TextColumn": case "Text": case "Story":
//The object is a text object; pass it on to a function.
myProcessText(app.selection[0]); break;
//In addition to checking for the above text objects, we can
//also continue if the selection is a text frame selected with
第 6 章 テキストと組版 テキストオブジェクト 92
}
//the Selection tool or the Direct Selection tool.
case "TextFrame":
//If the selection is a text frame, get a reference to the
//text in the text frame.
myProcessText(app.selection[0].texts.item(0)); break; default: alert("The selected object is not a text object.
Select some text and try again."); break;
}
} else{ alert("Please select some text and try again.");
}
テキストの移動とコピー
move
テキ
ストをコピーするには、 duplicate
メソッドを使用します(パラメーターは move
メソッドと同じです)
スクリプトにその例を示します(完全なスクリプトについては、MoveText を参照してください)。 var myDocument = app.documents.item(0); var myPage = myDocument.pages.item(0); var myTextFrameA = myPage.textFrames.item(3); var myTextFrameB = myPage.textFrames.item(2); var myTextFrameC = myPage.textFrames.item(1); var myTextFrameD = myPage.textFrames.item(0);
//Move WordC between the words in TextFrameC.
myTextFrameD.parentStory.paragraphs.item(-1).words.item(0).move(LocationOptions.before, myTextFrameC.parentStory.paragraphs.item(0).words.item(1))
//Move WordB after the word in TextFrameB.
myTextFrameD.parentStory.paragraphs.item(-2).words.item(0).move(LocationOptions.after, myTextFrameB.parentStory.paragraphs.item(0).words.item(0))
//Move WordA to before the word in TextFrameA.
myTextFrameD.parentStory.paragraphs.item(-3).words.item(0).move(LocationOptions.before, myTextFrameA.parentStory.paragraphs.item(0).words.item(0))
//Note that moving text removes it from its original location.
フォーマットされたテキストをドキュメント間で転送する場合にも、 move
して貼り付けるよりも、 move
メソッドや duplicate
メソッドを使用するほうが優れています。コピーして貼
り付けるためには、ドキュメントを表示して、コピーするテキストを選択しなければなりません。 move
や duplicate
を使用するほうが速くて確実です。 move
や duplicate
を使用して、ドキュメント間でテキストを
移動する方法を、次のスクリプトに示します (ここでは、 myGetBounds
関数は省略しています。この関数に
または MoveTextBetweenDocuments というチュートリア
ルスクリプトを参照してください)。
第 6 章 テキストと組版 テキストオブジェクト 93
//Create the source document.
var mySourceDocument = app.documents.add(); var mySourcePage = mySourceDocument.pages.item(0); var mySourceTextFrame = mySourcePage.textFrames.add({geometricBounds:myGetBounds(mySourceDocument, mySourcePage), contents:"This is the source text.¥rThis text is not the source text."}); var mySoureParagraph = mySourceTextFrame.parentStory.paragraphs.item(0); mySoureParagraph.pointSize = 24;
//Create the target document.
var myTargetDocument = app.documents.add(); var myTargetPage = myTargetDocument.pages.item(0); var myTargetTextFrame = myTargetPage.textFrames.add({geometricBounds:myGetBounds(myTargetDocument, myTargetDocument.pages.item(0)), contents:"This is the target text. Insert the source text before this paragraph.¥r"});
//Move the text from the source document to the target document.
//This deletes the text from the source document.
mySoureParagraph.move(LocationOptions.AT_BEGINNING, myTargetTextFrame.insertionPoints.item(0));
//To duplicate (rather than move) the text, use the following:
//mySoureParagraph.duplicate(LocationOptions.AT_BEGINNING, myTargetTextFrame.insertionPoints.item(0));
テキストをコピーして貼り付ける必要がある場合は、アプリケーションの copy
メソッドを使用できます。
の場合は、コピーする前にテキストを選択しておく必要があります。 繰り返しになりますが、コピーして貼
り付ける方法は最後の手段だと考えてください。他の方法を使用するほうが速くて確実であり、ドキュメン
トを表示する必要がありません (ここでは、 myGetBounds
関数は省略しています。この関数については、
または CopyPasteText というチュートリアルスクリプトを参照して
var myDocumentA = app.documents.add(); var myPageA = myDocumentA.pages.item(0); var myString = "Example text.¥r"; var myTextFrameA = myPageA.textFrames.add({geometricBounds:myGetBounds(myDocumentA, myPageA), contents:myString}); var myDocumentB = app.documents.add(); var myPageB = myDocumentB.pages.item(0); var myTextFrameB = myPageB.textFrames.add({geometricBounds:myGetBounds(myDocumentB, myPageB)});
//Make document A the active document.
app.activeDocument = myDocumentA;
//Select the text.
app.select(myTextFrameA.parentStory.texts.item(0)); app.copy();
//Make document B the active document.
app.activeDocument = myDocumentB;
//Select the insertion point at which you want to paste the text.
app.select(myTextFrameB.parentStory.insertionPoints.item(0)); app.paste();
フォーマットされていないテキストをテキストオブジェクト間でコピーする方法としては、コピーするテキ
ストオブジェクトの contents
プロパティを取得して、その文字列を別のテキストオブジェクトの contents
プロパティに設定する方法があります。 次のスクリプトにその例を示します(完全なスクリプトについては、
第 6 章 テキストと組版 テキストオブジェクト 94 var myDocument = app.documents.item(0); var myPage = myDocument.pages.item(0);
//Create a text frame on the active page.
var myTextFrameA = myPage.textFrames.add({geometricBounds:[72, 72, 144, 288]}); myTextFrameA.contents = "This is a formatted string."; myTextFrameA.parentStory.texts.item(0).fontStyle = "Bold";
//Create another text frame on the active page.
var myTextFrameB = myPage.textFrames.add({geometricBounds:[228, 72, 300, 288]}); myTextFrameB.contents = "This is the destination text frame. Text pasted here will retain its formatting."; myTextFrameB.parentStory.texts.item(0).fontStyle = "Italic";
//Copy from one frame to another using a simple copy.
app.select(myTextFrameA.texts.item(0)); app.copy(); app.select(myTextFrameB.parentStory.insertionPoints.item(-1)); app.paste();
//Create another text frame on the active page.
var myTextFrameC = myPage.textFrames.add({geometricBounds:[312, 72, 444, 288]}); myTextFrameC.contents = "Text copied here will take on the formatting of the existing text."; myTextFrameC.parentStory.texts.item(0).fontStyle = "Italic";
//Copy the unformatted string from text frame A to the end of text frame C (note
//that this doesn't really copy the text; it replicates the text string from one
//text frame in another text frame): myTextFrameC.parentStory.insertionPoints.item(-1).contents = myTextFrameA.parentStory.texts.item(0).contents;
テキストオブジェクトと反復処理
一連のテキストオブジェクトに対して繰り返して処理を行っている間に、テキストの移動、削除、追加を行
うと、テキスト参照に問題が発生することがあります。 このような問題が発生する例を、次のスクリプトに
示します (ここでは、 myGetBounds
関数は省略しています。この関数については、 80 ページの「テキストフ
レームの作成」 または TextIterationWrong というチュートリアルスクリプトを参照してください)。
var myDocument = app.documents.item(0); var myStory = myDocument.stories.item(0);
//The following for loop will fail to format all of the paragraphs.
for(var myParagraphCounter = 0; myParagraphCounter < myStory.paragraphs.length; myParagraphCounter ++){ if(myStory.paragraphs.item(myParagraphCounter).words.item(0).contents=="Delete"){ myStory.paragraphs.item(myParagraphCounter).remove();
} else{ myStory.paragraphs.item(myParagraphCounter).pointSize = 24;
}
}
この例では、フォーマットされない段落がいくつか発生することになります。 その理由は次のとおりです。 こ
のスクリプトのループは、ストーリー内の最初の段落から最後の段落まで、段落に対して繰り返し処理を行
が削除されると、第 3 段落がその場所に移動します。 次にループカウンターが 2 になると、先ほどまで第 4 段
落であった段落が処理されます。第 3 段落であった段落はこの時点で第 2 段落になっているので、処理は行
われません。
この問題を回避するには、次のスクリプトのように、テキストオブジェクトを逆順で処理します (ここで
は、 myGetBounds
関数は省略しています。この関数については、 80 ページの「テキストフレームの作成」
たは TextIterationRight というチュートリアルスクリプトを参照してください)。
第 6 章 テキストと組版 テキストフレームの操作 95 var myDocument = app.documents.item(0); var myStory = myDocument.stories.item(0);
//The following for loop will format all of the paragraphs by iterating
//backwards through the paragraphs in the story.
for(var myParagraphCounter = myStory.paragraphs.length-1; myParagraphCounter >= 0; myParagraphCounter --){ if(myStory.paragraphs.item(myParagraphCounter).words.item(0).contents=="Delete"){ myStory.paragraphs.item(myParagraphCounter).remove();
} else{ myStory.paragraphs.item(myParagraphCounter).pointSize = 24;
}
}
テキストフレームの操作
前の節ではテキストストリームオブジェクトの操作について説明しましたが、この節ではテキストフレーム
(InDesign ドキュメント内のテキストを格納するページレイアウトアイテム)について説明します。
テキストフレームのリンク
InDesign スクリプティングで、テキストフレームのリンクをたどっていく際に重要になるのが、テキストフ
レームの nextTextFrame
プロパティと previousTextFrame
プロパティです。
テキストフレームの入力ポートと出力ポートに相当します。次のスクリプトにその例を示します(完全なス
クリプトについては、LinkTextFrames を参照してください)。 var myDocument = app.documents.item(0); var myPage = myDocument.pages.item(0); var myTextFrameA = myPage.textFrames.item(1); var myTextFrameB = myPage.textFrames.item(0);
//Add a page.
var myNewPage = myDocument.pages.add();
//Create another text frame on the new page.
var myTextFrameC = myNewPage.textFrames.add({geometricBounds:[72, 72, 144, 144]})
//Link TextFrameA to TextFrameB using the nextTextFrame property.
myTextFrameA.nextTextFrame = myTextFrameB;
//Link TextFrameC to TextFrameB using the previousTextFrame property.
myTextFrameC.previousTextFrame = myTextFrameB;
//Fill the text frames with placeholder text.
myTextFrameA.contents = TextFrameContents.placeholderText;
テキストフレームのリンク解除
テキストフレームのリンクを解除する方法を、次のスクリプト例に示します(完全なスクリプトについては、
//Unlink the two text frames.
myTextFrameA.nextTextFrame = NothingEnum.nothing;
ストーリーからのフレームの削除
InDesign では、ストーリーからフレームを削除しても、フレーム内のテキストは削除されません(そのフ
特定のフレームとそこに含まれているテキストをストーリーから削除する方法を、次のスクリプトに示しま
す(完全なスクリプトについては、BreakFrame を参照してください)。
第 6 章 テキストと組版 テキストフレームの操作 96 var myObjectList = new Array;
//Script does nothing if no documents are open or if no objects are selected.
if(app.documents.length != 0){ if(app.selection.length != 0){
//Process the objects in the selection to create a list of
//qualifying objects (text frames).
for(myCounter = 0; myCounter < app.selection.length; myCounter ++){ switch(app.selection[myCounter].constructor.name){ case "TextFrame": myObjectList.push(app.selection[myCounter]); break; default: if(app.selection.length == 1){
//If text is selected, then get the parent text frame.
switch(app.selection[myCounter].constructor.name){ case "Text": case "InsertionPoint": case "Character": case "Word": case "Line": case "TextStyleRange": case "Paragraph": case "TextColumn": myObjectList.push(app.selection[myCounter].
parentTextFrames[0]); break;
}
} break;
}
}
//If the object list is not empty, pass it on to the function
//that does the real work.
if(myObjectList.length != 0){ myBreakFrames(myObjectList);
}
}
}
このスクリプトで参照されている myBreakFrames 関数を次に示します。 function myBreakFrames(myObjectList){ myObjectList.sort(myReverseSortByTextFrameIndex); for(var myCounter = 0; myCounter < myObjectList.length; myCounter ++){ myBreakFrame(myObjectList[myCounter]);
}
} function myBreakFrame(myTextFrame){ if((myTextFrame.nextTextFrame != null)&&(myTextFrame.previousTextFrame != null)){ var myNewFrame = myTextFrame.duplicate(); if(myTextFrame.contents != ""){ myTextFrame.texts.item(0).remove();
} myTextFrame.remove();
}
} function myReverseSortByTextFrameIndex(a,b){
//By combining the story id with the text frame index, we can sort the text frames
//into the right (reverse) order in a single pass.
$.write("padded a: " + myPadString(a.id, 8)+myPadString(a.textFrameIndex, 8));
$.write("padded b: " + myPadString(b.id, 8)+myPadString(b.textFrameIndex, 8)); if((myPadString(a.id, 8)+myPadString(a.textFrameIndex, 8)) >
(myPadString(b.id, 8)+myPadString(b.textFrameIndex, 8))){ return -1;
第 6 章 テキストと組版 テキストフレームの操作 97
} if((myPadString(a.id,8)+myPadString(a.textFrameIndex,8)) <
(myPadString(b.id,8)+myPadString(b.textFrameIndex,8))){ return 1;
} return 0;
} function myPadString(myString, myLength) {
var myTempString = "";
var myNewLength = myLength-String(myString).length;
for (var myCounter = 0; myCounter<myNewLength; myCounter++) {
myTempString += "0";
}
return myTempString + myString;
}
ストーリー内のすべてのフレームの分割
ストーリー内のすべてのフレームを独立した別個のストーリーに分割して、リンクされていないテキストフ
レームが各ストーリーに 1 つだけ含まれるようにする方法を、次のスクリプトに示します(完全なスクリプ
トについては、SplitStory を参照してください)。 if(app.documents.length != 0){ if(app.selection.length != 0){
//Get the first item in the selection.
var mySelection = app.selection[0];
//Process the selection. If text or a text frame is
//selected, do something; otherwise, do nothing.
switch(mySelection.constructor.name){ case "Text": case "InsertionPoint": case "Character": case "Word": case "Line": case "TextStyleRange": case "Paragraph": case "TextColumn": case "TextFrame":
//If the text frame is the only text frame in the story, do nothing.
if(mySelection.parentStory.textContainers.length != 1){
//Splitting the story is a two-step process: first, duplicate
//the text frames, second, delete the original text frames.
mySplitStory(mySelection.parentStory); myRemoveFrames(mySelection.parentStory);
} break;
}
}
}
このスクリプトで参照されている mySplitStory
関数を次に示します。
第 6 章 テキストと組版 テキストフレームの操作 98 function mySplitStory(myStory){ var myTextFrame;
//Duplicate each text frame in the story.
for(var myCounter = myStory.textContainers.length-1; myCounter >= 0; myCounter --){ myTextFrame = myStory.textContainers[myCounter];
myTextFrame.duplicate();
}
} function myRemoveFrames(myStory){
//Remove each text frame in the story. Iterate backwards to
//avoid invalid references.
for(var myCounter = myStory.textContainers.length-1; myCounter >= 0; myCounter --){ myStory.textContainers[myCounter].remove();
}
}
アンカー付きフレームの作成
アンカー付きフレーム(インラインフレームとも呼ばれます)を作成するには、テキストの特定の位置(通
常は挿入点)にテキストフレーム(または長方形、楕円形、多角形、グラフィックの線)を作成します。 次
のスクリプトにその例を示します(完全なスクリプトについては、AnchoredFrame を参照してください)。 var myInsertionPoint = myTextFrame.paragraphs.item(0).insertionPoints.item(0); var myInlineFrame = myInsertionPoint.textFrames.add();
//Recompose the text to make sure that getting the
//geometric bounds of the inline graphic will work.
myTextFrame.texts.item(0).recompose;
//Get the geometric bounds of the inline frame.
var myBounds = myInlineFrame.geometricBounds;
//Set the width and height of the inline frame. In this example, we'll
//make the frame 24 points tall by 72 points wide.
var myArray = [myBounds[0], myBounds[1], myBounds[0]+24, myBounds[1]+72]; myInlineFrame.geometricBounds = myArray; myInlineFrame.contents = "This is an inline frame."; myInsertionPoint = myTextFrame.paragraphs.item(1).insertionPoints.item(0); var myAnchoredFrame = myInsertionPoint.textFrames.add();
//Recompose the text to make sure that getting the
//geometric bounds of the inline graphic will work.
myTextFrame.texts.item(0).recompose;
//Get the geometric bounds of the inline frame.
var myBounds = myAnchoredFrame.geometricBounds;
//Set the width and height of the inline frame. In this example, we'll
//make the frame 24 points tall by 72 points wide.
myArray = [myBounds[0], myBounds[1], myBounds[0]+24, myBounds[1]+72]; myAnchoredFrame.geometricBounds = myArray; myAnchoredFrame.contents = "This is an anchored frame."; with(myAnchoredFrame.anchoredObjectSettings){ anchoredPosition = AnchorPosition.anchored; anchorPoint = AnchorPoint.topLeftAnchor; horizontalReferencePoint = AnchoredRelativeTo.anchorLocation; horizontalAlignment = HorizontalAlignment.leftAlign; anchorXoffset = 72; verticalReferencePoint = VerticallyRelativeTo.lineBaseline; anchorYoffset = 24; anchorSpaceAbove = 24;
}
第 6 章 テキストと組版 テキストのフォーマット 99
テキストフレームをコンテンツに合わせる
テキストフレームにルールを設定し、ユーザーのテキスト入力に応じてテキストフレームを伸縮させる方法
を、次のスクリプトに示します(完全なスクリプトについては、PersistedTextFrameFill を参照してください)。 var myDocument = app.documents.item(0); var myTextFrame = myDocument.pages.item(0).textFrames.item(3);
//Now add text at the end of the text frame.
myTextFrame.insertionPoints.item(-1).contents = "¥rThis is some overset text"; alert("The last paragraph in this alert should be ¥"This is some overset text¥". Is it?¥r"
+ myTextFrame.contents); alert("The last paragraph in this alert should be ¥"This is some overset text¥". Is it?¥r"
+ myTextFrame.parentStory.contents); var myTextFrame2 = myDocument.pages.item(0).textFrames.item(2);
//Set auto size dimension of the text frame with(myTextFrame2.textFramePreferences)
{ autoSizingDimension=AutoSizingDimension.HEIGHT_AND_WIDTH_PROPORTIONALLY;
}
//Now add text at the end of the text frame.
myTextFrame2.insertionPoints.item(-1).contents = "¥rThis is some overset text"; var myTextFrame3 = myDocument.pages.item(0).textFrames.item(1);
//Set auto size dimension of the text frame
//useMinimumHeightForAutoSizing and useNoLineBreaksForAutoSizing with(myTextFrame3.textFramePreferences)
{ autoSizingDimension=AutoSizingDimension.HEIGHT_ONLY; useMinimumHeightForAutoSizing=true useNoLineBreaksForAutoSizing=true
}
//Now add text at the end of the text frame.
myTextFrame3.insertionPoints.item(-1).contents = "¥rThis is some overset text"; var myTextFrame4 = myDocument.pages.item(0).textFrames.item(0);
//Set auto size dimension of the text frame and autoSizingReferencePoint with(myTextFrame4.textFramePreferences)
{ autoSizingDimension=AutoSizingDimension.WIDTH_ONLY; autoSizingReferencePoint=AutoSizingReferencePoint.TOP_LEFT_POSITION;
}
//Now add text at the end of the text frame.
myTextFrame4.insertionPoints.item(-1).contents = "¥rThis is some overset text";
テキストのフォーマット
この章の前の節では、ドキュメントにテキストを追加し、テキストフレームをリンクし、ストーリーやテキ
ストオブジェクトを操作しました。 この節では、テキストにフォーマットを適用します。 InDesign のすべての
フォーマット機能は、スクリプティングで操作することができます。
テキストデフォルトの設定
テキストデフォルトは、アプリケーションとドキュメントの両方で設定できます。 アプリケーションのテキ
ストデフォルトは、新しく作成されるすべてのドキュメントのテキストデフォルトとして使用されます。ド
キュメントのテキストデフォルトは、そのドキュメントで新しく作成されるすべてのテキストオブジェクト
のフォーマットとして使用されます (完全なスクリプトについては、TextDefaults を参照してください)。
第 6 章 テキストと組版 テキストのフォーマット 100 var myDocument = app.documents.item(0);
//To set the application text formatting defaults, replace the variable "myDocument"
//with "app" in the following lines.
with(myDocument.textDefaults){ alignToBaseline = true;
//Because the font might not be available, it's usually best
//to apply the font within a try...catch structure. Fill in the
//name of a font on your system.
try{ appliedFont = app.fonts.item("Minion Pro");
} catch(e){}
//Because the font style might not be available, it's usually best
//to apply the font style within a try...catch structure.
try{ fontStyle = "Regular";
} catch(e){}
//Because the language might not be available, it's usually best
//to apply the language within a try...catch structure.
try{ appliedLanguage = "English: USA";
} catch(e){} autoLeading = 100; balanceRaggedLines = false; baselineShift = 0; capitalization = Capitalization.normal; composer = "Adobe Paragraph Composer"; desiredGlyphScaling = 100; desiredLetterSpacing = 0; desiredWordSpacing = 100; dropCapCharacters = 0; if(dropCapCharacters != 0){ dropCapLines = 3;
//Assumes that the application has a default character style named "myDropCap" dropCapStyle = myDocument.characterStyles.item("myDropCap");
} fillColor = myDocument.colors.item("Black"); fillTint = 100; firstLineIndent = 14; gridAlignFirstLineOnly = false; horizontalScale = 100; hyphenateAfterFirst = 3; hyphenateBeforeLast = 4; hyphenateCapitalizedWords = false; hyphenateLadderLimit = 1; hyphenateWordsLongerThan = 5; hyphenation = true; hyphenationZone = 36; hyphenWeight = 9; justification = Justification.leftAlign; keepAllLinesTogether = false; keepLinesTogether = true; keepFirstLines = 2; keepLastLines = 2; keepWithNext = 0; kerningMethod = "Optical"; kerningValue = 0; leading = 14; leftIndent = 0; ligatures = true; maximumGlyphScaling = 100; maximumLetterSpacing = 0; maximumWordSpacing = 160; minimumGlyphScaling = 100;
第 6 章 テキストと組版 minimumLetterSpacing = 0; minimumWordSpacing = 80; noBreak = false; otfContextualAlternate = true; otfDiscretionaryLigature = false; otfFigureStyle = OTFFigureStyle.proportionalOldstyle; otfFraction = true; otfHistorical = false; otfOrdinal = false; otfSlashedZero = false; otfSwash = false; otfTitling = false; overprintFill = false; overprintStroke = false; pointSize = 11; position = Position.normal; rightIndent = 0; ruleAbove = false; if(ruleAbove == true){ ruleAboveColor = myDocument.colors.item("Black"); ruleAboveGapColor = myDocument.swatches.item("None"); ruleAboveGapOverprint = false; ruleAboveGapTint = 100; ruleAboveLeftIndent = 0; ruleAboveLineWeight = .25; ruleAboveOffset = 14; ruleAboveOverprint = false; ruleAboveRightIndent = 0; ruleAboveTint = 100; ruleAboveType = myDocument.strokeStyles.item("Solid"); ruleAboveWidth = RuleWidth.columnWidth;
} ruleBelow = false; if(ruleBelow == true){ ruleBelowColor = myDocument.colors.item("Black"); ruleBelowGapColor = myDocument.swatches.item("None"); ruleBelowGapOverprint = false; ruleBelowGapTint = 100; ruleBelowLeftIndent = 0; ruleBelowLineWeight = .25; ruleBelowOffset = 0; ruleBelowOverprint = false; ruleBelowRightIndent = 0; ruleBelowTint = 100; ruleBelowType = app.strokeStyles.item("Solid"); ruleBelowWidth = RuleWidth.columnWidth;
} singleWordJustification = SingleWordJustification.leftAlign; skew = 0; spaceAfter = 0; spaceBefore = 0; startParagraph = StartParagraph.anywhere; strikeThru = false; if(strikeThru == true){ strikeThroughColor = myDocument.colors.item("Black"); strikeThroughGapColor = myDocument.swatches.item("None"); strikeThroughGapOverprint = false; strikeThroughGapTint = 100; strikeThroughOffset = 3; strikeThroughOverprint = false; strikeThroughTint = 100; strikeThroughType = myDocument.strokeStyles.item("Solid"); strikeThroughWeight = .25;
}
テキストのフォーマット 101
第 6 章 テキストと組版 テキストのフォーマット 102
} strokeColor = myDocument.swatches.item("None"); strokeTint = 100; strokeWeight = 0; tracking = 0; underline = false; if(underline == true){ underlineColor = myDocument.colors.item("Black"); underlineGapColor = myDocument.swatches.item("None"); underlineGapOverprint = false; underlineGapTint = 100; underlineOffset = 3; underlineOverprint = false; underlineTint = 100; underlineType = myDocument.strokeStyles.item("Solid"); underlineWeight = .25
} verticalScale = 100;
フォントの操作
InDesign アプリケーションオブジェクトのフォントコレクションには、InDesign で利用できるすべてのフォ
ントが含まれています。 これとは対照的に、ドキュメントのフォントコレクションには、そのドキュメント
で使用されているフォントのみが含まれています。 ドキュメントのフォントコレクションには、環境に無い
フォント(ドキュメントで使用されているが InDesign では利用できないフォント)も含まれます。 アプリ
ケーションフォントとドキュメントフォントの違いを調べる方法を、次のスクリプトに示します (ここで
は、 myGetBounds
関数は省略しています。完全なスクリプトについては、FontCollections を参照してくださ var myApplicationFonts = app.fonts; var myDocument = app.documents.item(0); var myStory = myDocument.stories.item(0); var myDocumentFonts = myDocument.fonts; var myFontNames = myApplicationFonts.everyItem().name; var myDocumentFontNames = myDocument.fonts.everyItem().name; var myString = "Document Fonts:¥r"; for(var myCounter = 0;myCounter<myDocumentFontNames.length; myCounter++){ myString += myDocumentFontNames[myCounter] + "¥r";
} myString += "¥rApplication Fonts:¥r"; for(var myCounter = 0;myCounter<myFontNames.length; myCounter++){ myString += myFontNames[myCounter] + "¥r";
} myStory.contents = myString;
注意 : フォント名は通常、
familyName<tab>fontStyle
という形式で示されます。
familyName
はフォントファ
ミリー名、
<tab>
はタブ文字、
fontStyle
はフォントスタイル名です。
"Adobe Caslon Pro<tab>Semibold Italic"
フォントの適用
テキストのある範囲にローカルフォントを適用するには、 appliedFont
プロパティを使用します。次のスク
リプトにその例を示します(チュートリアルスクリプトの ApplyFont より)。
//Given a font name "myFontName" and a text object "myText"...
myText.appliedFont = app.fonts.item(myFontName);
また、次のスクリプトのように、フォントファミリー名とフォントスタイルを指定してフォントを適用する
こともできます。 myText.appliedFont = app.fonts.item("Adobe Caslon Pro"); myText.fontStyle = "Semibold Italic";
第 6 章 テキストと組版 テキストのフォーマット 103
テキストプロパティの変更
InDesign のテキストオブジェクトには、そのフォーマット属性に対応する多数のプロパティが用意されてい
ます。 単なる挿入点にも、テキストのフォーマットに影響を与える多数のプロパティ(その挿入点が含まれ
ている段落とほぼ同じプロパティ)が用意されています。 SetTextProperties というチュートリアルスクリプト
には、テキストオブジェクトのすべてのプロパティを設定する方法が示されています。 次のスクリプトにそ
の例を示します。 var myDocument = app.documents.item(0); var myPage = myDocument.pages.item(0); var myTextFrame = myPage.textFrames.add(); myTextFrame.contents = "x"; var myTextObject = myTextFrame.parentStory.characters.item(0); myTextObject.alignToBaseline = false; myTextObject.appliedCharacterStyle = myDocument.characterStyles.item("[None]"); myTextObject.appliedFont = app.fonts.item("Minion ProRegular"); myTextObject.appliedLanguage = app.languagesWithVendors.item("English: USA"); myTextObject.appliedNumberingList = myDocument.numberingLists.item("[Default]"); myTextObject.appliedParagraphStyle = myDocument.paragraphStyles.item("[No Paragraph Style]"); myTextObject.autoLeading = 120; myTextObject.balanceRaggedLines = BalanceLinesStyle.noBalancing; myTextObject.baselineShift = 0; myTextObject.bulletsAlignment = ListAlignment.leftAlign; myTextObject.bulletsAndNumberingListType = ListType.noList; myTextObject.bulletsCharacterStyle = myDocument.characterStyles.item("[None]"); myTextObject.bulletsTextAfter = "^t"; myTextObject.capitalization = Capitalization.normal; myTextObject.composer = "Adobe Paragraph Composer"; myTextObject.desiredGlyphScaling = 100; myTextObject.desiredLetterSpacing = 0; myTextObject.desiredWordSpacing = 100; myTextObject.dropCapCharacters = 0; myTextObject.dropCapLines = 0; myTextObject.dropCapStyle = myDocument.characterStyles.item("[None]"); myTextObject.dropcapDetail = 0; myTextObject.fillColor = myDocument.colors.item("Black"); myTextObject.fillTint = -1; myTextObject.firstLineIndent = 0; myTextObject.fontStyle = "Regular"; myTextObject.gradientFillAngle = 0; myTextObject.gradientFillLength = -1; myTextObject.gradientFillStart = [0,0]; myTextObject.gradientStrokeAngle = 0; myTextObject.gradientStrokeLength = -1; myTextObject.gradientStrokeStart = [0,0]; myTextObject.gridAlignFirstLineOnly = false; myTextObject.horizontalScale = 100; myTextObject.hyphenWeight = 5; myTextObject.hyphenateAcrossColumns = true; myTextObject.hyphenateAfterFirst = 2; myTextObject.hyphenateBeforeLast = 2; myTextObject.hyphenateCapitalizedWords = true; myTextObject.hyphenateLadderLimit = 3; myTextObject.hyphenateLastWord = true; myTextObject.hyphenateWordsLongerThan = 5; myTextObject.hyphenation = true; myTextObject.hyphenationZone = 3; myTextObject.ignoreEdgeAlignment = false; myTextObject.justification = Justification.leftAlign; myTextObject.keepAllLinesTogether = false; myTextObject.keepFirstLines = 2; myTextObject.keepLastLines = 2; myTextObject.keepLinesTogether = false; myTextObject.keepRuleAboveInFrame = false;
第 6 章 テキストと組版 テキストのフォーマット 104 myTextObject.keepWithNext = 0; myTextObject.kerningMethod = "Optical";
//myTextObject.kerningValue = error; myTextObject.lastLineIndent = 0; myTextObject.leading = 12; myTextObject.leftIndent = 0; myTextObject.ligatures = true; myTextObject.maximumGlyphScaling = 100; myTextObject.maximumLetterSpacing = 0; myTextObject.maximumWordSpacing = 133; myTextObject.minimumGlyphScaling = 100; myTextObject.minimumLetterSpacing = 0; myTextObject.minimumWordSpacing = 80; myTextObject.noBreak = false; myTextObject.numberingAlignment = ListAlignment.leftAlign; myTextObject.numberingApplyRestartPolicy = true; myTextObject.numberingCharacterStyle = myDocument.characterStyles.item("[None]"); myTextObject.numberingContinue = true; myTextObject.numberingExpression = "^#.^t"; myTextObject.numberingFormat = "1, 2, 3, 4..."; myTextObject.numberingLevel = 1; myTextObject.numberingStartAt = 1; myTextObject.otfContextualAlternate = true; myTextObject.otfDiscretionaryLigature = false; myTextObject.otfFigureStyle = OTFFigureStyle.proportionalLining; myTextObject.otfFraction = false; myTextObject.otfHistorical = false; myTextObject.otfLocale = true; myTextObject.otfMark = true; myTextObject.otfOrdinal = false; myTextObject.otfSlashedZero = false; myTextObject.otfStylisticSets = 0; myTextObject.otfSwash = false; myTextObject.otfTitling = false; myTextObject.overprintFill = false; myTextObject.overprintStroke = false; myTextObject.pointSize = 12; myTextObject.position = Position.normal; myTextObject.positionalForm = PositionalForms.none; myTextObject.rightIndent = 0; myTextObject.ruleAbove = false; myTextObject.ruleAboveColor = "Text Color"; myTextObject.ruleAboveGapColor = myDocument.swatches.item("None"); myTextObject.ruleAboveGapOverprint = false; myTextObject.ruleAboveGapTint = -1; myTextObject.ruleAboveLeftIndent = 0; myTextObject.ruleAboveLineWeight = 1; myTextObject.ruleAboveOffset = 0; myTextObject.ruleAboveOverprint = false; myTextObject.ruleAboveRightIndent = 0; myTextObject.ruleAboveTint = -1; myTextObject.ruleAboveType = myDocument.strokeStyles.item("Solid"); myTextObject.ruleAboveWidth = RuleWidth.columnWidth; myTextObject.ruleBelow = false; myTextObject.ruleBelowColor = "Text Color"; myTextObject.ruleBelowGapColor = myDocument.swatches.item("None"); myTextObject.ruleBelowGapOverprint = false; myTextObject.ruleBelowGapTint = -1; myTextObject.ruleBelowLeftIndent = 0; myTextObject.ruleBelowLineWeight = 1; myTextObject.ruleBelowOffset = 0; myTextObject.ruleBelowOverprint = false; myTextObject.ruleBelowRightIndent = 0; myTextObject.ruleBelowTint = -1;
第 6 章 テキストと組版 テキストのフォーマット 105 myTextObject.ruleBelowType = myDocument.strokeStyles.item("Solid"); myTextObject.ruleBelowWidth = RuleWidth.columnWidth; myTextObject.singleWordJustification = 1718971500; myTextObject.skew = 0; myTextObject.spaceAfter = 0; myTextObject.spaceBefore = 0; myTextObject.startParagraph = 1851945579; myTextObject.strikeThroughColor = "Text Color"; myTextObject.strikeThroughGapColor = myDocument.swatches.item("None"); myTextObject.strikeThroughGapOverprint = false; myTextObject.strikeThroughGapTint = -1; myTextObject.strikeThroughOffset = -9999; myTextObject.strikeThroughOverprint = false; myTextObject.strikeThroughTint = -1; myTextObject.strikeThroughType = myDocument.strokeStyles.item("Solid"); myTextObject.strikeThroughWeight = -9999; myTextObject.strikeThru = false; myTextObject.strokeColor = myDocument.swatches.item("None"); myTextObject.strokeTint = -1; myTextObject.strokeWeight = 1; myTextObject.tracking = 0; myTextObject.underline = false; myTextObject.underlineColor = "Text Color"; myTextObject.underlineGapColor = myDocument.swatches.item("None"); myTextObject.underlineGapOverprint = false; myTextObject.underlineGapTint = -1; myTextObject.underlineOffset = -9999; myTextObject.underlineOverprint = false; myTextObject.underlineTint = -1; myTextObject.underlineType = myDocument.strokeStyles.item("Solid"); myTextObject.underlineWeight = -9999; myTextObject.verticalScale = 100;
テキストカラーの変更
テキスト文字の塗りと線にカラーを適用できます。次のスクリプトにその例を示します(チュートリアルス
クリプトの TextColors より)。 var myColorA, myColorB, myName;
//Access the active document and page.
var myDocument = app.activeDocument; var myPage = app.activeWindow.activePage;
//Create a color.
try{ myColorA = myDocument.colors.item("DGC1_664a");
//If the color does not exist, trying to get its name will generate an error.
myName = myColorA.name;
} catch (myError){
//The color style did not exist, so create it.
myColorA = myDocument.colors.add({name:"DGC1_664a", model:ColorModel.process, colorValue:[90,
100, 70, 0]});
}
//Create another color.
try{ myColorB = myDocument.colors.item("DGC1_664b");
//If the color does not exist, trying to get its name will generate an error.
myName = myColorB.name;
} catch (myError){
//The color style did not exist, so create it.
myColorB = myDocument.colors.add({name:"DGC1_664b", model:ColorModel.process, colorValue:[70,
0, 30, 50]});
}
第 6 章 テキストと組版 テキストのフォーマット 106
//Create a text frame on the active page.
var myTextFrame = myPage.textFrames.add();
//Set the bounds of the text frame.
myTextFrame.geometricBounds = myGetBounds(myDocument, myPage);
//Enter text in the text frame.
myTextFrame.contents = "Text¥rColor" var myText = myTextFrame.parentStory.paragraphs.item(0) myText.pointSize = 72; myText.justification = Justification.centerAlign;
//Apply a color to the fill of the text.
myText.fillColor = myColorA;
//Use the itemByRange method to apply the color to the stroke of the text.
myText.strokeColor = myColorB; var myText = myTextFrame.parentStory.paragraphs.item(1) myText.strokeWeight = 3; myText.pointSize = 144; myText.justification = Justification.centerAlign; myText.fillColor = myColorB; myText.strokeColor = myColorA; myText.strokeWeight = 3;
スタイルの作成と適用
前述のいくつかの例でローカルフォーマットを適用する方法を示しましたが、ここでは、文字スタイルや段
落スタイルを使用してテキストをフォーマットする方法について説明します。 スタイルを使用すると、
フォーマットされたテキストとスタイルの間にリンクが作成されます。そのため、スタイルの再定義、特定
のスタイルでフォーマットされたテキストの収集、テキストの検索や変更などが簡単に行えます。 段落スタ
イルや文字スタイルは、テキストのフォーマット作業を効率化する上で重要な役割を果たします。段落と文
字スタイルはテキストにフォーマットを設定する場合に生産性の鍵となるものであり、テキストにフォー
マットを適用するどんなスクリプトにとっても中心的な存在になるはずです。
段落スタイルや文字スタイルを作成して適用する方法を、次のスクリプトに示します(完全なスクリプトに
ついては、CreateStyles を参照してください)。 var myDocument = app.documents.item(0); var myPage = myDocument.pages.item(0);
//Create a color for use by one of the paragraph styles we'll create.
try{ myColor = myDocument.colors.item("Red");
//If the color does not exist, trying to get its name will generate an error.
myName = myColor.name;
} catch (myError){
//The color style did not exist, so create it.
myColor = myDocument.colors.add({name:"Red", model:ColorModel.process, colorValue:[0, 100,
100, 0]});
}
//Create a text frame on the active page.
var myTextFrame = myPage.textFrames.add();
//Set the bounds of the text frame.
myTextFrame.geometricBounds = myGetBounds(myDocument, myPage);
//Fill the text frame with placeholder text.
myTextFrame.contents = "Normal text. Text with a character style applied to it. More normal text.";
//Create a character style named "myCharacterStyle" if
//no style by that name already exists.
try{ myCharacterStyle = myDocument.characterStyles.item("myCharacterStyle");
//If the style does not exist, trying to get its name will generate an error.
myName = myCharacterStyle.name;
} catch (myError){
//The style did not exist, so create it.
第 6 章 テキストと組版 テキストのフォーマット 107 myCharacterStyle = myDocument.characterStyles.add({name:"myCharacterStyle"});
}
//At this point, the variable myCharacterStyle contains a reference to a character
//style object, which you can now use to specify formatting.
myCharacterStyle.fillColor = myColor;
//Create a paragraph style named "myParagraphStyle" if
//no style by that name already exists.
try{ myParagraphStyle = myDocument.paragraphStyles.item("myParagraphStyle");
//If the paragraph style does not exist, trying to get its name will generate an error.
myName = myParagraphStyle.name;
} catch (myError){
//The paragraph style did not exist, so create it.
myParagraphStyle = myDocument.paragraphStyles.add({name:"myParagraphStyle"});
}
//At this point, the variable myParagraphStyle contains a reference to a paragraph
//style object, which you can now use to specify formatting.
myTextFrame.parentStory.texts.item(0).applyParagraphStyle(myParagraphStyle, true); var myStartCharacter = myTextFrame.parentStory.characters.item(13); var myEndCharacter = myTextFrame.parentStory.characters.item(54); myTextFrame.parentStory.texts.itemByRange(myStartCharacter, myEndCharacter).applyParagraphStyle(myParagraphStyle, true);
テキストオブジェクトの appliedParagraphStyle
プロパティを使用せずに applyParagraphStyle
メソッドを
使用する利点は、 既存のフォーマットをオーバーライドできる点にあります。スタイルにプロパティを設定
しても、ローカルフォーマットは変更されずに保持されます。
新規ドキュメントの作成時に、スタイルが存在するかどうかを確認しているのは、 アプリケーションのデ
フォルトスタイルとして同じ名前のスタイルが存在している可能性があるからです。 その場合、同じ名前で
新しいスタイルを作成しようとするとエラーが発生します。
先頭文字スタイル(Nested Style)を使用すると、文字スタイルのフォーマットを特定のパターンに従って段
落に適用することができます。 先頭文字スタイルを含む段落スタイルの作成方法を、次のスクリプトに示し
ます(完全なスクリプトについては、NestedStyles を参照してください)。 var myDocument = app.documents.item(0); var myPage = myDocument.pages.item(0); var myTextFrame = myPage.textFrames.item(0); var myParagraphStyle = myDocument.paragraphStyles.item("myParagraphStyle"); var myNestedStyle = myParagraphStyle.nestedStyles.add({appliedCharacterStyle:myCharacterStyle, delimiter:".", inclusive:true, repetition:1}); var myStartCharacter = myTextFrame.parentStory.characters.item(0); var myEndCharacter = myTextFrame.parentStory.characters.item(-1);
//Use the itemByRange method to apply the paragraph to all of the text in the story.
//(Note that the story object does not have the applyParagraphStyle method.) myTextFrame.parentStory.texts.itemByRange(myStartCharacter, myEndCharacter).applyParagraphStyle(myParagraphStyle, true);
スタイルの削除
ユーザーインターフェイスでスタイルを削除する際には、タグ付けされたスタイルでテキストのフォーマッ
ト方法を選択することができますが、 InDesign スクリプティングでもこれと同じことが行えます。次のスク
リプトにその例を示します(チュートリアルスクリプトの RemoveStyle より)。 var myDocument = app.activeDocument; var myParagraphStyleA = myDocument.paragraphStyles.item("myParagraphStyleA");
//Remove the paragraph style myParagraphStyleA and replace with myParagraphStyleB.
myParagraphStyleA.remove(myDocument.paragraphStyles.item("myParagraphStyleB"));
第 6 章 テキストと組版 テキストの検索と変更 108
段落スタイルや文字スタイルの読み込み
他の InDesign ドキュメントから文字スタイルや段落スタイルを読み込むことができます。次のスクリプトに
その例を示します(チュートリアルスクリプトの ImportTextStyles より)。
//Create a new document.
myDocument = app.documents.add();
//Import the styles from the saved document.
//importStyles parameters:
// Format as ImportFormat enumeration. Options for text styles are:
// ImportFormat.paragraphStylesFormat
// ImportFormat.characterStylesFormat
// ImportFormat.textStylesFormat
// From as File
// GlobalStrategy as GlobalClashResolutionStrategy enumeration. Options are:
// GlobalClashResolutionStrategy.doNotLoadTheStyle
// GlobalClashResolutionStrategy.loadAllWithOverwrite
// GlobalClashResolutionStrategy.loadAllWithRename
myDocument.importStyles(ImportFormat.textStylesFormat, File("/c/styles.indd"),
GlobalClashResolutionStrategy.loadAllWithOverwrite);
テキストの検索と変更
検索/変更機能は、テキストを操作するための最も強力なツールの 1 つであり、 スクリプティングに完全に
対応しています。スクリプトを使用すれば、ユーザーインターフェイスではできないことも可能になります。
InDesign では、次の 3 つの方法でテキストを検索できます。
テキストやテキストフォーマットを検索して、別のテキストやテキストフォーマットに変更できます。
この場合は、 findTextPreferences
オブジェクトや changeTextPreferences
オブジェクトを使用して、 findText
メソッドや changeText
メソッドのパラメーターを指定します。
正規表現を使用したテキスト検索(grep)を実行できます。 この場合は、 findGrepPreferences
オブジェ
クトや changeGrepPreferences
オブジェクトを使用して、 findGrep
メソッドや changeGrep
メソッドのパ
ラメーターを指定します。
特定の字形(とそのフォーマット)を検索して、別の字形やフォーマットに置換できます。 この場合は、 findGlyphPreferences
オブジェクトや changeGlyphPreferences
オブジェクトを使用して、 findGlyph
メ
ソッドや changeGlyph
メソッドのパラメーターを指定します。
どの検索/変更メソッドにも、
ReverseOrder
という 1 つのオプションパラメーターがあります。このパラ
メーターで、検索結果を返す順序を指定できます。 検索/変更操作の結果に基づいて、ストーリーのテキス
トを追加したり削除したりする場合は、この章の以前の節で説明したテキスト参照の問題に注意する必要が
あります。 この問題が発生する場合は、返されたテキストオブジェクトのコレクションを逆順で処理するよ
うにループを設定するか、または、検索結果を逆順で返すように設定して、そのコレクションを通常の順序
で処理します。
検索/変更の環境設定
テキストを検索する前に、検索/変更の環境設定を消去することで、前回の設定を引き継がないようにする
ことができます。 また、必要に応じていくつかの検索/変更環境設定を指定して、対象となるテキスト、
フォーマット、正規表現、字形などを指定することができます。 検索/変更操作を行う一般的な手順を次に
示します。
1.
検索/変更の環境設定を消去します。 検索/変更操作の種類に応じて、次の 3 つのいずれかを行います。
//find/change text preferences app.findTextPreferences = NothingEnum.nothing; app.changeTextPreferences = NothingEnum.nothing;
第 6 章 テキストと組版 テキストの検索と変更 109
//find/change grep preferences app.findGrepPreferences = NothingEnum.nothing; app.changeGrepPreferences = NothingEnum.nothing;
//find/change glyph preferences app.findGlyphPreferences = NothingEnum.nothing; app.changeGlyphPreferences = NothingEnum.nothing;
2.
検索パラメーターを設定します。
3.
検索/変更操作を実行します。
4.
検索/変更の環境設定を再び消去します。
テキストの検索と変更
指定したテキスト文字列を検索する方法を、次のスクリプトに示します。 このスクリプトではドキュメント
全体を検索していますが、ストーリー、テキストフレーム、段落、テキスト列などのテキストオブジェクト
を検索することもできます。 findText
メソッドとそのパラメーターは、すべてのテキストオブジェクトで共
通しています (完全なスクリプトについては、FindText を参照してください)。 var myDocument = app.activeDocument;
//Clear the find/change text preferences.
app.findTextPreferences = NothingEnum.nothing; app.changeTextPreferences = NothingEnum.nothing;
//Search the document for the string "Text".
app.findTextPreferences.findWhat = "text";
//Set the find options.
app.findChangeTextOptions.caseSensitive = false; app.findChangeTextOptions.includeFootnotes = false; app.findChangeTextOptions.includeHiddenLayers = false; app.findChangeTextOptions.includeLockedLayersForFind = false; app.findChangeTextOptions.includeLockedStoriesForFind = false; app.findChangeTextOptions.includeMasterPages = false; app.findChangeTextOptions.wholeWord = false; var myFoundItems = myDocument.findText(); alert("Found " + myFoundItems.length + " instances of the search string."); app.findTextPreferences = NothingEnum.nothing; app.changeTextPreferences = NothingEnum.nothing;
指定したテキスト文字列を検索して別の文字列に置換する方法を、次のスクリプトに示します(完全なスク
リプトについては、ChangeText を参照してください)。 var myDocument = app.activeDocument;
//Clear the find/change text preferences.
app.findTextPreferences = NothingEnum.nothing; app.changeTextPreferences = NothingEnum.nothing;
//Set the find options.
app.findChangeTextOptions.caseSensitive = false; app.findChangeTextOptions.includeFootnotes = false; app.findChangeTextOptions.includeHiddenLayers = false; app.findChangeTextOptions.includeLockedLayersForFind = false; app.findChangeTextOptions.includeLockedStoriesForFind = false; app.findChangeTextOptions.includeMasterPages = false; app.findChangeTextOptions.wholeWord = false;
//Search the document for the string "copy" and change it to "text".
app.findTextPreferences.findWhat = "copy"; app.changeTextPreferences.changeTo = "text"; myDocument.changeText();
//Clear the find/change text preferences after the search.
app.findTextPreferences = NothingEnum.nothing; app.changeTextPreferences = NothingEnum.nothing;
第 6 章 テキストと組版 テキストの検索と変更 110
テキストフォーマットの検索と変更
テキストフォーマットの検索や変更を行うには、 findTextPreferences
オブジェクトや changeTextPreferences
オブジェクトのその他のプロパティを設定します。次のスクリプトにその例を示し
ます(チュートリアルスクリプトの FindChangeFormatting より)。 var myDocument = app.documents.item(0);
//Clear the find/change preferences.
app.findTextPreferences = NothingEnum.nothing; app.changeTextPreferences = NothingEnum.nothing;
//Set the find options.
app.findChangeTextOptions.caseSensitive = false; app.findChangeTextOptions.includeFootnotes = false; app.findChangeTextOptions.includeHiddenLayers = false; app.findChangeTextOptions.includeLockedLayersForFind = false; app.findChangeTextOptions.includeLockedStoriesForFind = false; app.findChangeTextOptions.includeMasterPages = false; app.findChangeTextOptions.wholeWord = false;
//Search the document for the 24 point text and change it to 10 point text.
app.findTextPreferences.pointSize = 24; app.changeTextPreferences.pointSize = 10; myDocument.changeText();
//Clear the find/change preferences after the search.
app.findTextPreferences = NothingEnum.nothing; app.changeTextPreferences = NothingEnum.nothing;
grep の使用
InDesign の findGrep
メソッドや changeGrep
メソッドを使用すれば、正規表現を利用した検索/変更操作が
ストのフォーマットを changeGrepPreferences
オブジェクトのプロパティで指定したフォーマットに置換す
ることができます。 これらのメソッドや関係する環境設定オブジェクトの使用方法を、次のスクリプトに示
します(完全なスクリプトについては、FindGrep を参照してください)。 var myDocument = app.documents.item(0);
//Clear the find/change grep preferences.
app.findGrepPreferences = NothingEnum.nothing; app.changeGrepPreferences = NothingEnum.nothing;
//Set the find options.
app.findChangeGrepOptions.includeFootnotes = false; app.findChangeGrepOptions.includeHiddenLayers = false; app.findChangeGrepOptions.includeLockedLayersForFind = false; app.findChangeGrepOptions.includeLockedStoriesForFind = false; app.findChangeGrepOptions.includeMasterPages = false;
//Regular expression for finding an email address.
app.findGrepPreferences.findWhat = "(?i)[A-Z]*?@[A-Z]*?[.]...";
//Apply the change to 24-point text only.
app.findGrepPreferences.pointSize = 24; app.changeGrepPreferences.underline = true; myDocument.changeGrep();
//Clear the find/change preferences after the search.
app.findGrepPreferences = NothingEnum.nothing; app.changeGrepPreferences = NothingEnum.nothing;
注意 :
findChangeTextOptions
オブジェクトで使用できる wholeWord
と caseSensitive
の 2 つのプロパティ
は、 findChangeGrepOptions
ンを表現できるからです。 大文字と小文字を区別しない場合は
(?i)
を使用し、区別する場合は
(?-i)
を使用
します。 単語の先頭に一致するには
¥>
を使用し、単語の末尾に一致するには
¥<
を使用し、単語の境界に一致
するには
¥b
を使用します。 grep 検索/変更の利用例として、マークアップテキスト(タグでフォーマットが指定されているプレーンテ
キスト)を InDesign 形式のテキストに変換する処理があります。 簡単なテキストマークアップスキームとし
第 6 章 テキストと組版 テキストの検索と変更 111
ては、PageMaker の段落タグがあります(これは、PageMaker のタグ付きテキスト形式のファイルとは異な
落の先頭に示されます。
<heading1>This is a heading.
<body_text>This is body text.
grep 検索とテキスト検索/変更を組み合わせれば、テキストにフォーマットを適用して、マークアップタグ
を削除することができます。次のスクリプトにその例を示します(チュートリアルスクリプトの ReadPMTags
より)。 var myDocument = app.documents.item; var myStory = myDocument.stories.item(0); myReadPMTags(myStory);
このスクリプトで参照されている myReadPMTags 関数を次に示します。 function myReadPMTags(myStory){ var myName, myString, myStyle, myStyleName; var myDocument = app.documents.item(0);
//Reset the findGrepPreferences to ensure that previous settings
//do not affect the search.
app.findGrepPreferences = NothingEnum.nothing; app.changeGrepPreferences = NothingEnum.nothing;
//Find the tags (since this is a JavaScript string,
//the backslashes must be escaped).
app.findGrepPreferences.findWhat = "(?i)^<¥¥s*¥¥w+¥¥s*>"; var myFoundItems = myStory.findGrep(); if(myFoundItems.length != 0){ var myFoundTags = new Array; for(var myCounter = 0; myCounter<myFoundItems.length; myCounter++){ myFoundTags.push(myFoundItems[myCounter].contents);
} myFoundTags = myRemoveDuplicates(myFoundTags);
//At this point, we have a list of tags to search for.
for(myCounter = 0; myCounter < myFoundTags.length; myCounter++){ myString = myFoundTags[myCounter];
//Find the tag using findWhat.
app.findTextPreferences.findWhat = myString;
//Extract the style name from the tag.
myStyleName = myString.substring(1, myString.length-1);
//Create the style if it does not already exist.
try{ myStyle = myDocument.paragraphStyles.item(myStyleName); myName = myStyle.name;
} catch (myError){ myStyle = myDocument.paragraphStyles.add({name:myStyleName});
}
//Apply the style to each instance of the tag.
app.changeTextPreferences.appliedParagraphStyle = myStyle; myStory.changeText();
//Reset the changeTextPreferences.
app.changeTextPreferences = NothingEnum.nothing;
//Set the changeTo to an empty string.
app.changeTextPreferences.changeTo = "";
//Search to remove the tags.
myStory.changeText();
//Reset the find/change preferences again.
app.changeTextPreferences = NothingEnum.nothing;
}
}
//Reset the findGrepPreferences.
app.findGrepPreferences = NothingEnum.nothing;
}
第 6 章 テキストと組版 表の操作 112 function myRemoveDuplicates(myArray){
//Semi-clever method of removing duplicate array items; much faster
//than comparing every item to every other item! var myNewArray = new Array; myArray = myArray.sort(); myNewArray.push(myArray[0]); if(myArray.length > 1){ for(var myCounter = 1; myCounter < myArray.length; myCounter ++){ if(myArray[myCounter] != myNewArray[myNewArray.length -1]){ myNewArray.push(myArray[myCounter]);
}
}
} return myNewArray;
}
字形検索の使用
特定のフォントに含まれている個々の文字を検索/変更するには、 findGlyph
メソッドや changeGlyph
メ
ソッドを使用します。パラメーターは findGlyphPreferences
オブジェクトや changeGlyphPreferences
オブ
ジェクトで設定します。 次のスクリプトでは、サンプルドキュメントの中で字形を検索し、変更しています
(完全なスクリプトについては、FindChangeGlyph を参照してください)。
//Clear glyph search preferences.
app.findGlyphPreferences = NothingEnum.nothing; app.changeGlyphPreferences = NothingEnum.nothing; var myDocument = app.documents.item(0);
//You must provide a font that is used in the document for the
//appliedFont property of the findGlyphPreferences object.
app.findGlyphPreferences.appliedFont = app.fonts.itemByName("Minion ProRegular");
//Provide the glyph ID, not the glyph Unicode value.
app.findGlyphPreferences.glyphID = 374;
//The appliedFont of the changeGlyphPreferences object can be
//any font available to the application.
app.changeGlyphPreferences.appliedFont = app.fonts.itemByName("Times New RomanBold"); app.changeGlyphPreferences.glyphID = 85; myDocument.changeGlyph(false);
//Clear glyph search preferences.
app.findGlyphPreferences = NothingEnum.nothing; app.changeGlyphPreferences = NothingEnum.nothing;
表の操作
convertTextToTable
メソッドを使用して、既存のテキストから表を作成したり、ストーリー内の任意の挿入
点に空の表を作成することができます。 次のスクリプトでは、3 つの異なる方法で表を作成しています(完全
なスクリプトについては、MakeTable を参照してください)。
第 6 章 テキストと組版 表の操作 113 var myDocument = app.documents.item(0); var myStory = myDocument.stories.item(0); var myStartCharacter = myStory.paragraphs.item(6).characters.item(0); var myEndCharacter = myStory.paragraphs.item(6).characters.item(-2); var myText = myStory.texts.itemByRange(myStartCharacter, myEndCharacter);
//The convertToTable method takes three parameters:
//[ColumnSeparator as string]
//[RowSeparator as string]
//[NumberOfColumns as integer] (only used if the ColumnSeparator
//and RowSeparator values are the same)
//In the last paragraph in the story, columns are separated by commas
//and rows are separated by semicolons, so we provide those characters
//to the method as parameters.
var myTable = myText.convertToTable(",",";"); var myStartCharacter = myStory.paragraphs.item(1).characters.item(0); var myEndCharacter = myStory.paragraphs.item(4).characters.item(-2); var myText = myStory.texts.itemByRange(myStartCharacter, myEndCharacter);
//In the second through the fifth paragraphs, colums are separated by
//tabs and rows are separated by returns. These are the default delimiter
//parameters, so we don't need to provide them to the method.
var myTable = myText.convertToTable();
//You can also explicitly add a table--you don't have to convert text to a table.
var myTable = myStory.insertionPoints.item(-1).tables.add(); myTable.columnCount = 3; myTable.bodyRowCount = 3;
表セルの結合方法を、次のスクリプトに示します (完全なスクリプトについては、MergeTableCells を参照し
てください)。 var myDocument = app.documents.item(0); var myStory = myDocument.stories.item(0); var myTable = myStory.insertionPoints.item(-1).tables.add(); myTable.columnCount = 4; myTable.bodyRowCount = 4;
//Merge all of the cells in the first column.
myTable.cells.item(0).merge(myTable.columns.item(0).cells.item(-1));
//Convert column 2 into 2 cells (rather than 4).
myTable.columns.item(1).cells.item(-1).merge(myTable.columns.item(1).cells.item(-2)); myTable.columns.item(1).cells.item(0).merge(myTable.columns.item(1).cells.item(1));
//Merge the last two cells in row 1.
myTable.rows.item(0).cells.item(-2).merge(myTable.rows.item(0).cells.item(-1));
//Merge the last two cells in row 3.
myTable.rows.item(2).cells.item(-2).merge(myTable.rows.item(2).cells.item(-1));
表セルの分割方法を、次のスクリプトに示します (完全なスクリプトについては、SplitTableCells を参照して var myStory = myDocument.stories.item(0); var myTable = myStory.insertionPoints.item(-1).tables.add(); myTable.columnCount = 1; myTable.bodyRowCount = 1; var myArray = myGetBounds(myDocument, myDocument.pages.item(0)) var myWidth = myArray[3]-myArray[1]; myTable.columns.item(0).width = myWidth; myTable.cells.item(0).split(HorizontalOrVertical.horizontal); myTable.columns.item(0).split(HorizontalOrVertical.vertical); myTable.cells.item(0).split(HorizontalOrVertical.vertical); myTable.rows.item(-1).split(HorizontalOrVertical.horizontal); myTable.cells.item(-1).split(HorizontalOrVertical.vertical); for(myRowCounter = 0; myRowCounter < myTable.rows.length; myRowCounter ++){ myRow = myTable.rows.item(myRowCounter); for(myCellCounter = 0; myCellCounter < myRow.cells.length; myCellCounter ++){ myString = "Row: " + myRowCounter + " Cell: " + myCellCounter; myRow.cells.item(myCellCounter).contents = myString;
}
}
第 6 章 テキストと組版 表の操作 114
表にヘッダー行とフッター行を作成する方法を、次のスクリプトに示します(完全なスクリプトについては、 var myDocument = app.documents.item(0); var myTable = myDocument.stories.item(0).tables.item(0);
//Convert the first row to a header row.
myTable.rows.item(0).rowType = RowTypes.headerRow;
//Convert the last row to a footer row.
myTable.rows.item(-1).rowType = RowTypes.footerRow;
表にフォーマットを適用する方法を、次のスクリプトに示します(完全なスクリプトについては、 var myDocument = app.documents.item(0); var myTable = myDocument.stories.item(0).tables.item(0);
//Convert the first row to a header row.
myTable.rows.item(0).rowType = RowTypes.headerRow;
//Use a reference to a swatch, rather than to a color.
myTable.rows.item(0).fillColor = myDocument.swatches.item("DGC1_446b"); myTable.rows.item(0).fillTint = 40; myTable.rows.item(1).fillColor = myDocument.swatches.item("DGC1_446a"); myTable.rows.item(1).fillTint = 40; myTable.rows.item(2).fillColor = myDocument.swatches.item("DGC1_446a"); myTable.rows.item(2).fillTint = 20; myTable.rows.item(3).fillColor = myDocument.swatches.item("DGC1_446a"); myTable.rows.item(3).fillTint = 40;
//Use everyItem to set the formatting of multiple cells at once.
myTable.cells.everyItem().topEdgeStrokeColor = myDocument.swatches.item("DGC1_446b"); myTable.cells.everyItem().topEdgeStrokeWeight = 1; myTable.cells.everyItem().bottomEdgeStrokeColor = myDocument.swatches.item("DGC1_446b"); myTable.cells.everyItem().bottomEdgeStrokeWeight = 1;
//When you set a cell stroke to a swatch, make certain
//that you also set the stroke weight.
myTable.cells.everyItem().leftEdgeStrokeColor = myDocument.swatches.item("None"); myTable.cells.everyItem().leftEdgeStrokeWeight = 0; myTable.cells.everyItem().rightEdgeStrokeColor = myDocument.swatches.item("None"); myTable.cells.everyItem().rightEdgeStrokeWeight = 0;
表に反復行フォーマットを追加する方法を、次のスクリプトに示します(完全なスクリプトについては、
//Given a table "myTable," apply alternating fills to the table.
myTable.alternatingFills = AlternatingFillsTypes.alternatingRows; myTable.startRowFillColor = myDocument.swatches.item("DGC1_446a"); myTable.startRowFillTint = 60; myTable.endRowFillColor = myDocument.swatches.item("DGC1_446b"); myTable.endRowFillTint = 50;
テキストや表セルが選択されている場合の選択の処理方法を、次のスクリプトに示します。 このスクリプト
では、選択状況に応じて警告を表示していますが、実際のスクリプトでは選択されているアイテムに応じて
何らかの操作を行うことになります (完全なスクリプトについては、TableSelection を参照してください)。
第 6 章 テキストと組版 パステキストの追加 115 if(app.documents.length != 0){ if(app.selection.length != 0){ switch(app.selection[0].constructor.name){
//When a row, a column, or a range of cells is selected,
//the type returned is "Cell" case "Cell": alert("A cell is selected."); break; case "Table": alert("A table is selected."); break; case "InsertionPoint": case "Character": case "Word": case "TextStyleRange": case "Line": case "Paragraph": case "TextColumn": case "Text": if(app.selection[0].parent.constructor.name == "Cell"){ alert("The selection is inside a table cell.");
} break; case "Rectangle": case "Oval": case "Polygon": case "GraphicLine": if(app.selection[0].parent.parent.constructor.name == "Cell"){ alert("The selection is inside a table cell.");
} break; case "Image": case "PDF": case "EPS": if(app.selection[0].parent.parent.parent.constructor.name == "Cell"){ alert("The selection is inside a table cell.");
} break; default: alert("The selection is not inside a table."); break;
}
}
}
パステキストの追加
パステキストは、長方形、楕円形、多角形、グラフィックの線、テキストフレームに追加できます。 ページ
アイテムにパステキストを追加する方法を、次のスクリプトに示します(完全なスクリプトについては、
//Given a document "myDocument" with a rectangle on page 1...
var myPage = myDocument.pages.item(0); var myRectangle = myPage.rectangles.item(0); var myTextPath = myRectangle.textPaths.add({contents:"This is path text."});
テキストパスを別のテキストパスやテキストフレームにリンクするには、 nextTextFrame
プロパティや previousTextFrame
プロパティを使用します。これは、テキストフレームのリンクの場合と同じです
(
第 6 章 テキストと組版 自動修正の使用 116
自動修正の使用
自動修正機能を使用すると、テキストが入力されたときにテキストを自動的に修正することができます。 次
のスクリプトにその例を示します(完全なスクリプトについては、Autocorrect を参照してください)。
//The autocorrect preferences object turns the
//autocorrect feature on or off.
app.autoCorrectPreferences.autoCorrect = true; app.autoCorrectPreferences.autoCorrectCapitalizationErrors = true;
//Add a word pair to the autocorrect list. Each AutoCorrectTable is linked
//to a specific language. var myAutoCorrectTable = app.autoCorrectTables.item("English: USA");
//To safely add a word pair to the auto correct table, get the current
//word pair list, then add the new word pair to that array, and then
//set the autocorrect word pair list to the array.
var myWordPairList = myAutoCorrectTable.autoCorrectWordPairList;
//Add a new word pair to the array.
myWordPairList.push(["paragarph", "paragraph"]);
//Update the word pair list.
myAutoCorrectTable.autoCorrectWordPairList = myWordPairList;
//To clear all autocorrect word pairs in the current dictionary:
//myAutoCorrectTable.autoCorrectWordPairList = [[]];
脚注の追加
ストーリーに脚注を追加する方法を、次のスクリプトに示します( myGetRandom
関数を含む完全なスクリプ
トについては、Footnotes を参照してください)。 var myDocument = app.documents.item(0); var myPage = myDocument.pages.item(0); var myTextFrame = myPage.textFrames.item(0);
//Add four footnotes at random locations in the story.
for(myCounter = 0; myCounter < 4; myCounter ++){ myWord = myTextFrame.parentStory.words.item(myGetRandom(0, myTextFrame.parentStory.words.length)); var myFootnote = myWord.insertionPoints.item(-1).footnotes.add();
//Note: when you create a footnote, it contains text--the footnote marker
//and the separator text (if any). If you try to set the text of the footnote
//by setting the footnote contents, you will delete the marker. Instead, append
//the footnote text, as shown below.
myFootnote.insertionPoints.item(-1).contents = "This is a footnote.";
}
段抜きと段分割
段抜きや段分割の属性を適用して、段落のレイアウトを複数の段にまたがるようにしたり、段を分割したり
することができます。 段落の段抜きおよび段分割のスタイルを設定する方法を、次のスクリプトに示します
(完全なスクリプトについては、SpanColumns を参照してください)。
第 6 章 テキストと組版 テキスト環境設定の指定 117 var myDocument = app.activeDocument; var myPage = myDocument.pages.item(0); var myTextFrame = myPage.textFrames.item(0); myTextFrame.textFramePreferences.textColumnCount = 3; var myStory = myTextFrame.parentStory;
//Split Column with(myStory.paragraphs[0]) { spanColumnType = SpanColumnTypeOptions.splitColumns; spanSplitColumnCount = 2; splitColumnOutsideGutter = 0; splitColumnInsideGutter = 1;
}
//Span Columns var mySpanIndex = Math.floor(myStory.paragraphs.length / 2); with(myStory.paragraphs[mySpanIndex]) { spanColumnType = SpanColumnTypeOptions.spanColumns; spanSplitColumnCount = SpanColumnCountOptions.all;
}
テキスト環境設定の指定
一般的なテキスト環境設定の指定方法を、次のスクリプトに示します(完全なスクリプトについては、
//The following sets the text preferences for the application; to set the
//text preferences for the front-most document, replace "app.textPreferences" with
//"app.documents.item(0).textPreferences" with(app.textPreferences){ abutTextToTextWrap = true;
//baseline shift key increment can range from .001 to 200 points.
baselineShiftKeyIncrement = 1; highlightCustomSpacing = false; highlightHjViolations = true; highlightKeeps = true; highlightSubstitutedFonts = true; highlightSubstitutedGlyphs = true; justifyTextWraps = true;
//kerning key increment value is 1/1000 of an em.
kerningKeyIncrement = 10;
//leading key increment value can range from .001 to 200 points.
leadingKeyIncrement= 1; linkTextFilesWhenImporting = false; scalingAdjustsText = false; showInvisibles = true; smallCap = 60; subscriptPosition = 30; subscriptSize = 60; superscriptPosition = 30; superscriptSize = 60; typographersQuotes = false; useOpticalSize = false; useParagraphLeading = false; zOrderTextWrap = false;
}
//Text editing preferences are application-wide.
with(app.textEditingPreferences){ allowDragAndDropTextInStory = true; dragAndDropTextInLayout = true; smartCutAndPaste = true; tripleClickSelectsLine = false;
}
第 6 章 テキストと組版 リンクストーリーの操作 118
リンクストーリーの操作
リンクストーリーを使用すると、1 つのドキュメントに含まれる同一のストーリーまたはテキストコンテン
ツの複数のバージョンを簡単に管理することができます。これにより、例えば縦組みと横組みの両方のレイ
アウト用のデザインが必要になるといった、新たなデジタルパブリッシングワークフローへの対応が容易に
じストーリーをドキュメント内の別の場所に子ストーリーとして配置できます。 親ストーリーを更新すると
リンクパネル内で子ストーリーにフラグが付くので、子ストーリーを更新して親ストーリーに同期させるこ
とができます。
リンクストーリーの作成
リンクストーリーは複数の方法で作成できます。 既存のテキストフレームを親ストーリーにリンクする方法
と、指定した場所にテキストフレームを作成して親ストーリーにリンクするよう Page オブジェクト、Spread
オブジェクト、Master オブジェクトまたは Document オブジェクトに対して指示する方法があります。
既存のテキストフレームを親ストーリーにリンクするには、次のスクリプトを使用します(完全なスクリプ
トについては、CreateLinkedStories を参照してください)。 childTextFrame1.placeAndLink(myTextFrame.parentStory, false);
スが表示されます。指定しなかった場合は、デフォルトのオプションが使用されます。
親ストーリーのリンクストーリーの作成を Page オブジェクトに対して指示するために、placeAndLink メソッ
ドには 2 つのパラメーターが用意されており、これらのパラメーターでリンクストーリーを配置するレイ
ヤーと位置を指定できます。次のスクリプトにその例を示します(完全なスクリプトについては、 var newPage = myDocument.pages.add(); newPage.placeAndLink(myTextFrame.parentStory, [originY, originX], myDocument.activeLayer, false);
親ストーリーのリンクストーリーの作成を Spread オブジェクトに対して指示する場合、placeAndLink メソッ
ドでは Page オブジェクトの placeAndLink メソッドと同じパラメーターを取ります。次のスクリプトにその例
を示します(完全なスクリプトについては、CreateLinkedStories を参照してください)。 var newSpread = myDocument.spreads.add(); newSpread.placeAndLink(myTextFrame.parentStory, [originY, originX], myDocument.activeLayer, false);
また、placeAndLink メソッドを Document オブジェクトで呼び出すことも可能です。 このメソッドは親ストー
リーを唯一のパラメーターとして取ります。 このメソッドではリンクストーリーは作成されませんが、プ
レースガンが読み込まれるので、ユーザーがリンクストーリーの場所を自分で決めることができます。
リンクストーリーのオプションの変更
リンクストーリーのオプションを変更するには、次のスクリプトを使用します(完全なスクリプトについて
は、CreateLinkedStories を参照してください)。 with (myDocument.linkedStoryOptions)
{
removeForcedLineBreaks = true;
updateWhileSaving = true;
warnOnUpdateOfEditedStory = true;
}
第 6 章 テキストと組版 リンクストーリーの操作 119
よくある質問
特定のリンクがリンクストーリーのリンクであるかどうかは、どのように判断す
ることができますか?
リンクストーリーのリンクでは、リンクソースをどのような方法で取得できます
か?
次のスクリプトを使用して、リンクソースを選択します。
Link.editoriginal();
次に、次のスクリプトでアクティブな選択を検出します。これがリンクソースです。
Application.selection();
7
ユーザーインターフェイス
CS6
章の更新ステータス
変更なし
ダイアログボックスか、テキストを入力するためのダイアログボックスに限られていますが、より複雑なダ
イアログボックスを使用したいこともあります。 InDesign スクリプティングを使用すれば、ポップアップリ
スト、テキスト入力フィールド、数値入力フィールドなどの一般的なユーザーインターフェイスコントロー
ルを備えたダイアログボックスを作成できます。 ユーザー(または自分)から情報を受け取って、それに基
づいて処理を実行したい場合は、 dialog
オブジェクトが役に立ちます。
この章では、InDesign のダイアログボックスを使用したスクリプトについて説明します。 最初は簡単なサン
プルスクリプトから始めて、徐々に複雑なスクリプトへと進んでいきます。
注意 : JavaScript で InDesign スクリプトを作成する場合は、Adobe ScriptUI コンポーネントを使用してユー
ザーインターフェイスを作成することもできます。 この章には、ScriptUI スクリプティングのチュートリアル
も含まれています。詳しくは、『Adobe JavaScript Tools Guide』を参照してください。
ここでは、読者が『Adobe InDesign スクリプティングチュートリアル』を既に読んでおり、スクリプトを作
成して実行する方法を理解しているものとして説明を行います。
ダイアログボックスの概要
InDesign のダイアログボックスは、InDesign の他のスクリプティングオブジェクトと同じく、1 つのオブジェ
めることができます。 この図に示されている各要素について、この図の次の表で説明します。 dialog dialog column static text border panel checkbox control radiobutton group radiobutton control measurement editbox dropdown
120
第 7 章 ユーザーインターフェイス 最初の InDesign ダイアログボックスの作成 121
ダイアログボックスの要素
テキスト編集フィールド
数値入力フィールド
InDesign での名前
Text editbox control
ポップアップメニュー
テキスト編集フィールドとポップアップメニューを
組み合わせたコントロール
チェックボックス
ラジオボタン
Real editbox, integer editbox, measurement editbox, percent editbox, angle editbox
Drop-down control
Combo-box control
Check-box control
Radio-button control
これらのコントロールは、 dialog
オブジェクトに直接格納されるのではなく、 dialogColumn
というオブジェ
クトに格納されます。 dialogColumn
を使用することで、ダイアログボックス内のコントロールの位置を制御
することができます。 dialogColumn
の中に、別の dialogColumn
や borderPanel
を含めて、ダイアログボック
スをさらに細かく分割することができます(必要に応じて、 dialogColumn
や borderPanel
の中に別の dialogColumn
や borderPanel
。
InDesign の他のスクリプティングオブジェクトと同じように、ダイアログボックスの各パーツにも固有のプ
ロパティがあります。 例えば、 checkboxControl
には、表示されるテキストを表すプロパティ( staticLabel
)
や、コントロールの状態を表すプロパティ( checkedState
)があります。 また、 dropdown
コントロールには、
メニューに表示されるオプションのリストを表すプロパティ( stringList
)があります。
スクリプトの中でダイアログボックスを使用するには、まず dialog
オブジェクトを作成し、そこに様々なコ
ントロールを配置して、ダイアログボックスを表示します。そして、スクリプトの処理に必要な値をそれら
のコントロールから収集します。 ダイアログボックスは、破棄されるまで InDesign のメモリ内に維持されま
を複数のスクリプトで使用することが可能です。ただし、ダイアログボックスを保持するためにメモリが消
費されるので、必要がなくなったら破棄するようにしてください。 一般的には、スクリプトが処理を終了す
る前にダイアログボックスオブジェクトを破棄します。
最初の InDesign ダイアログボックスの作成
ボックスにダイアログコラムを追加し、ダイアログコラムにコントロールを追加します。 次のスクリプトに
その例を示します(完全なスクリプトについては、SimpleDialog を参照してください)。 var myDialog = app.dialogs.add({name:"Simple Dialog"});
//Add a dialog column.
with(myDialog.dialogColumns.add()){ staticTexts.add({staticLabel:"This is a very simple dialog box."});
}
//Show the dialog box.
var myResult = myDialog.show();
//If the user clicked OK, display one message;
//if they clicked Cancel, display a different message.
if(myResult == true){ alert("You clicked the OK button.");
} else{ alert("You clicked the Cancel button.");
}
//Remove the dialog box from memory.
myDialog.destroy();
第 7 章 ユーザーインターフェイス 「Hello World」へのユーザーインターフェイスの追加 122
「Hello World」へのユーザーインターフェイスの追加
リプトに、簡単なユーザーインターフェイスを追加したものです。 ダイアログボックスに表示されるオプ
ションを使用して、表示するテキストを指定したり、テキストのポイントサイズを変更したりすることがで
きます。 var myDialog = app.dialogs.add({name:"Simple User Interface Example Script",canCancel:true}); with(myDialog){
//Add a dialog column.
with(dialogColumns.add()){
//Create a text edit field.
var myTextEditField = textEditboxes.add({editContents:"Hello World!", minWidth:180});
//Create a number (real) entry field.
var myPointSizeField = measurementEditboxes.add({editValue:72, editUnits:MeasurementUnits.points});
}
}
//Display the dialog box.
var myResult = myDialog.show(); if(myResult == true){
//Get the values from the dialog box controls.
var myString = myTextEditField.editContents;
} else{ myDialog.destroy();
} var myPointSize = myPointSizeField.editValue;
//Remove the dialog box from memory.
myDialog.destroy(); myMakeDocument(myString, myPointSize);
このスクリプトで参照されている myMakeDocument
関数を次に示します。 function myMakeDocument(myString, myPointSize){
//Create a new document.
var myDocument = app.documents.add() with(myDocument){
//Create a text frame.
var myTextFrame = pages.item(0).textFrames.add();
//Resize the text frame to the "live" area of the page
//(using the function "myGetBounds").
var myBounds = myGetBounds(myDocument, myDocument.pages.item(0)); myTextFrame.geometricBounds=myBounds;
//Enter the text from the dialog box in the text frame.
myTextFrame.contents=myString;
//Set the size of the text to the size you entered in the dialog box.
myTextFrame.texts.item(0).pointSize = myPointSize;
}
}
さらに複雑なユーザーインターフェイスの作成
次の例では、様々なコントロールをサンプルダイアログボックスに追加します。 この例では、次のようなダ
イアログボックスが作成されます。
第 7 章 ユーザーインターフェイス さらに複雑なユーザーインターフェイスの作成 123
完全なスクリプトについては、ComplexUI を参照してください。 var myDialog = app.dialogs.add({name:"User Interface Example Script", canCancel:true}); with(myDialog){
//Add a dialog column.
with(dialogColumns.add()){
//Create a border panel.
with(borderPanels.add()){ with(dialogColumns.add()){
//The following line shows how to set a property as you create an object.
staticTexts.add({staticLabel:"Message:"});
} with(dialogColumns.add()){
//The following line shows how to set multiple properties
//as you create an object.
var myTextEditField = textEditboxes.add
({editContents:"Hello World!", minWidth:180});
}
}
//Create another border panel.
with(borderPanels.add()){ with(dialogColumns.add()){ staticTexts.add({staticLabel:"Point Size:"});
} with(dialogColumns.add()){
//Create a number entry field. Note that this field uses editValue
//rather than editText (as a textEditBox would).
var myPointSizeField = measurementEditboxes.add({editValue:72});
}
}
//Create another border panel.
with(borderPanels.add()){ with(dialogColumns.add()){ staticTexts.add({staticLabel:"Vertical Justification:"});
} with(dialogColumns.add()){
//Create a pop-up menu ("dropdown") control.
var myVerticalJustificationMenu = dropdowns.add
({stringList:["Top", "Center", "Bottom"], selectedIndex:0});
}
}
//Create another border panel.
with(borderPanels.add()){ staticTexts.add({staticLabel:"Paragraph Alignment:"}); var myRadioButtonGroup = radiobuttonGroups.add(); with(myRadioButtonGroup){ var myLeftRadioButton = radiobuttonControls.add
({staticLabel:"Left", checkedState:true}); var myCenterRadioButton = radiobuttonControls.add
({staticLabel:"Center"}); var myRightRadioButton = radiobuttonControls.add({staticLabel:"Right"});
}
}
第 7 章 ユーザーインターフェイス さらに複雑なユーザーインターフェイスの作成 124
}
}
//Display the dialog box.
if(myDialog.show() == true){ var myParagraphAlignment, myString, myPointSize, myVerticalJustification;
//If the user didn't click the Cancel button,
//then get the values back from the dialog box.
//Get the example text from the text edit field.
myString = myTextEditField.editContents
//Get the point size from the point size field.
myPointSize = myPointSizeField.editValue;
//Get the vertical justification setting from the pop-up menu.
if(myVerticalJustificationMenu.selectedIndex == 0){ myVerticalJustification = VerticalJustification.topAlign;
} else if(myVerticalJustificationMenu.selectedIndex == 1){ myVerticalJustification = VerticalJustification.centerAlign;
} else{ myVerticalJustification = VerticalJustification.bottomAlign;
}
//Get the paragraph alignment setting from the radiobutton group.
if(myRadioButtonGroup.selectedButton == 0){ myParagraphAlignment = Justification.leftAlign;
} else if(myRadioButtonGroup.selectedButton == 1){ myParagraphAlignment = Justification.centerAlign;
} else{ myParagraphAlignment = Justification.rightAlign;
} myDialog.destroy(); myMakeDocument(myString, myPointSize, myParagraphAlignment, myVerticalJustification);
} else{ myDialog.destroy()
}
このスクリプトで参照されている myMakeDocument
関数を次に示します。 function myMakeDocument(myString, myPointSize, myParagraphAlignment, myVerticalJustification){
//Create a new document.
var myDocument = app.documents.add(); with(myDocument){ viewPreferences.horizontalMeasurementUnits = MeasurementUnits.points; viewPreferences.verticalMeasurementUnits = MeasurementUnits.points; var myPage = pages[0]; with(myPage){
//Create a text frame.
var myTextFrame = pages.item(0).textFrames.add(); with(myTextFrame){
//Set the geometric bounds of the frame using the "myGetBounds" function.
geometricBounds = myGetBounds(myDocument, myPage);
//Set the contents of the frame to the string you
//entered in the dialog box.
contents = myString;
//Set the alignment of the paragraph.
texts.item(0).justification = myParagraphAlignment;
//Set the point size of the text.
texts.item(0).pointSize = myPointSize;
//Set the vertical justification of the text frame.
textFramePreferences.verticalJustification = myVerticalJustification;
}
}
}
}
第 7 章 ユーザーインターフェイス
ScriptUI の使用 125
ScriptUI の使用
JavaScript では、ScriptUI というアドビ システムズ社独自のスクリプティングコンポーネントを使用して、
ユーザーインターフェイス要素の作成や定義が行えます。 ScriptUI を使用すれば、InDesign の組み込みの dialog
オブジェクトよりも格段に複雑なインタラクティブダイアログボックスを作成できます。また、フ
ローティングパレットやプログレスバーも作成できます。
AppleScript や VBScript でも、ScriptUI を使用して定義されたユーザーインターフェイス要素にアクセスするこ
とができます。 do script メソッド(AppleScript の場合)や DoScript メソッド(VBScript の場合)を使用すれ
ば、他のスクリプト言語で書かれたスクリプトを実行できます。
ScriptUI を使用したプログレスバーの作成
JavaScript で ScriptUI を使用してプログレスバーを作成する方法を、次のスクリプトに示します(完全なスク
リプトについては、ProgressBar を参照してください)。このスクリプトで作成したプログレスバーは、別の
スクリプトで使用することが可能です。
#targetengine "session"
//Because these terms are defined in the "session" engine,
//they will be available to any other JavaScript running
//in that instance of the engine.
var myMaximumValue = 300; var myProgressBarWidth = 300; var myIncrement = myMaximumValue/myProgressBarWidth; myCreateProgressPanel(myMaximumValue, myProgressBarWidth); function myCreateProgressPanel(myMaximumValue, myProgressBarWidth){ myProgressPanel = new Window('window', 'Progress'); with(myProgressPanel){ myProgressPanel.myProgressBar = add('progressbar', [12, 12, myProgressBarWidth, 24], 0, myMaximumValue);
}
}
前のスクリプトで作成したプログレスバーを別の JavaScript で呼び出す方法を、次のスクリプトに示します
(完全なスクリプトについては、CallProgressBar を参照してください)。
Rem Create a document and add pages to it--
Rem if you do not do this, the progress bar
Rem will go by too quickly.
Set myDocument = myInDesign.Documents.Add
Rem Note that the JavaScripts must use the "session"
Rem engine for this to work.
myString = "#targetengine ""session""" & vbCr myString = myString & "myCreateProgressPanel(100, 400);" & vbcr myString = myString & "myProgressPanel.show();" & vbcr myInDesign.DoScript myString, idScriptLanguage.idJavascript
For myCounter = 1 to 100
Rem Add a page to the document.
myInDesign.Documents.Item(1).Pages.Add
myString = "#targetengine ""session""" & vbCr myString = myString & "myProgressPanel.myProgressBar.value = " myString = myString & cstr(myCounter) & "/myIncrement;" & vbcr myInDesign.DoScript myString, idScriptLanguage.idJavascript
If(myCounter = 100) Then myString = "#targetengine ""session""" & vbCr myString = myString & "myProgressPanel.myProgressBar.value = 0;" & vbcr
Next myString = myString & "myProgressPanel.hide();" & vbcr myInDesign.DoScript myString, idScriptLanguage.idJavascript
myDocument.Close idSaveOptions.idNo
End If
8
イベント
CS6
章の更新ステータス
変更なし
InDesign スクリプティングでは、アプリケーションやドキュメントの一般的なイベント(ファイルのオープ
ン、新規ファイルの作成、プリント、ディスク上のテキストファイルやグラフィックファイルの読み込みな
ど)に応答することができます。 アプリケーションで発生するイベントは、 event
オブジェクトによって表さ
れます。 eventListener
というスクリプトオブジェクトを使用しま
す。 イベントに割り当てるスクリプトは、通常のスクリプトとほとんど同じですが、通常のスクリプトは
ユーザーが(スクリプトパネルから)実行するのに対して、イベントに割り当てるスクリプトは自動的に
(目的のイベントが発生したときに)実行される点が異なります。
この章では、InDesign のイベントを使用したスクリプトについて説明します。 最初は簡単なサンプルスクリ
プトから始めて、徐々に複雑なスクリプトへと進んでいきます。
ここでは、読者が『Adobe InDesign スクリプティングチュートリアル』を既に読んでおり、スクリプトを作
成、インストール、実行する方法を理解しているものとして説明を行います。
メニューに関連するイベントについては、 第 9 章「メニュー」 を参照してください。
InDesign のイベントスクリプトモデルは、Worldwide Web Consortium(W3C)勧告のドキュメントオブジェ
クトモデルイベントに似ています。 詳しくは、 http://www.w3c.org
を参照してください。
イベントスクリプトモデルについて
InDesign のイベントスクリプトモデルは、アプリケーションで発生する各種のイベントに相当する一連のオ
ブジェクトによって構成されています。 その中心となるのが event
オブジェクトです。これは、InDesign の
ユーザーインターフェイスで行われる特定のアクション(またはスクリプトの処理に相当するアクション)
を表します。
イベントに応答するには、そのイベントを受け取るオブジェクトに eventListener
を登録します。
ジェクトが指定のイベントを受け取ると、 eventListener
のハンドラー関数に定義されているスクリプト関
数(スクリプト関数か、ディスク上のスクリプトファイルへの参照)が実行されます。
使用可能なイベントを確認するには、ExtendScript Toolkit のオブジェクトモデルビューアを使用します。
ExtendScript Toolkit で Event クラスを選択し、種類リストで Class をクリックすると、プロパティとメソッド
リストに使用可能なイベントのタイプのリストが表示されます。
イベントプロパティとイベントの伝達について
ユーザーやスクリプトによってアクションが実行されてイベントが発生すると、そのイベントに応答可能な
スクリプティングオブジェクトにイベントが伝達されます。 特定のイベントに対する eventListener
が登録
されているオブジェクトにそのイベントが伝達されると、その eventListener
が呼び出されます。
ントが複数のオブジェクトに伝達されて、複数のオブジェクトで処理が行われる場合もあります。
イベントの伝達には、次の 2 種類があります。
伝達しない — イベントターゲットに登録されている eventListener
のみが呼び出されます。
イベントの例としては、 beforeDisplay
イベントがあります。
126
第 8 章 イベント イベントリスナーの操作 127
バブル — target
から伝達が開始されます。まず、 target
に登録されている応答可能な eventListener
が呼び出されます。 次に、スクリプトオブジェクトモデルの上方向にイベントが伝達されます。スクリ
プトオブジェクトモデルで target
の上位にあるオブジェクトに登録されている、そのイベントに応答可
能な eventListener
が呼び出されます。
次の表に、 event
のプロパティの詳細と、スクリプトオブジェクトモデルでのイベント伝達に与える影響を
示します。
プロパティ
Bubbles
Cancelable
CurrentTarget
DefaultPrevented
EventPhase
EventType
PropagationStopped
Target
TimeStamp
説明
true の場合、 event
が発生したオブジェクトの上位にあるスクリプティングオ
ブジェクトにその event
が伝達されます。 target
における event
のデフォルトの動作をキャンセルできます。
これを行うには、
PreventDefault
メソッド を使用します。 event
この表の
Target
を参照してください。 true の場合、現在の target
における event
のデフォルト動作が実行されず、ア
クションがキャンセルされます。 この表の
Target
を参照してください。 event
の伝達プロセスの現在のステージ。 event
「 beforeNew
。 true の場合、 current target
以降への伝達が中止されます(この表の
Target
を
参照してください)。 stopPropagation
メソッ
ド を使用します。 event
例えば、 beforeImport
イベントの
Target
は
ドキュメントであり、 beforeNew
イベントの
Target
はアプリケーションです。 event
が発生した日時。
イベントリスナーの操作
eventListener
を作成するときには、イベントのタイプとイベントハンドラー(関数またはファイル参照)
を指定します。 特定のイベントに対して eventListener
を追加する方法を、次のスクリプトに示します(完
全なスクリプトについては、AddEventListener を参照してください)。 var myEventListener = app.addEventListener("afterNew", myDisplayEventType, false);
このスクリプトで参照されている関数を次に示します。 function myDisplayEventType(myEvent){ alert("This event is the " + myEvent.eventType + " event.");
}
このスクリプトで作成した eventListener
を削除するには、次のスクリプトを実行します(チュートリアル
スクリプトの RemoveEventListener より)。 app.removeEventListener("afterNew", myDisplayEventType);
1 つの eventListener
でイベントが処理されても、そのイベントを監視している他の eventListener
があれ afterOpen
イベントは、アプリケーションとドキュメントの両方の eventListener
で監視されている可能性
があります。 eventListener
すべての InDesign
セッションで eventListener
を利用できるようにしたい場合は、スタートアップスクリプト用のフォルダー
第 8 章 イベント イベントリスナーの操作 128
である Startup Scripts にスクリプトを追加します (スクリプトのインストールについて詳しくは、『Adobe
InDesign スクリプティングチュートリアル』の「スクリプトのインストール」を参照してください) ドキュ
メントに eventListener
スクリプトを追加しても、ドキュメントとともに保存されたり、IDML に書き出され
たりすることはありません。
注意 :
eventListener
を定義するスクリプトで問題が発生した場合は、その eventListener
を削除するスクリ
プトを実行するか、InDesign を終了して再起動します。
(外部ファイルではなく)スクリプトの中で定義されているハンドラー関数を使用する eventListener
では、
#targetengine "session"
このスクリプトを
#targetengine "main"
(デフォル
トの設定)で実行すると、イベントの発生時に関数が使用できず、エラーが発生します。
スクリプトオブジェクトモデルの中で 1 つのイベントが伝達されて、複数の eventListener
が呼び出される
場合があります。 次のサンプルスクリプトでは、様々なオブジェクトに登録されている eventListener
が 1
つのイベントによって呼び出されます(完全なスクリプトについては、MultipleEventListeners を参照してく
#targetengine "session" main(); function main(){ var myApplicationEventListener = app.eventListeners.add("beforeImport", myEventInfo); var myDocumentEventListener = app.documents.item(0).eventListeners.add
("beforeImport", myEventInfo);
} function myEventInfo(myEvent){ var myString = "Current Target: " + myEvent.currentTarget.name; alert(myString);
}
このスクリプトを実行してファイルを配置すると、ドキュメントの名前を示す警告と、アプリケーションの
名前を示す警告が順に表示されます。 このスクリプトで追加したイベントリスナーを削除するには、
RemoveMultipleEventListeners スクリプトを実行します。
次のサンプルスクリプトでは、ドキュメントの各イベントの eventListener
を作成して、簡単なダイアログ
ボックスにイベントに関する情報を表示しています。 完全なスクリプトについては、EventListenersOn を参照
してください。 main() function main(){ app.scriptPreferences.version = 5.0; var myEventNames = [
"beforeQuit", "afterQuit",
"beforeNew", "afterNew",
"beforeOpen", "afterOpen",
"beforeClose", "afterClose",
"beforeSave", "afterSave",
"beforeSaveAs", "afterSaveAs",
"beforeSaveACopy", "afterSaveACopy",
"beforeRevert", "afterRevert",
"beforePrint", "afterPrint",
"beforeExport", "afterExport",
"beforeImport", "afterImport"
] ; for (var myCounter = 0; myCounter < myEventNames.length; myCounter ++){ app.addEventListener(myEventNames[myCounter], myEventInfo);
}
} function myEventInfo(myEvent){ var myString = "Handling Event: " +myEvent.eventType; myString += "¥r¥rTarget: " + myEvent.target + " " +myEvent.target.name; myString += "¥rCurrent: " +myEvent.currentTarget + " " + myEvent.currentTarget.name; myString += "¥r¥rPhase: " + myGetPhaseName(myEvent.eventPhase );
第 8 章 イベント 「afterNew」イベントリスナーの例 129 myString += "¥rBubbles: " + myEvent.bubbles; myString += "¥r¥rCancelable: " +myEvent.cancelable; myString += "¥rStopped: " +myEvent.propagationStopped; myString += "¥rCanceled: " +myEvent.defaultPrevented; myString += "¥r¥rTime: " +myEvent.timeStamp; alert(myString); function myGetPhaseName(myPhase){ switch(myPhase){ case EventPhases.atTarget: myPhaseName = "At Target"; break; case EventPhases.bubblingPhase: myPhaseName = "Bubbling"; break; case EventPhases.done: myPhaseName = "Done"; break; case EventPhases.notDispatching: myPhaseName = "Not Dispatching"; break;
} return myPhaseName;
}
}
アプリケーションオブジェクトのすべての eventListener
をオフにする方法を、次のサンプルスクリプトに
#targetengine "session" app.eventListeners.everyItem().remove();
「afterNew」イベントリスナーの例
afterNew
イベントは、ユーザー名、ドキュメントの作成日、著作権情報、その他の作業に関する情報などを
ドキュメントに追加したい場合に便利です。 ドキュメントの最初のマスタースプレッドの印刷可能領域にあ
るテキストフレームにこのような情報を追加する方法を、次のチュートリアルスクリプトに示します(完全
なスクリプトについては、AfterNew というチュートリアルを参照してください)。 このスクリプトでは、ド
キュメントのメタデータ(ファイル情報または XMP 情報とも呼ばれます)も追加しています。
#targetengine "session"
//Creates an event listener that will run after a new document is created.
main(); function main(){ var myEventListener = app.eventListeners.add("afterNew", myAfterNewHandler);
} function myAfterNewHandler(myEvent){ var myDocument = myEvent.parent; myDocument.viewPreferences.horizontalMeasurementUnits =
MeasurementUnits.points; myDocument.viewPreferences.verticalMeasurementUnits =
MeasurementUnits.points; myDocument.viewPreferences.rulerOrigin = RulerOrigin.pageOrigin; myCreateSlug(myDocument); myAddXMPData(myDocument); function myCreateSlug(myDocument){
//mySlugOffset is the distance from the bottom of the page to
//the top of the slug.
var mySlugOffset = 24;
//mySlugHeight is the height of the slug text frame.
var mySlugHeight = 72; with(myDocument.documentPreferences){ documentSlugUniformSize = false; slugBottomOffset = mySlugOffset + mySlugHeight; slugTopOffset = 0;
第 8 章 イベント 「beforePrint」イベントリスナーの例 130
} slugInsideOrLeftOffset = 0; slugRightOrOutsideOffset = 0;
} for(var myCounter = 0; myCounter < myDocument.masterSpreads.length; myCounter++){ var myMasterSpread = myDocument.masterSpreads.item(myCounter); for(var myMasterPageCounter = 0; myMasterPageCounter < myMasterSpread.pages.length; myMasterPageCounter ++){ var myPage = myMasterSpread.pages.item(myMasterPageCounter); var mySlugBounds = myGetSlugBounds(myDocument, myPage, mySlugOffset, mySlugHeight); var mySlugFrame = myPage.textFrames.add(
{geometricBounds:mySlugBounds, contents:"Created: " + myEvent.timeStamp + "¥rby: " + app.userName});
}
}
} function myAddXMPData(myDocument){ with(myDocument.metadataPreferences){ author = "Adobe Systems"; description = "This is a sample document with XMP metadata.";
}
} function myGetSlugBounds(myDocument, myPage, mySlugOffset, mySlugHeight){ var myPageWidth = myDocument.documentPreferences.pageWidth; var myPageHeight = myDocument.documentPreferences.pageHeight
//Because "right" and "left" margins become "inside" and "outside"
//for pages in a facing pages view, we have to use a special case for
//left hand pages.
if(myPage.side == PageSideOptions.leftHand){ var myX2 = myPageWidth - myPage.marginPreferences.left; var myX1 = myPage.marginPreferences.right;
} else{ var myX1 = myPage.marginPreferences.left; var myX2 = myPageWidth - myPage.marginPreferences.right;
} var myY1 = myPageHeight + mySlugOffset; var myY2 = myY1 + mySlugHeight; return [myY1, myX1, myY2, myX2];
}
「beforePrint」イベントリスナーの例
beforePrint
プリ
ントを行う前にドキュメントの特定の属性を確認するイベントリスナーの追加方法を、次のスクリプトに示
します(完全なスクリプトについては、BeforePrint を参照してください)。
#targetengine "session"
//Adds an event listener that performs a preflight check on a document
//before printing. If the preflight check fails, the script cancels
//the print job.
main(); function main(){ var myEventListener = app.eventListeners.add("beforePrint", myBeforePrintHandler);
} function myBeforePrintHandler(myEvent){
//The parent of the event is the document.
var myDocument = myEvent.parent; if(myPreflight(myDocument) == false){ myEvent.stopPropagation(); myEvent.preventDefault();
第 8 章 イベント 選択に関連するイベントリスナーの例 131
} alert("Document did not pass preflight check.");
} else{alert("Document passed preflight check. Ready to print.");} function myPreflight(myDocument){ var myPreflightCheck = true; var myFontCheck = myCheckFonts(myDocument); var myGraphicsCheck = myCheckGraphics(myDocument); alert("Fonts: " + myFontCheck + "¥r" + "Links:" + myGraphicsCheck); if((myFontCheck == false)||(myGraphicsCheck == false)){ myPreflightCheck = false;
} return myPreflightCheck;
} function myCheckFonts(myDocument){
} function myCheckGraphics(myDocument){ var myGraphicsCheck = true; for(var myCounter = 0; myCounter < myDocument.allGraphics.length; myCounter++){ var myGraphic = myDocument.allGraphics[myCounter]; if(myGraphic.itemLink.status != LinkStatus.normal){ myGraphicsCheck = false;
}
} return myGraphicsCheck;
} var myFontCheck = true; for(var myCounter = 0; myCounter < myDocument.fonts.length; myCounter ++){ if(myDocument.fonts.item(myCounter).status != FontStatus.installed){ myFontCheck = false;
}
} return myFontCheck;
選択に関連するイベントリスナーの例
選択したり選択解除したりしたときには、 afterSelectionChanged
クトの属性(フォーマットや位置)を変更したときには、 afterSelectionAttributeChanged
イベントが発生
します。 この 2 つのイベントは、ユーザーアクションに応答するスクリプトを作成する場合に便利です。
選択が変更されたときにオブジェクトの種類を取得して表示する方法を、次のスクリプトに示します。 完全
なスクリプトについては、AfterSelectionChanged を参照してください。 var myDocument = app.documents.add(); myDocument.addEventListener("afterSelectionChanged", myDisplaySelectionType);
このスクリプトで参照されているイベントハンドラーを次に示します。 function myDisplaySelectionType(myEvent){ if(app.documents.length != 0){ if(app.documents.item(0).selection.length != 0){ var mySelection = app.documents.item(0).selection; var myString = "Selection Contents:¥r"; for(var myCounter = 0; myCounter < mySelection.length; myCounter++){ myString = myString + mySelection[myCounter].constructor.name + "¥r"
} alert(myString);
}
}
}
第 8 章 イベント 「onIdle」イベントリスナーの例 132
このスクリプトで追加したイベントリスナーを削除するには、RemoveAfterSelectionChanged スクリプトを実
行します。
選択の属性の変更に応答する方法を、次のスクリプトに示します。 この例では、選択で Registration スウォッ
チが適用されたかどうかをイベントハンドラーで確認します (Registration スウォッチを誤って適用すると、
業務用のプリンターで問題が発生する可能性があります)。 Registration スウォッチが適用されていた場合、変
更が意図的に行われたものであるかどうかをユーザーに確認します。 完全なスクリプトについては、
AfterSelectionAttributeChanged を参照してください。 app.addEvenListener("afterSelectionAttributeChanged", myCheckForRegistration);
このスクリプトで参照されているイベントハンドラーを次に示します。 function myCheckForRegistration(myEvent){ var myRegistrationSwatchUsed = false; if(app.selection.length != 0){ for(var myCounter = 0; myCounter < app.selection.length; myCounter++){ if((app.documents.item(0).selection[myCounter].fillColor == app.documents.item(0).swatches.item("Registration"))||
(app.documents.item(0).selection[myCounter].strokeColor == app.documents.item(0).swatches.item("Registration")){ myRegistrationSwatchUsed = true;
}
}
} if(myRegistrationSwatchUsed == true){ alert("The Registration swatch is applied to some of the¥robjects in the selection.
Did you really intend to apply this swatch?");
}
}
このスクリプトで追加したイベントリスナーを削除するには、RemoveAfterSelectionAttributeChanged スクリ
プトを実行します。
「onIdle」イベントリスナーの例
InDesign のアイドルタスクは、アプリケーションのイベントキューに処理対象のイベントが存在しないとき
に実行されます。 アイドルタスクは、スクリプトで簡単に実行できます。 onIdle
イベントにより、スクリプ
トベースのアイドルタスクを実行する方法が提供されます。 このイベントを使用して、InDesign および
InCopy がアイドル状態のときに自動的にスクリプトを実行できます。
IdleTask
に、イ
ベントオブジェクトは
IdleEvent
になります。
アイドルタスクの sleep
プロパティは、タスクが再度呼び出されるまでの時間です。
時間には、ユーザーの作業に支障が出ないだけの大きな値を設定する必要があります。ただし、この値は、
スクリプトで実行するタスクによって異なります。
方法は、アイドルタスクを中止する場合に便利です。
イベントリスナーを追加し、アイドルタスクからメッセージボックスを表示する方法を、次のスクリプトに
示します(完全なスクリプトについては、Reminder を参照してください)。
第 8 章 イベント 「onIdle」イベントリスナーの例 133
#targetengine "session" main(); function main()
{ var myIdleTask = app.idleTasks.add({name:"my_idle_task", sleep:10000}); var onIdleEventListener = myIdleTask.addEventListener(IdleEvent.ON_IDLE, onIdleEventHandler, false); alert("Created idle task " + myIdleTask.name + "; added event listener on " + onIdleEventListener.eventType);
} function onIdleEventHandler(myIdleEvent)
{ if (app.documents.length == 0)
{ var myDoc = app.documents.add(); alert("Created document " + myDoc.name + " in idle task."); return;
} var myTextFrames = app.activeDocument.pages.item(0).textFrames; if (myTextFrames.length == 0)
{ var myTextFrame = myTextFrames.add(); myTextFrame.geometricBounds = ["72pt", "72pt", "288pt", "288pt"]; myTextFrame.contents = "Text frame created in idle task"; alert("Created a text frame in idle task."); return;
}
//Delete idle task by setting its sleep time to zero.
myIdleEvent.parent.sleep = 0; alert("Nothing to do. Delete idle task.");
}
このスクリプトで作成したアイドルタスクを削除するには、次のスクリプトを実行します(完全なスクリプ
トについては、RemoveIdleTask を参照してください)。
#targetengine "session" main(); function main()
{ if (app.idleTasks.length == 0)
{ alert("There is no idle task.");
} else
{ var myIdleTaskName = "my_idle_task"; var myIdleTask = app.idleTasks.itemByName(myIdleTaskName); if (myIdleTask != null)
{ myIdleTask.remove();
} else
{ alert("There is no idle task " + myIdleTaskName);
}
}
}
すべてのアイドルタスクを削除するには、次のスクリプトを実行します(完全なスクリプトについては、
第 8 章 イベント 「onIdle」イベントリスナーの例 134
#targetengine "session" main(); function main()
{ var length = app.idleTasks.length; if (length == 0)
{
} else
{ alert("There is no idle task."); for (var i = length-1; i >=0; i--)
{ app.idleTasks.item(i).remove();
} alert(length + " idle task(s) removed.");
}
}
既存のアイドルタスクを表示するには、次のスクリプトを実行します(完全なスクリプトについては、
#targetengine "session" main(); function main()
{ var length = app.idleTasks.length; if (length == 0)
{
} else
{ alert("There is no idle task."); var str = ""; for (var i = 0; i < length; i++)
{ var myIdleTask = app.idleTasks.item(i); str += "idle task " + myIdleTask.id + ": " + myIdleTask.name + "¥n";
} alert(str);
}
}
9
メニュー
CS6
章の更新ステータス
変更なし
InDesign スクリプティングでは、メニュー項目の追加と削除、任意のメニューコマンドの実行、メニュー項
目へのスクリプトの割り当てを行うことができます。
この章では、InDesign のメニューをスクリプトで操作する方法について説明します。 最初は簡単なサンプル
スクリプトから始めて、徐々に複雑なスクリプトへと進んでいきます。
ここでは、読者が『Adobe InDesign スクリプティングチュートリアル』を既に読んでおり、スクリプトを作
成、インストール、実行する方法を理解しているものとして説明を行います。
メニューモデルについて
InDesign のメニュースクリプトモデルは、アプリケーションのユーザーインターフェイスに表示されるメ
ニューに対応する一連のオブジェクトによって構成されています(メインのメニューバーに表示されるメ
ニューだけでなく、パネルに用意されているメニューも含みます)。
オブジェクトには、次のオブジェク
トが含まれています。
menuItems
— メニューに表示されるメニューオプション (サブメニューは含まれません)
menuSeparators
— メニュー内のメニューオプションを区切るために使用される線
submenus
— 更なるメニュー選択が含まれているメニューオプション
menuElements
— メニューに表示されるすべての menuItems
、 menuSeparators
、 submenus
eventListeners
— メニューに対するユーザーアクションやスクリプトアクションに応答するためのリス
ナー
events
— メニューによって発生した events
どの menuItem
にも、 associatedMenuAction
というプロパティによって menuAction
が割り当てられていま
す。 そのメニュー項目が選択されたときの処理は、 menuAction
のプロパティによって定義されています。
ユーザーインターフェイスで定義されている menuAction
に加えて、独自の scriptMenuAction
を作成して、
メニュー項目にスクリプトを割り当てることができます。
1 つの menuAction
や scriptMenuAction
は、0 個以上の menuItem
に関連付けることができます。
次の図に、様々なメニューオブジェクトの関係を示します。
135
第 9 章 メニュー メニューモデルについて 136 application menuActions menuAction area checked enabled eventListeners id index label name events parent title scriptMenuActions scriptMenuAction same as menuAction eventListener eventListener
...
event event
...
すべてのメニューアクションのリスト(テキストファイル)を作成するには、次のスクリプトを実行します
(チュートリアルスクリプトの GetMenuActions より)。 var myMenuActionNames = app.menuActions.everyItem().name;
//Open a new text file.
var myTextFile = File.saveDialog("Save Menu Action Names As", undefined);
//If the user clicked the Cancel button, the result is null.
if(myTextFile != null){
//Open the file with write access.
myTextFile.open("w"); for(var myCounter = 0; myCounter < myMenuActionNames.length; myCounter++){ myTextFile.writeln(myMenuActionNames[myCounter]);
} myTextFile.close();
}
利用可能なメニューのリスト(テキストファイル)を作成するには、次のスクリプトを実行します(完全な
スクリプトについては、GetMenuNames を参照してください)。 InDesign には多数のメニューがあるので、こ
のスクリプトの実行には時間がかかる場合があります。
第 9 章 メニュー メニューモデルについて 137 var myMenu;
//Open a new text file.
var myTextFile = File.saveDialog("Save Menu Action Names As", undefined);
//If the user clicked the Cancel button, the result is null.
if(myTextFile != null){
//Open the file with write access.
myTextFile.open("w"); for(var myMenuCounter = 0;myMenuCounter< app.menus.length; myMenuCounter++){ myMenu = app.menus.item(myMenuCounter); myTextFile.writeln(myMenu.name); myProcessMenu(myMenu, myTextFile);
} myTextFile.close(); alert("done!");
} function myProcessMenu(myMenu, myTextFile){ var myMenuElement; var myIndent = myGetIndent(myMenu); for(var myCounter = 0; myCounter < myMenu.menuElements.length; myCounter++){ myMenuElement = myMenu.menuElements.item(myCounter); if(myMenuElement.getElements()[0].constructor.name != "MenuSeparator"){ myTextFile.writeln(myIndent + myMenuElement.name); if(myMenuElement.getElements()[0].constructor.name == "Submenu"){ if(myMenuElement.menuElements.length > 0){ myProcessMenu(myMenuElement, myTextFile);
}
}
}
}
} function myGetIndent(myObject){ var myString = "¥t"; var myDone = false; do{ if((myObject.parent.constructor.name == "Menu")||
(myObject.parent.constructor.name == "Application")){ myDone = true;
} else{ myString = myString + "¥t"; myObject = myObject.parent;
}
}while(myDone == false) return myString;
}
ローカライゼーションとメニュー名
InDesign スクリプティングでは、 menuItem
、 menu
、 menuAction
、 submenu
はすべて名前で参照されます。
がって、アプリケーションがインストールされているロケールに依存せずにオブジェクトを指定する方法が
必要になります。 これを行うには、ロケールに依存せずに特定の項目を参照するための文字列が格納されて
いる内部データベースを使用します。 例えば、次のスクリプトを使用すれば、ロケールに依存しないメ
ニューアクション名を取得することができます(完全なスクリプトについては、GetKeyStrings を参照してく
ださい)。
第 9 章 メニュー スクリプトからのメニューアクションの実行 138 var myString = ""; var myMenuAction = app.menuActions.item("Convert to Note"); var myKeyStrings = app.findKeyStrings(myMenuAction.name); if(myKeyStrings.constructor.name == "Array"){ for(var myCounter = 0; myCounter < myKeyStrings.length; myCounter ++){ myString += myKeyStrings[myCounter] + "¥r";
}
} else{ myString = myKeyStrings;
} alert(myString);
注意 : ロケールに依存しない名前を取得する場合は、 menu
、 menuItem
、 submenu
の名前を取得するよりも、 menuAction
の名前を取得するほうが便利です。 menuAction
のタイトルは、単一の文字列である場合が多いか
らです。 findKeyStrings
メソッドで複数の文字列が返されま
す。
ロケールに依存しない名前を取得したら、スクリプトで使用することができます。 この文字列を使用したス
クリプトは、現在使用している InDesign と異なるロケールにインストールされている InDesign でも正常に機
能します。
ロケールに依存しない文字列を現在のロケールに変換するには、次のスクリプトを使用します(チュートリ
アルスクリプトの TranslateKeyString より)。 var myString = app.translateKeyString("$ID/NotesMenu.ConvertToNote"); alert(myString);
スクリプトからのメニューアクションの実行
InDesign に組み込まれている menuAction
は、いずれもスクリプトから実行することができます。 menuAction
が menuItem
に割り当てられているとは限りませんが、その点を除けば、スクリプトから menuAction
を実行することは、ユーザーインターフェイスでメニューオプションを選択することとまったく
応する menuAction
をスクリプトから実行すると同じダイアログボックスが表示されます。
スクリプトから menuAction
を実行する方法を、次のスクリプトに示します(完全なスクリプトについては、
//Get a reference to a menu action.
var myMenuAction = app.menuActions.item("$ID/NotesMenu.ConvertToNote");
//Run the menu action. This example action will fail if you do not
//have text selected.
myMenuAction.invoke();
注意 : 一般的に、InDesign のプロセスをスクリプトで自動化する場合、メニューアクションやユーザーイン
ターフェイスを選択することで必要な処理を実行するのは、あまりよい方法とは言えません。InDesign のス
クリプトオブジェクトモデルを操作するほうが、はるかに確実で強力な処理を実現できます。 メニューアク
ションは、選択やウィンドウの状態など、ユーザーインターフェイスの様々な条件に依存しています。 オブ
ジェクトモデルを使用すれば、InDesign ドキュメント内のオブジェクトを直接操作できるので、ユーザーイ
ンターフェイスに依存することなく、一貫性のある高速な処理を実現できます。
第 9 章 メニュー メニューやメニュー項目の追加 139
メニューやメニュー項目の追加
InDesign のユーザーインターフェイスと同じように、スクリプトでもメニューやメニュー項目の作成や削除
が行えます。 新しい場所に新しいメニューを作成して、あるサブメニューの内容をそのメニューに複製する
方法を、次のサンプルスクリプトに示します(完全なスクリプトについては、CustomizeMenu を参照してく
ださい)。 var myMainMenu = app.menus.item("Main"); var myTypeMenu = myMainMenu.menuElements.item("Type"); var myFontMenu = myTypeMenu.menuElements.item("Font"); var myKozukaMenu = myFontMenu.submenus.item("Kozuka Mincho Pro "); var mySpecialFontMenu = myMainMenu.submenus.add("Kozuka Mincho Pro"); for(myCounter = 0;myCounter < myKozukaMenu.menuItems.length; myCounter++){ var myAssociatedMenuAction = myKozukaMenu.menuItems.item(myCounter).associatedMenuAction; mySpecialFontMenu.menuItems.add(myAssociatedMenuAction);
}
このスクリプトで作成されたカスタムメニュー項目を削除するには、RemoveCustomMenu を使用します。 var myMainMenu = app.menus.item("$ID/Main"); try{ var mySpecialFontMenu = myMainMenu.submenus.item("Kozuka Mincho Pro"); mySpecialFontMenu.remove();
}catch(myError){}
メニューとイベント
ユーザーインターフェイスでメニューやサブメニューを選択すると、イベントが生成されます。これと同じ
ように、 menuAction
や scriptMenuAction
を実行した場合にも、イベントが生成されます。
用すれば、これらのイベントに応答するために eventListener
を登録することができます。
スクリプティングコンポーネントのイベントを次の表に示します。
オブジェクト
menu menuAction scriptMenuAction submenu
イベント
beforeDisplay afterInvoke beforeInvoke afterInvoke beforeInvoke beforeDisplay onInvoke beforeDisplay
説明
メニューの内容が表示される前に、登録したスクリプトが実
行されます。
関連付けられている menuItem
が選択されて、 onInvoke
イベン
トが発生した後に、登録したスクリプトが実行されます。
関連付けられている menuItem
が選択されて、 onInvoke
イベン
トが発生する前に、登録したスクリプトが実行されます。
関連付けられている menuItem
が選択されて、 onInvoke
イベン
トが発生した後に、登録したスクリプトが実行されます。
関連付けられている menuItem
が選択されて、 onInvoke
イベン
トが発生する前に、登録したスクリプトが実行されます。 scriptMenuAction
の有効/チェックのステータスに対する内
部要求が行われる前に、登録したスクリプトが実行されます。 scriptMenuAction
が呼び出されたときに、登録したスクリプ
トが実行されます。 submenu
の内容が表示される前に、登録したスクリプトが実行
されます。 event
や eventListener
を参照してください。
第 9 章 メニュー scriptMenuAction の操作 140
メニューに表示する項目を変更するには、 beforeDisplay event
に対する eventListener
メ
ニューが選択されると、登録したスクリプト(メニュー項目の有効化/無効化や名前の変更などの、メ
ニューに関連するタスクを実行するスクリプト)が eventListener
によって実行されます。
利用可能なフォント、最近使用したドキュメント、開いているウィンドウなどをメニューに表示するために、
内部的に使用されています。
scriptMenuAction の操作
scriptMenuAction
を使用すると、 menuAction
を新しく作成して、 onInvoke event
の発生時に指定のスクリプ
トを実行することができます。 scriptMenuAction
を作成してメニュー項目に割り当てる方法を、次のスクリプトに示します(完全なスクリ
プトについては、MakeScriptMenuAction を参照してください)。 このスクリプトでは、メニュー項目が選択さ
れると、単に警告が表示されます。 var mySampleScriptAction = app.scriptMenuActions.add("Display Message"); var myEventListener = mySampleScriptAction.eventListeners.add("onInvoke", function(){alert("This menu item was added by a script.");});
//If the submenu "Script Menu Action" does not already exist, create it.
try{ var mySampleScriptMenu = app.menus.item("$ID/Main").submenus.item(
"Script Menu Action"); mySampleScriptMenu.title;
} catch (myError){ var mySampleScriptMenu = app.menus.item("$ID/Main").submenus.add
("Script Menu Action");
} var mySampleScriptMenuItem = mySampleScriptMenu.menuItems.add(mySampleScriptAction);
このスクリプトで作成した menu
、 submenu
、 menuItem
、 scriptMenuAction
を削除するには、次のスクリプト
を実行します(チュートリアルスクリプトの RemoveScriptMenuAction より)。
#targetengine "session" var mySampleScriptAction = app.scriptMenuActions.item("Display Message"); mySampleScriptAction.remove(); var mySampleScriptMenu = app.menus.item("$ID/Main").submenus.item
("Script Menu Action"); mySampleScriptMenu.remove();
すべての scriptMenuAction
を削除することもできます。次のスクリプトにその例を示します(チュートリア
ルスクリプトの RemoveAllScriptMenuActions より)。 このスクリプトでは、 scriptMenuAction
のメニューリス
トも削除されますが、作成したメニューやサブメニューは削除されません。
#targetengine "session" app.scriptMenuActions.everyItem().remove();
現在のすべての scriptMenuAction
のリストを作成することができます。次のスクリプトにその例を示します
(チュートリアルスクリプトの ListScriptMenuActions より)。 var myScriptMenuActionNames = app.scriptMenuActions.everyItem().name;
//Open a new text file.
var myTextFile = File.saveDialog("Save Script Menu Action Names As", undefined);
//If the user clicked the Cancel button, the result is null.
if(myTextFile != null){
//Open the file with write access.
myTextFile.open("w"); for(var myCounter = 0; myCounter < myScriptMenuActionNames.length; myCounter++){ myTextFile.writeln(myScriptMenuActionNames[myCounter]);
} myTextFile.close();
}
第 9 章 メニュー さらに複雑なメニュースクリプティングの例 141 scriptMenuAction
を使用して、 beforeDisplay event
の発生時にスクリプトを実行することもできます。こ
の場合は、 scriptMenuAction
の状態に対する内部要求が行われる前に(メニュー項目が表示される直前に)
スクリプトが実行されます。 これは、スクリプトでメニュー名を変更したり、有効/チェックのステータス
を設定したりする場合に特に役立ちます。
次のサンプルスクリプトでは、 beforeDisplay event
に対する eventListener
を追加して、現在の選択を確認
するようにしています。 何も選択されていない場合は、 eventListener
のスクリプトによってメニュー項目が
無効化されます。 アイテムが選択されている場合は、メニュー項目が有効化されます。メニュー項目を選択
すると、選択されている最初のアイテムの種類が表示されます (完全なスクリプトについては、 var mySampleScriptAction = app.scriptMenuActions.add("Display Message"); var myEventListener = mySampleScriptAction.eventListeners.add("onInvoke", function()
{
//JavaScript function to run when the menu item is selected.
myString = app.selection[0].constructor.name; alert("The first item in the selection is a " + myString + ".");
}); var mySampleScriptMenu = app.menus.item("$ID/Main").submenus.add("Script Menu Action"); var mySampleScriptMenuItem = mySampleScriptMenu.menuItems.add(mySampleScriptAction); mySampleScriptMenu.eventListeners.add("beforeDisplay", function()
{
//JavaScript function to run before the menu item is drawns.
var mySampleScriptAction = app.scriptMenuActions.item("Display Message"); if(app.selection.length > 0){ mySampleScriptAction.enabled = true;
} else{ mySampleScriptAction.enabled = false;
}
});
さらに複雑なメニュースクリプティングの例
InDesign のユーザーインターフェイスで別の項目を選択すると、コンテキストメニューの内容が変わります。
選択したオブジェクトのプロパティに基づいてコンテキストメニューを変更する方法を、次のサンプルスク
リプトに示します。 このサンプルスクリプトは断片的なスクリプトです。完全なスクリプトについては、
LayoutContextMenu を参照してください。
次のスクリプトでは、レイアウトコンテキストメニュー(ページアイテムを選択すると表示されるコンテキ
ストメニュー)に新規のメニュー項目を追加する方法を示します。 このスクリプトでは、 beforeDisplay eventListener
が追加されています。このイベントリスナーは、 menuItem
が既に存在するかどうかを確認し、
存在する場合は削除します。 これにより、グラフィックが選択されていない場合はコンテキストメニューに menuItem
が表示されず、コンテキストメニューに複数のメニュー項目が追加されるのを防ぎます。 eventListener
では、次に、グラフィックが選択されているかどうかを確認し、選択されている場合は新規
の scriptMenuItem
が作成されます。
第 9 章 メニュー さらに複雑なメニュースクリプティングの例 142
//The locale-independent name (aka "key string") for the
//Layout context menu is "$ID/RtMouseLayout".
var myLayoutContextMenu = app.menus.item("$ID/RtMouseLayout");
//Create the event handler for the "beforeDisplay"
//event of the Layout context menu.
var myBeforeDisplayListener = myLayoutContextMenu.addEventListener
("beforeDisplay", myBeforeDisplayHandler, false);
//This event handler checks the type of the selection.
//If a graphic is selected, the event handler adds the script menu
//action to the menu.
function myBeforeDisplayHandler(myEvent){ if(app.documents.length != 0){ if(app.selection.length > 0){ var myObjectList = new Array;
//Does the selection contain any graphics?
for(var myCounter = 0; myCounter < app.selection.length; myCounter ++){ switch(app.selection[myCounter].constructor.name){ case "PDF": case "EPS": case "Image": myObjectList.push(app.selection[myCounter]); break; case "Rectangle": case "Oval": case "Polygon": if(app.selection[myCounter].graphics.length != 0){ myObjectList.push(app.selection[myCounter].
graphics.item(0));
} break; default:
}
} if(myObjectList.length > 0){
//Add the menu item if it does not already exist.
if(myCheckForMenuItem(myLayoutContextMenu,
"Create Graphic Label") == false){ myMakeLabelGraphicMenuItem();
}
} else{
//Remove the menu item, if it exists.
if(myCheckForMenuItem(myLayoutContextMenu,
"Create Graphic Label") == true){ myLayoutContextMenu.menuItems.item("Create Graphic
Label").remove();
}
}
}
} function myMakeLabelGraphicMenuItem(){
//alert("Got to the myMakeLabelGraphicMenuItem function!"); if(myCheckForScriptMenuItem("Create Graphic Label") == false){
//alert("Making a new script menu action!"); var myLabelGraphicMenuAction = app.scriptMenuActions.add("Create
Graphic Label"); var myLabelGraphicEventListener = myLabelGraphicMenuAction.
eventListeners.add("onInvoke", myLabelGraphicEventHandler, false);
} var myLabelGraphicMenuItem = app.menus.item("$ID/RtMouseLayout").
menuItems.add(app.scriptMenuActions.item("Create Graphic Label")); function myLabelGraphicEventHandler(myEvent){
//alert("Got to myLabelGraphicEventListener!"); if(app.selection.length > 0){ var myObjectList = new Array;
第 9 章 メニュー さらに複雑なメニュースクリプティングの例 143
//Does the selection contain any graphics?
for(var myCounter = 0; myCounter < app.selection.length; myCounter ++){ switch(app.selection[myCounter].constructor.name){ case "PDF": case "EPS": case "Image": myObjectList.push(app.selection[myCounter]); break; case "Rectangle": case "Oval": case "Polygon": if(app.selection[myCounter].graphics.length != 0){ myObjectList.push(app.selection[myCounter].
graphics.item(0));
} break; default:
}
} if(myObjectList.length > 0){ myDisplayDialog(myObjectList);
}
}
//Function that adds the label.
function myAddLabel(myGraphic, myLabelType, myLabelHeight, myLabelOffset, myLabelStyleName, myLayerName){ var myLabelLayer; var myDocument = app.documents.item(0); var myLabel; myLabelStyle = myDocument.paragraphStyles.item
(myLabelStyleName); var myLink = myGraphic.itemLink; try{ myLabelLayer = myDocument.layers.item(myLayerName);
//if the layer does not exist, trying to get
//the layer name will cause an error.
myLabelLayer.name;
} catch (myError){ myLabelLayer = myDocument.layers.add(myLayerName);
}
//Label type defines the text that goes in the label.
switch(myLabelType){
//File name case 0: myLabel = myLink.name; break;
//File path case 1: myLabel = myLink.filePath; break;
//XMP description case 2: try{ myLabel = myLink.linkXmp.description;
} catch(myError){ myLabel = "No description available.";
} break;
//XMP author case 3: try{ myLabel = myLink.linkXmp.author
}
第 9 章 メニュー さらに複雑なメニュースクリプティングの例 144 catch(myError){ myLabel = "No author available.";
} break;
} var myFrame = myGraphic.parent; var myX1 = myFrame.geometricBounds[1]; var myY1 = myFrame.geometricBounds[2] + myLabelOffset; var myX2 = myFrame.geometricBounds[3]; var myY2 = myY1 + myLabelHeight; var myTextFrame = myFrame.parent.textFrames.add(myLabelLayer, undefined, undefined,{geometricBounds:[myY1, myX1, myY2, myX2],contents:myLabel}); myTextFrame.textFramePreferences.firstBaselineOffset =
FirstBaseline.leadingOffset; myTextFrame.paragraphs.item(0).appliedParagraphStyle = myLabelStyle;
} function myDisplayDialog(myObjectList){ var myLabelWidth = 100; var myStyleNames = myGetParagraphStyleNames
(app.documents.item(0)); var myLayerNames = myGetLayerNames(app.documents.item(0)); var myDialog = app.dialogs.add({name:"LabelGraphics"}); with(myDialog.dialogColumns.add()){
//Label type with(dialogRows.add()){ with(dialogColumns.add()){ staticTexts.add({staticLabel:"Label Type", minWidth:myLabelWidth});
} with(dialogColumns.add()){ var myLabelTypeDropdown = dropdowns.add(
{stringList:["File name", "File path", "XMP description", "XMP author"], selectedIndex:0});
}
}
//Text frame height with(dialogRows.add()){ with(dialogColumns.add()){ staticTexts.add({staticLabel:"Label Height", minWidth:myLabelWidth});
} with(dialogColumns.add()){ var myLabelHeightField = measurementEditboxes.add
({editValue:24, editUnits:MeasurementUnits.points});
}
}
//Text frame offset with(dialogRows.add()){ with(dialogColumns.add()){ staticTexts.add({staticLabel:"Label Offset", minWidth:myLabelWidth});
} with(dialogColumns.add()){ var myLabelOffsetField = measurementEditboxes.add
({editValue:0, editUnits:MeasurementUnits.points});
}
}
//Style to apply with(dialogRows.add()){ with(dialogColumns.add()){ staticTexts.add({staticLabel:"Label Style", minWidth:myLabelWidth});
第 9 章 メニュー さらに複雑なメニュースクリプティングの例 145
} with(dialogColumns.add()){ var myLabelStyleDropdown = dropdowns.add
({stringList:myStyleNames, selectedIndex:0});
}
}
//Layer with(dialogRows.add()){ with(dialogColumns.add()){ staticTexts.add({staticLabel:"Layer:", minWidth:myLabelWidth});
} with(dialogColumns.add()){ var myLayerDropdown = dropdowns.add
({stringList:myLayerNames, selectedIndex:0});
}
}
} var myResult = myDialog.show(); if(myResult == true){ var myLabelType = myLabelTypeDropdown.selectedIndex; var myLabelHeight = myLabelHeightField.editValue; var myLabelOffset = myLabelOffsetField.editValue; var myLabelStyle = myStyleNames[myLabelStyleDropdown.
selectedIndex]; var myLayerName = myLayerNames[myLayerDropdown.
selectedIndex]; myDialog.destroy();
}
}
}
} var myOldXUnits = app.documents.item(0).viewPreferences.
horizontalMeasurementUnits; var myOldYUnits = app.documents.item(0).viewPreferences.
verticalMeasurementUnits; app.documents.item(0).viewPreferences.
horizontalMeasurementUnits = MeasurementUnits.points; app.documents.item(0).viewPreferences.
verticalMeasurementUnits = MeasurementUnits.points; for(var myCounter = 0; myCounter < myObjectList.length; myCounter++){ var myGraphic = myObjectList[myCounter]; myAddLabel(myGraphic, myLabelType, myLabelHeight, myLabelOffset, myLabelStyle, myLayerName);
} app.documents.item(0).viewPreferences.
horizontalMeasurementUnits = myOldXUnits; app.documents.item(0).viewPreferences.
verticalMeasurementUnits = myOldYUnits;
} else{ myDialog.destroy();
}
10
プリフライトの操作
CS6
章の更新ステータス
変更なし
プリフライトを実行すると、パブリケーションを出力デバイスに送る前に、ファイルやフォント、アセット
(配置画像や PDF ファイルなど)、プリンター設定、トラップスタイルなど、必要なものがすべてそろってい
るかどうかを検証できます。 例えば、画像を低解像度プロキシで配置しているが、使用中のハードディスク
(またはワークグループのサーバー)で高解像度の元の画像にアクセスできない場合、プリント処理時にエ
ラーが発生することがあります。 プリフライトは、このような問題を検証します。 プリフライトは、ユー
ザーの作業中にバックグラウンドで実行できます。
この章では、スクリプトを使用して、インタラクティブにプリフライトシステムを操作する方法について説
プリフライトを設定する方法を紹介します。 ユーザーインターフェイスでの設定方法を簡単に紹介し、その
後でスクリプトを使用して同じ設定を行う方法について説明します。
ここでは、読者が『Adobe InDesign スクリプティングチュートリアル』を既に読んでおり、スクリプトを作
成、インストール、実行する方法を理解しているものとして説明を行います。
プリフライトプロファイルの調査
InDesign のプリフライト機能は、プロファイルベースで、ルールに従って実行されます。また、パラメー
ターを使用します。 プリフライトプロファイルは、1 つ以上存在します。 最初は、[ 基本 ] という名前のプロ
ファイルが 1 つ用意されています。このプロファイルは読み取り専用で、変更したり削除したりできません。
プリフライトプロファイルには、様々なプリフライトルールが含まれています。 各ルールは、名前と複数の
データオブジェクトを保持しています。 各データオブジェクトには、名前、データ型、データ値があります。
データ値は変更することができます。 各ルールは、次のように設定できます。
無効 — プリフライトルールは無効化されます。
エラーを返す — プリフライトルールは、エラーレベルのフィードバックを返します。
警告を返す — プリフライトルールは、警告レベルのフィードバックを返します。
通知を返す — プリフライトルールは、通知レベルのフィードバックを返します。
スクリプトでもプロファイル情報を取得できます。
146
第 10 章 プリフライトの操作 プリフライトプロファイルの調査 147
プリフライトプロファイルの一覧表示
すべてのプリフライトプロファイルを一覧表示する方法を、次のスクリプトに示します。 完全なスクリプト
については、ListPreflightProfiles を参照してください。 var profiles = app.preflightProfiles; var profileCount = profiles.length;| var str = "Preflight profiles: "; for (var i = 0; i < profileCount; i++)
{ if (i != 0)
{ str += ", ";
} str += profiles.item(i).name;
} alert(str);
プリフライトルールの一覧表示
プロファイル内のすべてのプリフライトルールを一覧表示する方法を、次のスクリプトに示します。 完全な
スクリプトについては、ListPreflightRules を参照してください。
// Assume the [Basic] profile exists var myProfile = app.preflightProfiles.item(0); var myRules = myProfile.preflightProfileRules; var ruleCount = myRules.length; var str = "Preflight rules of " + myProfile.name + ": "; for (var i = 0; i < ruleCount; i++)
{ if (i > 0)
{ str += ", ";
} str += myRules.item(i).name;
} alert(str);
プリフライトデータオブジェクトの一覧表示
プロファイルのルール内のすべてのプリフライトデータオブジェクトを一覧表示する方法を、次のスクリプ
トに示します。 完全なスクリプトについては、ListPreflightDataObjects を参照してください。
// Assume the [Basic] profile exists.
var myProfile = app.preflightProfiles.item(0);
// rule ADBE_BlankPages var myRule = myProfile.preflightProfileRules.item(0); var dataObjects = myRule.ruleDataObjects; var dataObjectCount = dataObjects.length; var str = "Preflight rule data objects of " + myProfile.name + "." + myRule.name + ": "; for (var i = 0; i < dataObjectCount; i++)
{ if (i > 0)
{ str += "; ";
} str += dataObjects.item(i).name + ", "; str += getDataObjectDataType(dataObjects.item(i).dataType) + ", "; str += dataObjects.item(i).dataValue;
} alert(str);
第 10 章 プリフライトの操作 function getDataObjectDataType(type)
{ if (type == RuleDataType.BOOLEAN_DATA_TYPE)
{ return "Boolean";
} else if (type == RuleDataType.INTEGER_DATA_TYPE)
{ return "Integer";
} else if (type == RuleDataType.LIST_DATA_TYPE)
{ return "List";
} else if (type == RuleDataType.OBJECT_DATA_TYPE)
{ return "Object";
} else if (type == RuleDataType.REAL_DATA_TYPE)
{ return "Real";
} else if (type == RuleDataType.SHORT_INTEGER_DATA_TYPE)
{ return "Short Integer";
} else if (type == RuleDataType.STRING_DATA_TYPE)
{
} else
{ return "String"; return type;
}
}
プリフライトプロファイルの調査 148
第 10 章 プリフライトの操作 プリフライトプロファイルの読み込み 149
プリフライトプロファイルの読み込み
プリフライトパネルからプリフライトプロファイルを読み込むには、プリフライトパネル/プロファイルを
定義を選択します。続いて、プリフライトプロファイルウィンドウのドロップダウンメニューで「プロファ
イルを読み込み」を選択します。
また、スクリプトでプロファイルを読み込むこともできます。 次のスクリプトでは、Test という名前のプロ
ファイルを読み込みます。 完全なスクリプトについては、ImportPreflightProfile を参照してください。 var myProfile = app.loadPreflightProfile(File("/c/Test.idpp")); if (myProfile == null)
{
} else
{ alert("The profile did not load successfully"); alert("Preflight profile " + myProfile.name + " is loaded.")
}
プロファイルの作成には、スクリプトよりもプリフライトパネルを使用したほうが簡単です。 1 つのワークフ
ローとしては、ユーザーインターフェイスですべてのプロファイルを作成し、プロファイルをファイルに書
き出し、書き出したファイルをスクリプトで読み込むといった流れが考えられます。 この方法を使用すると、
スクリプトを使用して手動でルールを追加する手間を省くことできます。
第 10 章 プリフライトの操作 プリフライトプロファイルの作成 150
プリフライトプロファイルの作成
プリフライトパネルからプリフライトプロファイルを作成するには、プリフライトパネル/プロファイルを
定義を選択し、プラス記号(+)を選択して新しいプリフライトプロファイルを追加します。 プロファイルに
名前を付け、使用可能なルールのデータ値をすべて入力します。
また、スクリプトでプロファイルを作成することもできます。 次のスクリプトでは、Test という名前のプロ
ファイルを 1 つ追加します。 完全なスクリプトについては、CreatePreflightProfile を参照してください。
//Add a new preflight profile var myProfile = app.preflightProfiles.add(); if (myProfile == null)
{ alert("The profile did not add successfully");
} else
{ alert("Preflight profile " + myProfile.name + " is added.")
}
//Rename the profile.
var oldName = myProfile.name
myProfile.name = "Test"; myProfile.description = "Test description"; alert("Preflight profile " + oldName + " is renamed to " + myProfile.name + ".")
プリフライトプロファイルの名前は、一意である必要があります。 このスクリプトを同じインスタンスの
InDesign で 2 回以上実行すると、エラーが発生し、該当する名前のプロファイルは既に存在していると通知
されます。 app.preflightProfiles.itemByName()
を使用して既存のプロファイル
にアクセスするか、プロファイルが存在するかどうかを確認して削除します。次のスクリプトにその例を示
第 10 章 プリフライトの操作 ルールの追加 151 function removeProfile(name)
{
//Lookup the existing preflight profile by name var oldProfile = app.preflightProfiles.itemByName(name);
//If a profile with that name was found if (oldProfile != null)
{ oldProfile.remove();
}
}
ルールの追加
プリフライトプロファイルには、相互排他的なルール一式が含まれます。 プロファイルにルールを追加する
には、次の手順に従います。
1.
プロファイルに、名前による指定方式でルールを追加します。
名前による指定方式でルールが追加されます。 ルール名について詳しくは、
ルール」 を参照してください。 次のスクリプトでは、プロファイルに ADBE_PageSizeOrientation のルール
を追加しています。
//Add a rule that requires a specific page size and orientation
//(portrait or landscape).
const RULE_NAME = "ADBE_PageSizeOrientation"; var myRule = myProfile.preflightProfileRules.add(RULE_NAME);
2.
ルールのデータ値を設定します。
すべてではありませんが、多くのルールにはデータプロパティが含まれています。 InDesign で使用可能な
ADBE_PageSizeOrientation のルールには、固有のデータプロパティが含まれており、このプロパティでは
ページサイズを指定できます。 次のスクリプトでは、許可するページの高さと幅、許容範囲(誤差)、
ページ方向の処理オプションを設定しています。
//Requires the page size to be 8.5in x 11in (Letter Size)
//enters a value for tolerance myRule.ruleDataObjects.add("tolerance", RuleDataType.realDataType, 0.01);
//Sets the width to the point equivalent of 8.5 inches myRule.ruleDataObjects.add("width", RuleDataType.realDataType, 612);
//Sets the width to the point equivalent of 11 inches myRule.ruleDataObjects.add("height", RuleDataType.realDataType, 792);
//true = ignore orientation is checked myRule.ruleDataObjects.add("ignore_orientation", RuleDataType.booleanDataType, true);
3.
ルールのレポート状態を設定します。
この設定を行うには、ルールの flag
プロパティを使用します。
エラー)があり、この選択肢は
PreflightRuleFlag
列挙法で制御されます。
//set the rule to return an error myRule.flag = PreflightRuleFlag.returnAsError;
第 10 章 プリフライトの操作 プロファイルの処理 152
プロファイルの処理
デスクトップ版の InDesign では、プリフライトエラーはユーザーインターフェイスでレポートされます。
(特に InDesign Server の)スクリプトでは、エラーは必要に応じて生成されます。 次のスクリプトでは、
InDesign ドキュメントに対する処理を行います (完全なスクリプトについては、ProcessPreflightProfile を参
照してください)。 エラーが発生した場合は、新しい PDF ファイルにエラー結果が書き込まれます。 出力結果
の例については、スクリプトの後のスクリーンショットを参照してください。
// Assume there is a document.
var myDoc = app.documents.item(0);
// Assume the Test preflight profile exists.
var myProfile = app.preflightProfiles.itemByName("Test");
//Process the myDoc with the rule var myProcess = app.preflightProcesses.add(myDoc, myProfile); myProcess.waitForProcess(); var myResults = myProcess.processResults;
//If errors were found if (myResults != "None")
{
//Export the file to PDF. The "true" value selects to open the file after export.
myProcess.saveReport(File("C:¥PreflightResults.pdf"), true);
}
//Cleanup myProcess.remove();
テキストファイルでの作成が望ましい場合は、単純に、出力ファイルの名前に
.txt
の拡張子を付けます。
また、エラーに対する繰り返し処理をユーザー自身が行いたい場合も考えられます。 エラー配列にアクセス
する方法を、次のスクリプトに示します。 完全なスクリプトについては、ProcessPreflightProfileShowErrors を
参照してください。
第 10 章 プリフライトの操作
ルール名
ADBE_BlankPages
ADBE_BleedSlug
ADBE_BleedTrimHazard
ADBE_CMYPlates
ADBE_Colorspace
ADBE_ConditionIndicators
ADBE_CrossReferences
ADBE_FontUsage
ADBE_ImageColorManagement
ADBE_ImageResolution
ADBE_InteractiveContent
カスタムルール 153
//If errors were found if (myResults != "None")
{
// array containing detailed results var errors = myProcess.aggregatedResults
// Show the errors in a message box.
var str = "Document: " + errors[0] + ", Profile: " + errors[1] + ", Results: [" var errorResults = errors[2] for (var i = 0; i < errorResults.length; i++)
{ if (i > 1)
{ str += ", "
} str += errorResults[i][1]
} str = str + "]" alert(str)
}
カスタムルール
プリフライトパネルやスクリプトからはカスタムルールを作成できません。ただし、C++ プラグインを使用
すると、カスタムルールを作成することができます。InDesign Products SDK にはサンプルの PreflightRule が含
まれおり、この中に、プラグインを使用してカスタムルールを追加する方法が示されています。
使用可能なルール
スクリプトでルールを使用する際に苦労する点は、ルールの名前とプロパティを把握しておくことです。
ルールの動的な性質上(ルールは実際には単なる文字列であるため)、ルールの具体的な名前とプロパティは
を参照してください。 ご参考までに、SDK には
DumpPreflightRules.jsx
スクリプトが用意されています。このスクリプトは、次のような出力の HTML ファ
イルを作成します(SDK¥docs¥references¥PreflightRules.html)。 カスタムルールを追加するプラグインを使用
している場合、スクリプトを実行して新しい名前とプロパティを取得できます。
ルールのプロパティ
155 ページの「ADBE_BleedTrimHazard」
なし
なし
156 ページの「ADBE_CrossReferences」
156 ページの「ADBE_ImageColorManagement」
157 ページの「ADBE_ImageResolution」
なし
第 10 章 プリフライトの操作 使用可能なルール 154
ルール名
ADBE_LayerVisibility
ADBE_MissingFonts
ADBE_MissingGlyph
ADBE_MissingModifiedGraphics
ADBE_OPI
ADBE_Overprint
ADBE_OversetText
ADBE_PageCount
ADBE_PageSizeOrientation
ADBE_Registration
ADBE_ScaledGraphics
ADBE_ScaledType
ADBE_SmallText
ADBE_SpellCheck
ADBE_SpotColorSetup
ADBE_StrokeRequirements
ADBE_TextOverrides
ADBE_TransparencyBlending
ADBE_TransparencyUsage
ADBE_WhiteOverprint
ADBE_BlankPages
データ型
Boolean
Boolean
ADBE_BleedSlug
データ型
Real
Real
Integer
名前
ignore_master ignore_nonprinting
名前
bleed_b bleed_b_aux bleed_comparison_type
なし
なし
なし
なし
ルールのプロパティ
なし
なし
なし
157 ページの「ADBE_PageSizeOrientation」
なし
なし
158 ページの「ADBE_StrokeRequirements」
159 ページの「ADBE_TransparencyBlending」
なし
なし
デフォルト値
true true
デフォルト値
9
9
3
第 10 章 プリフライトの操作
Real
Real
Real
Real
Real
データ型
Boolean
Real
Real
Real
Real
Real
Real
Real
Real
Integer
Boolean
Real
Real
ADBE_BleedTrimHazard
データ型
Boolean
Real
Real
Real
Real
Real
Real
名前
bleed_enabled bleed_l bleed_l_aux bleed_r bleed_r_aux bleed_t bleed_t_aux slug_b slug_b_aux slug_comparison_type slug_enabled slug_l slug_l_aux slug_r slug_r_aux slug_t slug_t_aux tolerance
名前
binding_enabled binding_width live_b live_l live_r live_t tolerance
18
18
18
18
デフォルト値
false
1
0.01
18
18
18
18
0.01
3 false
18
18
9
9
18
18
9
9
9
9
デフォルト値
true
使用可能なルール 155
第 10 章 プリフライトの操作
ADBE_Colorspace
データ型
Boolean
Boolean
Boolean
Boolean
Boolean
ADBE_CrossReferences
データ型
Boolean
Boolean
ADBE_FontUsage
名前
no_cmyk no_gray no_lab no_rgb no_spot
名前
xrefs_out_of_date xrefs_unresolved
データ型
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
ADBE_ImageColorManagement
名前
no_ATC no_Bitmap no_CID no_MultipleMaster no_OpenTypeCFF no_OpenTypeCID no_OpenTypeTT no_TrueType no_Type1 no_protected
データ型
Boolean
Boolean
Boolean
名前
no_cmyk_profiles no_image_overrides overrides_exclude_uncal
デフォルト値
false false false false false
デフォルト値
true true false false false false
デフォルト値
false false false false false true
デフォルト値
true true true
使用可能なルール 156
第 10 章 プリフライトの操作
ADBE_ImageResolution
データ型
Boolean
Real
Boolean
Real
Boolean
Real
Boolean
Real
Boolean
Real
Boolean
Real
Real
ADBE_PageCount
名前
bw_max_enabled bw_max_res bw_min_enabled bw_min_res color_max_enabled color_max_res color_min_enabled color_min_res gray_max_enabled gray_max_res gray_min_enabled gray_min_res tolerance
データ型
Integer
Integer
Integer
ADBE_PageSizeOrientation
名前
comparison_type comparison_value comparison_value_aux
データ型
Real
Boolean
Real
Real
名前
height ignore_orientation tolerance width
1200 true
250
0.5
1200 true
250 false
デフォルト値
false
2400 true
800 false
1
1
デフォルト値
2
デフォルト値
792 false
0.01
612
使用可能なルール 157
第 10 章 プリフライトの操作
ADBE_ScaledGraphics
データ型
Real
ADBE_ScaledType
データ型
Boolean
Real
ADBE_SmallText
名前
max_scale
名前
ignore_justification max_scale
データ型
Real
Boolean
ADBE_SpotColorSetup
名前
minSize minSize_trap_safe_only
データ型
Boolean
Boolean
Integer
Boolean
ADBE_StrokeRequirements
名前
lab_spots lab_spots_enabled max_spots max_spots_enabled
データ型
Real
Boolean
名前
min_width min_width_trap_safe_only
デフォルト値
100.5
デフォルト値
true
100.5
デフォルト値
4 false
デフォルト値
true false
1 true
デフォルト値
0.125
false
使用可能なルール 158
第 10 章 プリフライトの操作
ADBE_TextOverrides
データ型
Boolean
Boolean
Boolean
Boolean
名前
ignore_color_overrides ignore_font_overrides ignore_kerning_tracking_overrides ignore_language_overrides
ADBE_TransparencyBlending
データ型
Integer
名前
space
デフォルト値
false false false false
デフォルト値
3
使用可能なルール 159
11
ダイナミックドキュメントの作成
CS6
章の更新ステータス
変更なし
InDesign では、Web やオンラインで使用するドキュメントを作成できます。これは、Rich Interactive
ンクなどインタラクティブなコンテンツが含まれます。 InDesign ドキュメントは、SWF や XFL、PDF に書き出
すことができます。 SWF および XFL ファイルの場合は、ドキュメントにアニメーション、ボタン、マルチス
テートオブジェクト、ムービー、サウンドクリップを含めることができます。 InDesign のプレビューパネル
を使用すると、書き出す前に、いくつかの種類のダイナミックコンテンツをテストすることができます。
この章では、スクリプトを使用してダイナミックドキュメントを作成する方法について説明します。 PDF、
SWF および XFL 形式で書き出す方法について詳しくは、ユーザーガイドの「ドキュメントを使用した作業」
の章を参照してください。
ムービーとサウンドの読み込み
InDesign では、ムービーファイルやサウンドファイルを読み込み、書き出し後の PDF、SWF、XFL ドキュメン
トで表示したり再生したりすることができます。 InDesign ドキュメント内のムービーとサウンドは、InDesign
ページ上のコンテナオブジェクトに含まれるという点でグラフィックによく似ています。 ただし、グラ
フィックとは異なり、読み込んだマルチメディアファイルのコンテンツは InDesign ページ上で表示(または
再生)できません。 ファイルを表示するには、プレビューパネルでページを表示するか、ファイルを書き出
してコンテンツを表示可能なビューア(Adobe Reader や Web ブラウザーなど)でそのファイルを開く必要が
あります。
スクリプトを使用して、書き出し後のダイナミックドキュメント内のサウンドやムービーの再生プロパティ
を制御できます。 また、サウンドやムービーが含まれているページアイテムに、プレビュー画像(「ポス
ター」画像)を追加することもできます。
ムービーを読み込み、書き出し後のドキュメントのムービーの表示と再生仕様を制御する方法を、次のスク
リプトに示します(完全なスクリプトについては、PlaceMovie を参照してください)。
//Given a page "myPage"... var myFrame = myPage.rectangles.add({geometricBounds:[72, 72, 288, 288]});
//Import a movie file (you'll have to provide a valid file path on your system); var myMovie = myFrame.place(File("/c/movie.flv"))[0];
//Set movie properties.
myMovie.embedInPDF = true; myMovie.showControls = true;
//Add a preview image. You'll have to provide a valid path on your system.
myMovie.posterFile = File("/c/movie poster.jpg");
サウンドファイルを読み込み、書き出し後のドキュメントのサウンドの再生と表示を制御する方法を、次の
スクリプトに示します(完全なスクリプトについては、PlaceSound を参照してください)。
160
第 11 章 ダイナミックドキュメントの作成 ボタンの作成 161
//Given a page "myPage"...
//Import a sound file (you'll have to provide a valid file path on your system); var mySound = myPage.place(File("/c/sound.mp3"), [72, 72])[0];
//Set sound properties.
mySound.embedInPDF = true; mySound.doNotPrintPoster = true; mySound.soundLoop = true; mySound.stopOnPageTurn = true;
//Add a preview image. You'll have to provide a valid path on your system.
mySound.posterFile = File("/c/sound poster.jpg");
ボタンを使用して、サウンドやムービーの再生を制御することもできます。 スクリプトでボタンを操作する
方法について詳しくは、次の節を参照してください。
ボタンの作成
ボタンは多くの場合、ダイナミックドキュメントでのナビゲーションに使用します。 ボタンには、「通常」、
楕円形、テキストフレーム、画像など)を含めることもできます。 ボタンは一度に 1 つのステートしか表示
できません。その他のステートは、マウスアクションによって呼び出されたときに表示されます。
動作は、ユーザーが特定のマウスアクションを実行したときに、ボタンがどのように反応するかを制御しま
タンには、複数の動作を含めることができます。
書き出し後の PDF または SWF で次のページを表示する簡単なボタンを作成する方法を、次のスクリプトに示
します(完全なスクリプトについては、SimpleButton を参照してください)。 このボタンでは、「通常」ス
テートのみを使用しています。
//Given a page "myPage" and a document containing the color "Red"...
//Make a button by converting a page item.
var myRightArrow = myPage.polygons.add({fillColor:myDocument.colors.item("Red"), name:"GoToNextPageButton"}); myRightArrow.paths.item(0).entirePath = [[72, 72],[144,108],[72, 144]]; var myButton = myPage.buttons.add({geometricBounds:[72, 72, 144, 144]}); myButton.states.item(0).addItemsToState(myRightArrow); var myGoToNextPageBehavior = myButton.gotoNextPageBehaviors.add({behaviorEvent:BehaviorEvents.mouseUp});
3 種類の各ボタンステートの外観を変更するページアイテムが含まれた、もう少し複雑なボタンを作成する
方法を、次のスクリプトに示します (完全なスクリプトについては、ButtonStates を参照してください)。
第 11 章 ダイナミックドキュメントの作成 ボタンの作成 162
//Given a page "myPage" in a document "myDocument," containing the colors
//"Blue" and "Red"...
//Make a button "from scratch." var myButton = myPage.buttons.add({geometricBounds:[72, 72, 144, 144], name:"GoToNextPageButton"}); var myRightArrow = myButton.states.item(0).polygons.add({fillColor:myDocument.colors.item("Red")}); myRightArrow.paths.item(0).entirePath = [[72, 72],[144,108],[72, 144]];
//Add the Rollover state.
var myRolloverState = myButton.states.add();
//Add a shadow to the polygon in the Rollover state.
var myRolloverArrow = myRolloverState.polygons.add({fillColor:myDocument.colors.item("Red")}); myRolloverArrow.paths.item(0).entirePath = [[72, 72],[144,108],[72, 144]]; var myFillTransparencySettings = myRolloverArrow.fillTransparencySettings; myFillTransparencySettings.dropShadowSettings.mode = ShadowMode.drop; myFillTransparencySettings.dropShadowSettings.angle = 90; myFillTransparencySettings.dropShadowSettings.xOffset = 0; myFillTransparencySettings.dropShadowSettings.yOffset = 0; myFillTransparencySettings.dropShadowSettings.size = 6;
//Add a shadow to the polygon in the Click state.
var myClickState = myButton.states.add(); var myClickArrow = myClickState.polygons.add({fillColor:myDocument.colors.item("Blue")}); myClickArrow.paths.item(0).entirePath = [[72, 72],[144,108],[72, 144]];
//Set the behavior for the button.
var myGoToNextPageBehavior = myButton.gotoNextPageBehaviors.add({behaviorEvent:BehaviorEvents.mouseUp});
ボタンを使用して、ムービーファイルやサウンドファイルの再生を制御することもできます。 ムービーファ
イルの再生を制御するボタン一式を使用した例を、次のスクリプトに示します(完全なスクリプトについて
は、MovieControl を参照してください)。
//Given a page "myPage" in a document "myDocument,"
//containing the colors "Gray" and "Red"...
var myFrame = myPage.rectangles.add({geometricBounds:[72, 72, 288, 288]});
//Import a movie file (you'll have to provide a valid file path on your system); myFrame.place(File("/c/movie.flv"));
//Create the movie "Start" button.
var myPlayButton = myPage.buttons.add({geometricBounds:[294,186,354,282], name:"PlayMovieButton"}); var myRightArrow = myPlayButton.states.item(0).polygons.add({fillColor:myDocument.colors.item("Gray")}); myRightArrow.paths.item(0).entirePath = [[186, 294],[186,354],[282, 324]];
//Add the Rollover state.
var myRolloverState = myPlayButton.states.add();
//Add a shadow to the polygon in the Rollover state.
var myRolloverArrow = myRolloverState.polygons.add({fillColor:myDocument.colors.item("Gray")}); myRolloverArrow.paths.item(0).entirePath = [[186, 294],[186,354],[282, 324]]; var myFillTransparencySettings = myRolloverArrow.fillTransparencySettings; myFillTransparencySettings.dropShadowSettings.mode = ShadowMode.drop; myFillTransparencySettings.dropShadowSettings.angle = 90; myFillTransparencySettings.dropShadowSettings.xOffset = 0; myFillTransparencySettings.dropShadowSettings.yOffset = 0; myFillTransparencySettings.dropShadowSettings.size = 6;
//Add a shadow to the polygon in the Click state.
var myClickState = myPlayButton.states.add(); var myClickArrow = myClickState.polygons.add({fillColor:myDocument.colors.item("Red")}); myClickArrow.paths.item(0).entirePath = [[186, 294],[186,354],[282, 324]];
//Set the behavior for the button.
var myMovieStartBehavior = myPlayButton.movieBehaviors.add({movieItem:myFrame.movies.item(0), behaviorEvent:BehaviorEvents.mouseUp, operation:MoviePlayOperations.play});
//Create the movie "Stop" button.
var myStopButton = myPage.buttons.add({geometricBounds:[294,78,354,174], name:"StopMovieButton"}); var myNormalRectangle = myStopButton.states.item(0).rectangles.add({geometricBounds:[294,78,354,174],
第 11 章 ダイナミックドキュメントの作成 マルチステートオブジェクトの作成 163 fillColor:myDocument.colors.item("Gray")}); myRolloverState = myStopButton.states.add(); var myRolloverRectangle = myRolloverState.rectangles.add({geometricBounds:[294,78,354,174], fillColor:myDocument.colors.item("Gray")}); var myFillTransparencySettings = myRolloverRectangle.fillTransparencySettings; myFillTransparencySettings.dropShadowSettings.mode = ShadowMode.drop; myFillTransparencySettings.dropShadowSettings.angle = 90; myFillTransparencySettings.dropShadowSettings.xOffset = 0; myFillTransparencySettings.dropShadowSettings.yOffset = 0; myFillTransparencySettings.dropShadowSettings.size = 6; myClickState = myStopButton.states.add(); var myClickRectangle = myClickState.rectangles.add({geometricBounds:[294,78,354,174], fillColor:myDocument.colors.item("Red")}); var myMovieStopBehavior = myStopButton.movieBehaviors.add({movieItem:myFrame.movies.item(0), behaviorEvent:BehaviorEvents.mouseUp, operation:MoviePlayOperations.stop});
また、ボタンはマルチステートオブジェクトの外観を制御する場合に重要です。この点については、次の節
で説明します。
マルチステートオブジェクトの作成
マルチステートオブジェクト(MSO)は、複数のステートを含んでいる点と、一度に 1 つのステートしか表
示できない点がボタンに似ています。 ボタンと異なる点は、マルチステートオブジェクトにはいくつでもス
テートを含めることができることです。ボタンには最大 3 つまでしかステートを含めることができません。
マルチステートオブジェクトは、ステートの表示方法を変更する場合はボタンに依存します。
簡単なマルチステートオブジェクトを作成し、このオブジェクトのステート表示を制御するボタンを追加す
る方法を、次のスクリプトに示します(完全なスクリプトについては、MakeMultiStateObject を参照してく
//Given a document "myDocument" and a page "myPage" and
//four colors "myColorA," "myColorB," "myColorC," and "myColorD"...
var myMSO = myPage.multiStateObjects.add({name:"Spinner", geometricBounds:[72, 72, 144, 144]});
//New multistate objects contain two states when they're created. Add two more.
myMSO.states.item(0).name = "Up"; myMSO.states.item(1).name = "Right";
//Add two more states.
myMSO.states.add({name:"Down"}); myMSO.states.add({name:"Left"});
//Add page items to the states.
var myPolygon = myMSO.states.item(0).polygons.add({fillColor:myColorA, strokeColor:myDocument.swatches.item("None")}); myPolygon.paths.item(0).entirePath = [[72, 144], [144, 144], [108, 72]]; myPolygon = myMSO.states.item(1).polygons.add({fillColor:myColorB, strokeColor:myDocument.swatches.item("None")}); myPolygon.paths.item(0).entirePath = [[72, 72], [72, 144], [144, 108]]; myPolygon = myMSO.states.item(2).polygons.add({fillColor:myColorC, strokeColor:myDocument.swatches.item("None")}); myPolygon.paths.item(0).entirePath = [[72, 72], [108, 144], [144, 72]]; myPolygon = myMSO.states.item(3).polygons.add({fillColor:myColorD, strokeColor:myDocument.swatches.item("None")}); myPolygon.paths.item(0).entirePath = [[144, 72], [72, 108], [144, 144]];
一般的に、マルチステートオブジェクトのステート表示を制御するには、ボタンを使用します。 次のスクリ
プトにその例を示します(完全なスクリプトについては、MultiStateObjectControl を参照してください)。
第 11 章 ダイナミックドキュメントの作成 アニメーションの操作 164
//Given a document "myDocument" and a page "myPage" and
//four colors "myColorA," "myColorB," "myColorC," and "myColorD"...
var myMSO = myPage.multiStateObjects.add({name:"Spinner", geometricBounds:[72, 72, 144, 144]});
//New multistate objects contain two states when they're created. Add two more.
myMSO.states.item(0).name = "Up"; myMSO.states.item(1).name = "Right";
//Add two more states.
myMSO.states.add({name:"Down"}); myMSO.states.add({name:"Left"});
//Add page items to the states.
var myPolygon = myMSO.states.item(0).polygons.add({fillColor:myColorA, strokeColor:myDocument.swatches.item("None")}); myPolygon.paths.item(0).entirePath = [[72, 144], [144, 144], [108, 72]]; myPolygon = myMSO.states.item(1).polygons.add({fillColor:myColorB, strokeColor:myDocument.swatches.item("None")}); myPolygon.paths.item(0).entirePath = [[72, 72], [72, 144], [144, 108]]; myPolygon = myMSO.states.item(2).polygons.add({fillColor:myColorC, strokeColor:myDocument.swatches.item("None")}); myPolygon.paths.item(0).entirePath = [[72, 72], [108, 144], [144, 72]]; myPolygon = myMSO.states.item(3).polygons.add({fillColor:myColorD, strokeColor:myDocument.swatches.item("None")}); myPolygon.paths.item(0).entirePath = [[144, 72], [72, 108], [144, 144]]; var myButton = myPage.buttons.add({geometricBounds:[72, 72, 144, 144]}); myRolloverState = myButton.states.add(); var myRolloverRectangle = myRolloverState.rectangles.add({geometricBounds:[72, 72, 144, 144]}); var myFillTransparencySettings = myRolloverRectangle.strokeTransparencySettings; myFillTransparencySettings.dropShadowSettings.mode = ShadowMode.drop; myFillTransparencySettings.dropShadowSettings.angle = 90; myFillTransparencySettings.dropShadowSettings.xOffset = 0; myFillTransparencySettings.dropShadowSettings.yOffset = 0; myFillTransparencySettings.dropShadowSettings.size = 6; var myClickState = myButton.states.add(); var myNextStateBehavior = myButton.gotoNextStateBehaviors.add({associatedMultiStateObject:myMSO, behaviorEvent:BehaviorEvents.mouseDown, enableBehavior:true, loopsToNextOrPrevious:true});
アニメーションの操作
ページアイテムはアニメーション化することができます。アニメーション化するには、InDesign で作成した
ダイナミックドキュメントにモーションを追加します。 オブジェクトにアニメーションを適用するにはモー
ションプリセットを、アニメーションオブジェクトの動作を定義するにはモーションパスを、アニメーショ
ンの長さを制御するにはタイミング設定、タイミングリスト、タイミンググループを使用します。
オブジェクトの animationSettings
は、オブジェクトに適用されるアニメーションを制御します。
クトにアニメーション設定が適用されている場合、オブジェクトの hasCustomSettings
プロパティには true
が設定されます。オブジェクトがアニメーション化されない場合は、false が設定されます。
アニメーションの再生が開始される位置は、アニメーションを呼び出すイベントを基準に、ページアイテム
または親コンテナの 1 つ(通常はスプレッド)に割り当てられている timingSettings
オブジェクトのオブ
ジェクトとプロパティによって制御されます。
第 11 章 ダイナミックドキュメントの作成 アニメーションの操作 165
基本的なアニメーション
簡単なアニメーションの作成方法を、次のスクリプトに示します(完全なスクリプトについては、
SimpleAnimation を参照してください) 最も基本的な形式のアニメーションは、タイミング設定を使用せず
に適用することができます。
//Given a document "myDocument" and a page "myPage" and a color "myColorA"...
//Add a page items to animate.
var myPolygon = myPage.polygons.add({fillColor:myColorA, strokeColor:myDocument.swatches.item("None")}); myPolygon.paths.item(0).entirePath = [[72, 72], [72, 144], [144, 108]];
//Create a motion path.
var myMotionPathPoints = [[[[108,108],[108,108],[108,108]],[[516, 108],[516, 108],[516,
108]]],true];
//Set animation preferences for the polygon. We havent' set a dynamic trigger
//for the animation, so the polygon's animation will be triggered by
//DynamicTriggerEvents.onPageLoad (the default).
myPolygon.animationSettings.duration = 2; myPolygon.animationSettings.motionPathPoints = myMotionPathPoints;
タイミング設定
スプレッド、ページおよびページアイテムの timingSettings
オブジェクトは、そのオブジェクトや、そのオ
ブジェクトに含まれているすべてのオブジェクトに適用されるアニメーションのタイミングを制御します。 timingSettings
には、次のプロパティが含まれます。
timingLists
。アニメーションを開始するトリガーイベント(ページの読み込みやページのクリックな
ど)を定義します。
timingGroups
。1 つまたは複数のページアイテムを特定のタイミングに関連付けます。また、アニメー
ションが表示される順番を定義します。 timingGroups
には timingTargets
が含まれています。このプロパティは、特定の timingGroup
に関連付けら
れているオブジェクトを定義します。また、 timingTargets
は、ページアイテムに適用されるアニメーショ
ンの遅延値も指定します。この値は、 timingGroup
のアニメーションの開始に対する相対値で指定するか
( timingGroup
( timingGroup
、 timingGroup
内の前のアイテムの開始からの値で指定します
様々なタイミングオブジェクトを使用して、オブジェクトのアニメーションのタイミングを制御する方法を、
次のスクリプトに示します(完全なスクリプトについては、TimingSettings を参照してください)。 timingGroup
の作成に使用するパラメーターにより、 timingGroup
内の最初の timingTarget
のプロパティが
指定されます。続いて、(存在する場合は) timingTargets
を個別に追加できます。
//Given a document "myDocument" and a page "myPage" and the color "myColorA",
//"myColorB", and "myColorC"...
//Add a page items to animate.
var myPolygonA = myPage.polygons.add({fillColor:myColorA, strokeColor:myDocument.swatches.item("None")}); myPolygonA.paths.item(0).entirePath = [[72, 72], [72, 144], [144, 108]]; var myPolygonB = myPage.polygons.add({fillColor:myColorB, strokeColor:myDocument.swatches.item("None")}); myPolygonB.paths.item(0).entirePath = [[72, 72], [72, 144], [144, 108]]; var myPolygonC = myPage.polygons.add({fillColor:myColorC, strokeColor:myDocument.swatches.item("None")}); myPolygonC.paths.item(0).entirePath = [[72, 72], [72, 144], [144, 108]];
//Create a motion path.
var myMotionPathPoints = [[[[108,108],[108,108],[108,108]],[[516, 108],[516, 108],[516,
108]]],true];
//Set animation preferences for the polygons.
第 11 章 ダイナミックドキュメントの作成 アニメーションの操作 166 myPolygonA.animationSettings.duration = 2; myPolygonA.animationSettings.motionPathPoints = myMotionPathPoints; myPolygonB.animationSettings.duration = 2; myPolygonB.animationSettings.motionPathPoints = myMotionPathPoints; myPolygonC.animationSettings.duration = 2; myPolygonC.animationSettings.motionPathPoints = myMotionPathPoints; var myTimingSettings = myPage.parent.timingSettings;
//Remove the default timing list.
myTimingSettings.timingLists.item(0).remove();
//Add a new timing list that triggers when the page is clicked.
var myTimingList = myTimingSettings.timingLists.add(DynamicTriggerEvents.onPageClick);
//Add the polygons to a single timing group.
var myTimingGroup = myTimingList.timingGroups.add(myPolygonA, 0); myTimingGroup.timingTargets.add(myPolygonB, 2); myTimingGroup.timingTargets.add(myPolygonC, 2);
(ページアイテムの animationSettings
オブジェクトの) hasCustomSettings
プロパティが false のページアイ
テムを timingTarget
に追加しようとすると、エラーが発生することに注意してください。
ページ上のオブジェクトに適用されるアニメーションの順番を制御する方法を、次のスクリプトに示します timingList
に timingGroups
が
追加された順番により、 timingList
で指定されたトリガーイベントが発生したときのアニメーションの再生
順が決まります。 一部のトリガーイベント(
DynamicTriggerEvents.onPageLoad
など)は、 timingList
のア
ニメーションを(順番に)呼び出しますが、それ以外のトリガーイベント
(
DynamicTriggerEvents.onPageClick
など)は、イベントの各インスタンスで 1 つずつ(順番に)アニメー
ションを呼び出します。 例えば、
DynamicTriggerEvents.onPageClick
のトリガーイベントが設定された timingList
に 5 つの
timingGroups
が含まれ、それぞれに 1 つの timingTarget
が含まれている場合、すべて
のアニメーションを処理するにはマウスを 5 回クリックする必要があります。
//Given a document "myDocument" and a page "myPage" and the color "myColorA",
//"myColorB", and "myColorC"...
//Add a page items to animate.
var myPolygonA = myPage.polygons.add({fillColor:myColorA, strokeColor:myDocument.swatches.item("None")}); myPolygonA.paths.item(0).entirePath = [[72, 72], [72, 144], [144, 108]]; var myPolygonB = myPage.polygons.add({fillColor:myColorB, strokeColor:myDocument.swatches.item("None")}); myPolygonB.paths.item(0).entirePath = [[72, 72], [72, 144], [144, 108]]; var myPolygonC = myPage.polygons.add({fillColor:myColorC, strokeColor:myDocument.swatches.item("None")}); myPolygonC.paths.item(0).entirePath = [[72, 72], [72, 144], [144, 108]]; var myPolygonD = myPage.polygons.add({fillColor:myColorA, strokeColor:myDocument.swatches.item("None")}); myPolygonD.paths.item(0).entirePath = [[72, 144], [72, 216], [144, 180]]; var myPolygonE = myPage.polygons.add({fillColor:myColorB, strokeColor:myDocument.swatches.item("None")}); myPolygonE.paths.item(0).entirePath = [[72, 144], [72, 216], [144, 180]] var myPolygonF = myPage.polygons.add({fillColor:myColorC, strokeColor:myDocument.swatches.item("None")}); myPolygonF.paths.item(0).entirePath = [[72, 144], [72, 216], [144, 180]];
//Create a motion path.
var myMotionPathPointsA = [[[[108,108],[108,108],[108,108]],[[516, 108],[516, 108],[516,
108]]],true]; var myMotionPathPointsB = [[[[108,180],[108,180],[108,180]],[[516, 180],[516, 180],[516,
180]]],true];
//Set animation preferences for the polygons.
//DynamicTriggerEvents.onPageLoad (the default).
myPolygonA.animationSettings.duration = 2; myPolygonA.animationSettings.motionPathPoints = myMotionPathPointsA; myPolygonB.animationSettings.duration = 2; myPolygonB.animationSettings.motionPathPoints = myMotionPathPointsA; myPolygonC.animationSettings.duration = 2; myPolygonC.animationSettings.motionPathPoints = myMotionPathPointsA; myPolygonD.animationSettings.duration = 2; myPolygonD.animationSettings.motionPathPoints = myMotionPathPointsB;
第 11 章 ダイナミックドキュメントの作成 アニメーションの操作 167 myPolygonE.animationSettings.duration = 2; myPolygonE.animationSettings.motionPathPoints = myMotionPathPointsB; myPolygonF.animationSettings.duration = 2; myPolygonF.animationSettings.motionPathPoints = myMotionPathPointsB; var myTimingSettings = myPage.parent.timingSettings;
//Remove the default timing list.
myTimingSettings.timingLists.item(0).remove();
//Add a new timing list that triggers when the page is clicked.
var myTimingList = myTimingSettings.timingLists.add(DynamicTriggerEvents.onPageClick);
//Add the polygons to a single timing group.
var myTimingGroupA = myTimingList.timingGroups.add(myPolygonA, 0); myTimingGroupA.timingTargets.add(myPolygonB, 2); myTimingGroupA.timingTargets.add(myPolygonC, 2);
//myTimingGroupB will play on the second page click.
var myTimingGroupB = myTimingList.timingGroups.add(myPolygonD, 0); myTimingGroupB.timingTargets.add(myPolygonE, 2); myTimingGroupB.timingTargets.add(myPolygonF, 2);
任意の timingSettings
オブジェクトに複数の timingList
オブジェクトを含めて、それぞれのオブジェクト
で別々のトリガーイベントに応答することができます。 次のスクリプトでは、
DynamicTriggerEvents.onPageLoad
および
DynamicTriggerEvents.onPageClick
によって呼び出された一連の
アニメーションを表示します(完全なスクリプトについては、MultipleTimingLists を参照してください)。
//Given a document "myDocument" and a page "myPage" containg 6 polygons:
//"myPolygonA", "myPolygonB", "myPolygonC", "myPolygonD", "myPolygonE", "myPolygonF".
//Add a page items to animate.
var myTimingSettings = myPage.parent.timingSettings;
//At this point, all of the polygons have already been added as timing targets
//of the default timing list. Change the delay of myPolygonB and myPolygonC.
var myTimingListA = myTimingSettings.timingLists.item(0); var myTimingGroup = myTimingListA.timingGroups.item(1); myTimingGroup.timingTargets.item(0).delaySeconds = 2; myTimingGroup = myTimingListA.timingGroups.item(2); myTimingGroup.timingTargets.item(0).delaySeconds = 2;
//Remove the last three timing groups in the timing list.
myTimingListA.timingGroups.item(-1).remove(); myTimingListA.timingGroups.item(-1).remove(); myTimingListA.timingGroups.item(-1).remove();
//Add a new timing list that triggers when the page is clicked.
var myTimingListB = myTimingSettings.timingLists.add(DynamicTriggerEvents.onPageClick); var myTimingGroupB = myTimingListB.timingGroups.add(myPolygonD, 0); myTimingGroupB.timingTargets.add(myPolygonE, 2); myTimingGroupB.timingTargets.add(myPolygonF, 2);
前述の例では、アニメーション化したいページアイテムが含まれているスプレッドの timingSettings
を操作
しました。 ユーザーがクリックしたときにページアイテムをアニメーション化したい場合は、ページアイテ
ム自体の timingSettings
を使用する必要があります。次のスクリプトにその例を示します(完全なスクリプ
トについては、PageItemTimingSettings を参照してください)。
//Given a document "myDocument" and a page "myPage" containg a polygon "myPolygonA"...
//Remove the default timing list in the timing settings for the spread.
//Set animation preferences for the polygon. myPolygonA.animationSettings.duration = 2; myPolygonA.animationSettings.motionPathPoints = myMotionPathPointsA; myPage.parent.timingSettings.timingLists.item(0).remove(); var myTimingSettings = myPolygonA.timingSettings; var myTimingList = myTimingSettings.timingLists.add(DynamicTriggerEvents.onClick); var myTimingGroup = myTimingList.timingGroups.add(myPolygonA, 0);
第 11 章 ダイナミックドキュメントの作成 アニメーションの操作 168
変形のアニメーション化
ページアイテムのアニメーションを再生するときに、ページアイテムのサイズ、回転または角度の歪み、不
透明度および表示/非表示を変更できます。 ページアイテムの animationSettings
にはプロパティ
( rotationArray
、 hiddenAfter
など)が含まれていて、このプロパティでアニメーション中に適用される変
形を定義できます。 モーションパスに従ってページアイテムを回転する方法を、次のスクリプトに示します
(完全なスクリプトについては、AnimateRotation を参照してください)。
//Given a document "myDocument" and a page "myPage" and the color "myColorA"...
//Add a page items to animate.
var myPolygonA = myPage.polygons.add({fillColor:myColorA, strokeColor:myDocument.swatches.item("None")}); myPolygonA.paths.item(0).entirePath = [[72, 72], [72, 144], [144, 108]];
//Create a motion path.
var myMotionPathPoints = [[[[108,108],[108,108],[108,108]],[[516, 108],[516, 108],[516,
108]]],true];
//Set animation preferences for the polygon.
myPolygonA.animationSettings.duration = 2; myPolygonA.animationSettings.motionPathPoints = myMotionPathPoints;
//Assuming 24 Frames Per Second (FPS)
//23 = 1 second, 47 = 2 seconds, 71 = 3 seconds, 95 = 4 seconds, 119 = 5 seconds, 143 = 6 seconds
//Since the duration of our animation is 2 seconds, the following line will
//make the polygon rotate 360 degrees from the start to the end
//of the animation.
myPolygonA.animationSettings.rotationArray = [[0, 0], [47, 360]]; var myTimingSettings = myPage.parent.timingSettings;
//Remove the default timing list.
myTimingSettings.timingLists.item(0).remove();
//Add a new timing list that triggers when the page is clicked.
var myTimingList = myTimingSettings.timingLists.add(DynamicTriggerEvents.onPageClick);
//Add the polygons to a single timing group.
var myTimingGroup = myTimingList.timingGroups.add(myPolygonA, 0);
スクリプトを使用すると、InDesign のユーザーインターフェイスを使用した場合よりも、アニメーションを
細かく制御できます。 例えば、スクリプトを使用したアニメーションの場合、任意のモーションパスの各
キーフレームで変形を適用できます。 詳しくは、この章で後述する 「キーフレーム」
を参照してください。
モーションプリセット
前述の例では、InDesign のユーザーインターフェイスで基本レベルからアニメーションを作成するように、
モーションパスを構成してアニメーション設定を行いました。 しかし、InDesign では、モーションプリセッ
トを使用して、レイアウト内のページアイテムのアニメーションを定義することもできます。 モーションプ
リセットは、一度に複数のアニメーションのプロパティに適用できます。次のスクリプトにその例を示しま
す(完全なスクリプトについては、MotionPreset を参照してください)。 InDesign には、多くのモーションプ
リセットが付属しています。また、ユーザーインターフェイスまたはスクリプトを使用して、新しいプリ
セットを追加することもできます。
//Given a page containing the ovals "myOvalA"... var myMotionPreset = app.motionPresets.item("move-right-grow"); myOvalA.animationSettings.duration = 2; myOvalA.animationSettings.playsLoop = true; myOvalA.animationSettings.preset = myMotionPreset;
第 11 章 ダイナミックドキュメントの作成 アニメーションの操作 169
デザインオプション
デザインオプションは、オブジェクトのアニメーション設定で指定したモーションに関連して、アニメー
ションオブジェクトの表示仕様に影響を与えます。 次のスクリプトでは、アニメーションシェイプのデザイ
ンオプションが、アニメーションの再生にどのような影響を与えるかを示します(完全なスクリプトについ
ては、DesignOptions を参照してください)。
//Given a page containing the ovals "myOvalA" and "myOvalB"... var myMotionPreset = app.motionPresets.item("move-right-grow"); myOvalA.animationSettings.duration = 2; myOvalA.animationSettings.playsLoop = true; myOvalA.animationSettings.preset = myMotionPreset; myOvalA.animationSettings.designOption = DesignOptions.fromCurrentAppearance; myOvalB.animationSettings.duration = 2; myOvalB.animationSettings.playsLoop = true; myOvalB.animationSettings.preset = myMotionPreset; myOvalB.animationSettings.designOption = DesignOptions.toCurrentAppearance;
キーフレーム
キーフレームは、アニメーションのタイムライン内における時点です。 InDesign のスクリプティングでは、
キーフレームをアニメーションの任意の時点に追加することで、オブジェクトがアニメーションするときに
変更を適用できます。 キーフレームは、アニメーションするページアイテムに適用されるモーションパスの
一部で、アニメーションの長さと速度を基準にして指定します。 例えば、長さ 2 秒のアニメーションの場合、
1 秒間に 24 フレームで再生すると、アニメーションの最後のフレームはフレーム 48 です。
モーションパスにキーフレームを追加する方法と、アニメーション化するページアイテムに適用される変形
を各キーフレームで変更する方法を、次のスクリプトに示します (完全なスクリプトについては、
//Given a page containing ovals "myOvalA," "myOvalB," and "myOvalC"...
//The motion path is constructed relative to the center of the object, and key frames
//are based on the duration of the animation divided by the number of frames per second
//(usually 24). The following array sets key frames at the start, midpoint, and end
//of a path.
var myMotionPath = [[0,[[0,0], [0,0], [0,0]]], [23,[[234,0], [234,0], [234,0]]], [47,[[468,0],
[468,0], [468,0]]]]; myOvalA.animationSettings.duration = 2; myOvalA.animationSettings.motionPath = myMotionPath;
//The transformation changes at each key frame.
//scaleXArray in the form [[keyframe, scale], [keyframe, scale], ...] myOvalA.animationSettings.scaleXArray = [[0, 100], [23,200], [47, 100]];
//scaleYArray in the form [[keyframe, scale], [keyframe, scale], ...] myOvalA.animationSettings.scaleYArray = [[0, 100], [23,200], [47, 100]];
//opacityArray in the form [[keyframe, opacity], [keyframe, opacity],...]; myOvalA.animationSettings.opacityArray = [[0, 100], [23, 20], [47, 100]]; myOvalA.animationSettings.playsLoop = true; myOvalB.animationSettings.duration = 2; myOvalB.animationSettings.motionPath = myMotionPath; myOvalB.animationSettings.scaleXArray = [[0, 200], [23,300], [47, 50]]; myOvalB.animationSettings.scaleYArray = [[0, 200], [23,300], [47, 50]]; myOvalB.animationSettings.opacityArray = [[0, 10], [23, 80], [47, 60]]; myOvalB.animationSettings.playsLoop = true; myOvalC.animationSettings.duration = 2; myOvalC.animationSettings.motionPath = myMotionPath; myOvalC.animationSettings.scaleXArray = [[0, 50], [23,200], [47, 400]]; myOvalC.animationSettings.scaleYArray = [[0, 50], [23,200], [47, 400]]; myOvalC.animationSettings.opacityArray = [[0, 100], [23, 40], [47, 80]]; myOvalC.animationSettings.playsLoop = true;
第 11 章 ダイナミックドキュメントの作成 ページ効果の追加 170
ページ効果の追加
ページ効果は、書き出し後のダイナミックドキュメントのページを変更した場合に現れる特殊効果です。
ページ効果の追加は、スクリプトを使用して簡単に行えます。次のスクリプトにその例を示します(完全な
スクリプトについては、PageTransitions を参照してください)。
//Given a document "myDocument" containing at least two spreads...
for(var myCounter = 0; myCounter < myDocument.spreads.length; myCounter++){ myDocument.spreads.item(myCounter).pageTransitionType =
PageTransitionTypeOptions.pageTurnTransition;
//This page transition option does not support the pageTransitionDirection
//or pageTransitionDuration properties. If you chose
//PageTransitionTypeOptions.wipeTransition (for example), you would be
//able to set those options, as shown in the next two lines:
//myDocument.spreads.item(myCounter).pageTransitionDirection =
PageTransitionDirectionOptions.leftToRight;
//myDocument.spreads.item(myCounter).pageTransitionDuration =
PageTransitionDurationOptions.medium;
}
//Export the document to SWF, and you'll see the page transitions.
12
XML
CS6
章の更新ステータス
変更なし
XML(Extensible Markup Language)は、World Wide Web Consortium( www.w3.org
)で作成と管理が行われて
いる、テキストベースのマークアップシステムです。 XML では、HTML(Hypertext Markup Language)と同じ
ように、不等号記号で囲まれたマークアップタグ(
<article>
や
<para>
など)が使用されます。
使用できるタグが事前に定義されていますが、XML では独自のタグを作成して、ドキュメントの構造をより
詳細に記述することができます。
高い柔軟性を備えている XML は、データの保存形式として広く利用されています。 InDesign には、XML デー
タをページレイアウトに読み込むための様々な機能が用意されていますが、それらはスクリプトを使用して
制御できます。
ここでは、読者が『Adobe InDesign スクリプティングチュートリアル』を既に読んでおり、スクリプトを作
成して実行する方法を理解しているものとして説明を行います。 また、XML、DTD、XSLT に関する基礎知識を
持っていることを前提としています。
概要
XML はフォーマットを行うためのものではなく、ドキュメントの構造を記述するためのものです。したがっ
て、ページレイアウト作業で XML を活用するには、やや複雑な手順が必要になります。 InDesign は、XML に
完全かつ柔軟に対応できますが、次のような制約があります。
InDesign ドキュメントに読み込んだ XML 要素は、XML 構造に対応する InDesign 要素に変換されます。
InDesign によって表現された XML 要素は、元の XML 要素とは異なります。
い場合は、XML 要素そのものを複製する必要があります。
XML 要素のレイアウト上での出現順序は、XML 構造での出現順序とほぼ同じになります。
XML 要素に関連付けられているストーリー内のテキストは、その要素のデータになります。
InDesign での XML スクリプティングの推奨事項
XML ファイルの処理は、InDesign の外部で(InDesign のレイアウトに XML ファイルを読み込む前に)そのほ
とんどを行うのが一般的です。 InDesign の外部では、XML エディターや XML パーサーなどの様々な便利な
ツールが利用できます。
大規模な XML データ構造に含まれている要素を再配置したり複製したりする場合は、XSLT を使用して XML
を変換することを推奨します。 これは、XML ファイルを読み込むときに実行できます。
InDesign ドキュメントで既にフォーマットされている XML データを操作する場合は、XML ルールを使用する
と便利です。 XML ルールを使用すると、効率よくドキュメント内の XML 構造を検索して、目的の XML 要素を
処理できます。
171
第 12 章 XML
XML 要素のスクリプティング 172
XML 要素のスクリプティング
ここでは、XML 環境設定や XML 読み込み環境設定の指定、XML の読み込み、XML 要素の作成、XML 属性の追
加を行う方法について説明します。 ここでは、XML コンテンツ自体を操作するスクリプトについて説明しま
す。XML 要素にフォーマットを適用するスクリプトについては、
XML 環境設定の指定
XML ビュー環境設定オブジェクトを使用して、InDesign の構造パネルの外観を制御できます。次のスクリプ
トにその例を示します(チュートリアルスクリプトの XMLViewPreferences より)。 var myDocument = app.documents.add(); var myXMLViewPreferences = myDocument.xmlViewPreferences; myXMLViewPreferences.showAttributes = true; myXMLViewPreferences.showStructure = true; myXMLViewPreferences.showTaggedFrames = true; myXMLViewPreferences.showTagMarkers = true; myXMLViewPreferences.showTextSnippets = true;
また、XML 環境設定オブジェクトを使用して、XML タグ付きプリセット環境設定(表やストーリーのデフォ
ルトのタグ名やユーザーインターフェイスカラー)を指定することもできます。次のスクリプトにその例を
示します(チュートリアルスクリプトの XMLPreferences より)。 var myDocument = app.documents.add(); var myXMLPreferences = myDocument.xmlPreferences; myXMLPreferences.defaultCellTagColor = UIColors.blue; myXMLPreferences.defaultCellTagName = "cell"; myXMLPreferences.defaultImageTagColor = UIColors.brickRed; myXMLPreferences.defaultImageTagName = "image"; myXMLPreferences.defaultStoryTagColor = UIColors.charcoal; myXMLPreferences.defaultStoryTagName = "text"; myXMLPreferences.defaultTableTagColor = UIColors.cuteTeal; myXMLPreferences.defaultTableTagName = "table";
XML 読み込み環境設定の指定
XML ファイルを読み込む前に、XML 読み込み環境設定を指定することができます。この環境設定を使用すれ
ば、XSLT 変換を適用したり、XML ファイル内の空白文字の処理方法を制御したり、繰り返すテキスト要素を
作成したりすることができます。 XML 読み込み環境設定オブジェクトの設定方法を、次のスクリプトに示し
ます(チュートリアルスクリプトの XMLImportPreferences より)。
第 12 章 XML
XML 要素のスクリプティング 173 var myDocument = app.documents.add(); var myXMLImportPreferences = myDocument.xmlImportPreferences; myXMLImportPreferences.allowTransform = false; myXMLImportPreferences.createLinkToXML = false; myXMLImportPreferences.ignoreUnmatchedIncoming = true; myXMLImportPreferences.ignoreWhitespace = true; myXMLImportPreferences.importCALSTables = true; myXMLImportPreferences.importStyle = XMLImportStyles.mergeImport; myXMLImportPreferences.importTextIntoTables = false; myXMLImportPreferences.importToSelected = false; myXMLImportPreferences.removeUnmatchedExisting = false; myXMLImportPreferences.repeatTextElements = true;
//The following properties are only used when the
//AllowTransform property is set to True.
//myXMLImportPreferences.transformFilename = "c:¥myTransform.xsl"
//If you have defined parameters in your XSL file, then you can pass
//parameters to the file during the XML import process. For each parameter,
//enter an array containing two strings. The first string is the name of the
//parameter, the second is the value of the parameter.
//myXMLImportPreferences.transformParameters = [["format", "1"]];
XML の読み込み
XML 読み込み環境設定を指定したら、XML ファイルを読み込みます。次のスクリプトにその例を示します
(チュートリアルスクリプトの ImportXML より)。 myDocument.importXML(File("/c/xml_test.xml"));
XML ファイルの内容を特定の XML 要素に読み込む必要がある場合は、ドキュメントではなく XML 要素の importXML
次のスクリプトにその例を示します(チュートリアルスクリプトの myXMLElement.importXML(File("/c/xml_test.xml"));
または、 xmlImportPreferences
オブジェクトの importToSelected
プロパティを true に設定し、XML 要素を
選択した状態で XML ファイルを読み込む方法もあります。次のスクリプトにその例を示します(チュートリ
アルスクリプトの ImportXMLIntoSelectedElement より)。 var myXMLTag = myDocument.xmlTags.add("xml_element"); var myXMLElement = myDocument.xmlElements.item(0).xmlElements.add(myXMLTag); myDocument.select(myXMLElement); myDocument.xmlImportPreferences.importToSelected = true;
//Import into the selected XML element.
myDocument.importXML(File("/c/xml_test.xml"));
XML タグの作成
の要素名が、ドキュメントの XML タグのリストに追加されます。 また、XML タグを直接作成することもでき
ます。次のスクリプトにその例を示します(チュートリアルスクリプトの MakeXMLTags より)。
//You can create an XML tag without specifying a color for the tag.
var myXMLTagA = myDocument.xmlTags.add("XML_tag_A");
//You can define the highlight color of the XML tag using the UIColors enumeration...
var myXMLTagB = myDocument.xmlTags.add("XML_tag_B", UIColors.gray);
//...or you can provide an RGB array to set the color of the tag.
var myXMLTagC = myDocument.xmlTags.add("XML_tag_C", [0, 92, 128]);
第 12 章 XML
XML タグのロード
XML 要素のスクリプティング 174
XML データを読み込む前にタグとスタイルのマッピングを行いたい場合に便利です。次のスクリプトにその
例を示します(チュートリアルスクリプトの LoadXMLTags より)。 myDocument.loadXMLTags(File("/c/test.xml"));
XML タグの保存
ファイルから XML タグをロードするのとは逆に、XML タグをファイルに保存することもできます。 これを行
うと、タグだけが XML ファイルに保存されます。ドキュメントデータは保存されません。 この処理は、XML
を書き出すより高速で、生成されるファイルも小さくなります。 XML タグを保存する方法を、次のサンプル
スクリプトに示します(完全なスクリプトについては、SaveXMLTags を参照してください)。 myDocument.saveXMLTags(File("/c/xml_tags.xml"), "Tag set created October 5, 2006");
XML 要素の作成
通常、XML 要素は XML ファイルを読み込んで作成しますが、InDesign スクリプティングを使用して XML 要素
を作成することもできます。次のスクリプトにその例を示します(チュートリアルスクリプトの var myDocument = myInDesign.documents.add(); var myXMLTagA = myDocument.xmlTags.add("XML_tag_A"); var myXMLElementA = myDocument.xmlElements.item(0).xmlElements.add(myXMLTagA); myXMLElementA.contents = "This is an XML element containing text.";
XML 要素の移動
move
メソッドを使用して、XML 構造内の XML 要素を移動できます。次のスクリプトにその例を示します
(チュートリアルスクリプトの MoveXMLElement より)。 var myRootXMLElement = myDocument.xmlElements.item(0); var myXMLElementA = myRootXMLElement.xmlElements.item(0); myXMLElementA.move(LocationOptions.after, myRootXMLElement.xmlElements.item(2)); myRootXMLElement.xmlElements.item(-1).move(LocationOptions.atBeginning);
XML 要素の削除
XML 要素を削除すると、レイアウトと XML 構造の両方から XML 要素が削除されます。次のスクリプトにその
例を示します(チュートリアルスクリプトの DeleteXMLElement より)。 myRootXMLElement.xmlElements.item(0).remove();
XML 要素の複製
XML 要素を複製すると、新しい XML 要素が、XML 構造内の元の XML 要素の直後に追加されます。次のスク
リプトにその例を示します(チュートリアルスクリプトの DuplicateXMLElement より)。 var myDocument = app.documents.item(0); var myRootXMLElement = myDocument.xmlElements.item(0);
//Duplicate the XML element containing "A" var myNewXMLElement = myRootXMLElement.xmlElements.item(0).duplicate();
//Change the content of the duplicated XML element.
myNewXMLElement.contents = myNewXMLElement.contents + " duplicate";
第 12 章 XML
XML 要素のスクリプティング 175
XML 構造からのアイテムの削除
XML 要素とページアイテムやテキストとの関連付けを削除するには、 untag
メソッドを使用します。次のス
クリプトにその例を示します。 このメソッドを使用すると、XML 要素との関連付けは削除されますが、オブ
ジェクトそのものは削除されません。 XML 要素が削除されたコンテンツは、親の XML 要素に関連付けられま
ストまたはページアイテム)は、ドキュメントに保持されます (完全なスクリプトについては、 var myXMLElement = myDocument.xmlElements.item(0).xmlElements.item(0); myXMLElement.untag();
XML コメントの作成
のスクリプトに示します(チュートリアルスクリプトの MakeXMLComment より)。 var myRootXMLElement = myDocument.xmlElements.item(0); var myXMLElementB = myRootXMLElement.xmlElements.item(1); myXMLElementB.xmlComments.add("This is an XML comment.");
XML 処理命令の作成
処理命令(PI:Processing Instruction)とは、XML ドキュメントを読み込むアプリケーションに対する命令が
含まれている XML 要素のことです。 XML 処理命令は、InDesign では無視されますが、他のアプリケーション
で使用するために InDesign の XML 構造に挿入することができます。 XML ドキュメントには複数の処理命令を
含めることができます。
<?xml-stylesheet type="text/css" href="generic.css"?>
XML 処理命令を追加する方法を、次のスクリプトに示します(完全なスクリプトについては、 var myRootXMLElement = myDocument.xmlElements.item(0); var myXMLProcessingInstruction = myRootXMLElement.xmlInstructions.add("xml-stylesheet type=¥"text/css¥" ", "href=¥"generic.css¥"");
XML 属性の操作
方法を、次のスクリプトに示します(チュートリアルスクリプトの MakeXMLAttribute より)。 XML 要素には任
意の数の XML 属性を追加できますが、各属性の名前はその要素内で固有のものであることが必要です(例え
ば、「id」という名前の属性を 2 つ使用することはできません)。 var myDocument = app.documents.item(0); var myRootXMLElement = myDocument.xmlElements.item(0); var myXMLElementB = myRootXMLElement.xmlElements.item(1); myXMLElementB.xmlAttributes.add("example_attribute", "This is an XML attribute. It will not appear in the layout!");
スクリプトを使用して属性を直接作成する以外に、XML 要素を変換して属性を作成することもできます。 こ
れを行うと、XML 要素のテキスト内容が XML 属性の値として使用され、XML 要素の親に追加されます。 XML
要素の名前が属性の名前になるので、同じ名前を持つ属性が XML 要素の親に既に存在している場合は、作成
に失敗します。 XML 要素にページアイテムが含まれている場合、それらのページアイテムはレイアウトから
削除されます。
第 12 章 XML
XML 要素のスクリプティング 176
は、XML 属性の親の先頭または末尾に追加できます。 デフォルトでは、親要素の先頭に追加されます。
新しい XML 要素に XML マークアップタグを指定することもできます。 このパラメーターを省略すると、その
XML 属性が含まれている XML 要素と同じ XML タグを使用して新しい XML 要素が作成されます。
XML 要素を XML 属性に変換する方法を、次のスクリプトに示します(完全なスクリプトについては、 var myRootXMLElement = myDocument.xmlElements.item(0); myRootXMLElement.xmlElements.item(-1).convertToAttribute();
XML 属性を XML 要素に変換することもできます。次のスクリプトにその例を示します(チュートリアルスク
リプトの ConvertAttributeToElement より)。 var myRootXMLElement = myDocument.xmlElements.item(0); var myXMLElementB = myRootXMLElement.xmlElements.item(1);
//The "at" parameter can be either LocationOptions.atEnd or LocationOptions.atBeginning, but cannot
//be LocationOptions.after or LocationOptions.before.
myXMLElementB.xmlAttributes.item(0).convertToElement(LocationOptions.atEnd, myDocument.xmlTags.item("xml_element"));
XML ストーリーの操作
レイアウト要素(ストーリーまたはページアイテム)に関連付けられていない XML 要素を読み込むと、その
要素は XML ストーリーに格納されます。 テキストフレーム内のテキストと同じように、配置されていない
については、XMLStory を参照してください)。 var myXMLStory = myDocument.xmlStories.item(0);
//Though the text has not yet been placed in the layout, all text
//properties are available.
myXMLStory.paragraphs.item(0).pointSize = 72;
//Place the XML element in the layout to see the result.
myDocument.xmlElements.item(0).xmlElements.item(0).placeXML(myDocument.pages.item(0).textFrames.
item(0));
XML の書き出し
InDesign ドキュメントから XML を書き出す方法としては、ドキュメント内の XML 構造全体を書き出す方法
と、1 つの XML 要素(とその要素に含まれているすべての子 XML 要素)を書き出す方法があります。 次のス
クリプトにその例を示します(完全なスクリプトについては、ExportXML を参照してください)。
//Export the entire XML structure in the document.
myDocument.exportFile(ExportFormat.xml, File("/c/completeDocumentXML.xml"));
//Export a specific XML element and its child XML elements.
var myXMLElement = myDocument.xmlElements.item(0).xmlElements.item(-1); myXMLElement.exportFile(ExportFormat.xml, File("/c/partialDocumentXML.xml"));
また、 xmlExportPreferences
オブジェクトの exportFromSelected
プロパティを使用して、ユーザーイン
ターフェイスで選択されている XML 要素を書き出すこともできます。 次のスクリプトにその例を示します
(完全なスクリプトについては、ExportSelectedXMLElement を参照してください)。 myDocument.select(myDocument.xmlElements.item(0).xmlElements.item(1)); myDocument.xmlExportPreferences.exportFromSelected = true;
//Export the entire XML structure in the document.
myDocument.exportFile(ExportFormat.xml, File("/c/selectedXMLElement.xml")); myDocument.xmlExportPreferences.exportFromSelected = false;
第 12 章 XML レイアウトへの XML 要素の追加 177
レイアウトへの XML 要素の追加
これまでの節では、XML データを InDesign ドキュメントに読み込んで、ドキュメント内の XML 構造を操作す
る方法について説明しました。 この節では、XML 情報をページレイアウトに読み込んでフォーマットを行う
方法について説明します。
XML 要素とページアイテムやテキストとの関連付け
ページアイテムやテキストに既存の XML 要素を関連付けるには、 placeXML
メソッドを使用します。
ソッドを使用すると、ページアイテムの内容が XML 要素の内容に置き換わります。次のスクリプトにその例
を示します(チュートリアルスクリプトの PlaceXML より)。 myDocument.xmlElements.item(0).placeXML(myDocument.pages.item(0).textFrames.item(0));
既存のページアイテムやテキストオブジェクトに既存の XML 要素を関連付けるには、 markup
メソッドを使用
が結合されます。 markup
メソッドを使用する方法を、次のスクリプトに示します(完全なスクリプトについ
ては、Markup を参照してください)。 myDocument.xmlElements.item(0).xmlElements.item(0).markup(myDocument.pages.item(0).textFrames.it
em(0));
ページアイテムへの XML の配置
XML 要素をページアイテムに関連付ける別の方法として、 placeIntoFrame
メソッドを使用する方法がありま
す(完全なスクリプトについては、PlaceIntoFrame を参照してください)。 myDocument.viewPreferences.horizontalMeasurementUnits = MeasurementUnits.points; myDocument.viewPreferences.verticalMeasurementUnits = MeasurementUnits.points; myDocument.viewPreferences.rulerOrigin = RulerOrigin.pageOrigin;
//PlaceIntoFrame has two parameters:
//On: The page, spread, or master spread on which to create the frame
//GeometricBounds: The bounds of the new frame (in page coordinates).
myDocument.xmlElements.item(0).xmlElements.item(0).placeIntoFrame(myDocument.pages.item(0), [72,
72, 288, 288]);
XML 要素をインラインページアイテム(アンカーオブジェクト)に関連付けるには、 placeIntoCopy
メソッ
ドを使用します。次のスクリプトにその例を示します(チュートリアルスクリプトの PlaceIntoCopy より)。 var myPage = myDocument.pages.item(0); var myXMLElement = myDocument.xmlElements.item(0); myXMLElement.placeIntoCopy(myPage, [288, 72], myPage.textFrames.item(0), true);
既存のページアイテム(または既存のページアイテムのコピー)を XML 要素に関連付けて、XML 構造内のそ
の要素がある場所にページアイテムを挿入するには、 placeIntoInlineCopy
メソッドを使用します。次のス
クリプトにその例を示します(チュートリアルスクリプトの PlaceIntoInlineCopy より)。 var myPage = myDocument.pages.item(0); var myTextFrame = myDocument.textFrames.add({geometricBounds:[72, 72, 96, 144]}); var myXMLElement = myDocument.xmlElements.item(0).xmlElements.item(2); myXMLElement.placeIntoInlineCopy(myTextFrame, false);
XML 要素を新規インラインフレームに関連付けるには、 placeIntoInlineFrame
メソッドを使用します。次の
スクリプトにその例を示します(チュートリアルスクリプトの PlaceIntoInlineFrame より)。 var myXMLElement = myDocument.xmlElements.item(0).xmlElements.item(2);
//Specify width and height as you create the inline frame.
myXMLElement.placeIntoInlineFrame([72, 24]);
第 12 章 XML レイアウトへの XML 要素の追加 178
XML テキスト要素の内部や周囲へのテキストの挿入
前」や「住所」などのラベル)を XML 要素のテキストに追加したいことがあります。 XML 要素の内部や周囲
にテキストを追加する方法を、次のサンプルスクリプトに示します(完全なスクリプトについては、 var myXMLElement = myDocument.xmlElements.item(0).xmlElements.item(0);
//By inserting the return character after the XML element, the character
//becomes part of the content of the parent XML element, not of the element itself.
myXMLElement.insertTextAsContent("¥r", LocationOptions.after); myXMLElement = myDocument.xmlElements.item(0).xmlElements.item(1); myXMLElement.insertTextAsContent("Static text: ", LocationOptions.before); myXMLElement.insertTextAsContent("¥r", LocationOptions.after);
//To add text inside the element, set the location option to beginning or end.
myXMLElement = myDocument.xmlElements.item(0).xmlElements.item(2); myXMLElement.insertTextAsContent("Text at the start of the element: ",
LocationOptions.atBeginning); myXMLElement.insertTextAsContent(" Text at the end of the element.", LocationOptions.atEnd); myXMLElement.insertTextAsContent("¥r", LocationOptions.after);
//Add static text outside the element.
myXMLElement = myDocument.xmlElements.item(0).xmlElements.item(3); myXMLElement.insertTextAsContent("Text before the element: ", LocationOptions.before); myXMLElement.insertTextAsContent(" Text after the element.", LocationOptions.after);
//To insert text inside the text of an element, work with the text objects contained by the element.
myXMLElement.words.item(2).insertionPoints.item(0).contents = "(the third word of) ";
既存レイアウトのマークアップ
XML 以外のファイルに基づいて XML を作成したいことがあります(例えば、既存のページレイアウトを XML
スタイルへのタグのマッピング
XML テキスト要素にフォーマットを適用する最も簡単な方法の 1 つが、
XMLImportMaps
を使用してタグをス
タイルにマッピングする方法です。 この方法では、特定の XML タグを段落スタイルや文字スタイルに関連付
けることができます。 ドキュメントの mapXMLTagsToStyles
メソッドを使用すると、テキストにスタイルが適
用されます。次のスクリプトにその例を示します(チュートリアルスクリプトの MapTagsToStyles より)。 var myDocument = app.documents.item(0);
//Create a tag to style mapping.
myDocument.xmlImportMaps.add(myDocument.xmlTags.item("heading_1"), myDocument.paragraphStyles.item("heading 1")); myDocument.xmlImportMaps.add(myDocument.xmlTags.item("heading_2"), myDocument.paragraphStyles.item("heading 2")); myDocument.xmlImportMaps.add(myDocument.xmlTags.item("para_1"), myDocument.paragraphStyles.item("para 1")); myDocument.xmlImportMaps.add(myDocument.xmlTags.item("body_text"), myDocument.paragraphStyles.item("body text"));
//Map the XML tags to the defined styles.
myDocument.mapXMLTagsToStyles();
//Place the XML element in the layout to see the result.
var myPage = myDocument.pages.item(0); var myTextFrame = myPage.textFrames.add({geometricBounds:myGetBounds(myDocument, myPage)}); var myStory = myTextFrame.parentStory; myStory.placeXML(myDocument.xmlElements.item(0));
第 12 章 XML レイアウトへの XML 要素の追加 179
タグへのスタイルのマッピング
XML 要素が関連付けられていないフォーマットされたテキストを XML 構造に移動したい場合は、スタイルを
タグにマッピングします。これによって、段落スタイルや文字スタイルを XML タグに関連付けることができ
ます。 これを行うには、 xmlExportMap
オブジェクトを使用して、XML タグとスタイルの間にリンクを作成し、 mapStylesToXMLTags
メソッドを使用して該当する XML 要素を作成します。次のスクリプトにその例を示し
ます(チュートリアルスクリプトの MapStylesToTags より)。 var myDocument = app.documents.item(0);
//Create a style to tag mapping.
myDocument.xmlExportMaps.add(myDocument.paragraphStyles.item("heading 1"), myDocument.xmlTags.item("heading_1")); myDocument.xmlExportMaps.add(myDocument.paragraphStyles.item("heading 2"), myDocument.xmlTags.item("heading_2")); myDocument.xmlExportMaps.add(myDocument.paragraphStyles.item("para 1"), myDocument.xmlTags.item("para_1")); myDocument.xmlExportMaps.add(myDocument.paragraphStyles.item("body text"), myDocument.xmlTags.item("body_text"));
//Apply the style to tag mapping.
myDocument.mapStylesToXMLTags();
別の方法としては、単純に、ドキュメント内のすべての段落スタイルや文字スタイルに対して新しい XML タ
グを作成して、スタイルをタグにマッピングする方法があります。次のスクリプトにその例を示します
(チュートリアルスクリプトの MapAllStylesToTags より)。 var myDocument = app.documents.item(0);
//Create tags that match the style names in the document,
//creating an XMLExportMap for each tag/style pair.
for(var myCounter = 0; myCounter<myDocument.paragraphStyles.length; myCounter++){ var myParagraphStyle = myDocument.paragraphStyles.item(myCounter); var myParagraphStyleName = myParagraphStyle.name; var myXMLTagName = myParagraphStyleName.replace(/¥ /gi, "_") myXMLTagName = myXMLTagName.replace(/¥[/gi, "") myXMLTagName = myXMLTagName.replace(/¥]/gi, "") var myXMLTag = myDocument.xmlTags.add(myXMLTagName); myDocument.xmlExportMaps.add(myParagraphStyle, myXMLTag);
}
//Apply the style to tag mapping.
myDocument.mapStylesToXMLTags();
グラフィックのマークアップ
グラフィックに XML 要素を関連付ける方法を、次のスクリプトに示します(完全なスクリプトについては、 var myXMLTag = myDocument.xmlTags.add("graphic"); var myGraphic = myDocument.pages.item(0).place(File(/c/test.tif"));
//Associate the graphic with a new XML element as you create the element.
var myXMLElement = myDocument.xmlElements.Item(0).xmlElements.add(myXMLTag, myGraphic);
XML 要素へのスタイルの適用
タグとスタイルをマッピングしたり、XML 要素が関連付けられているテキストやページアイテムにスタイル
を適用したりする以外に、XML 要素にスタイルを直接適用することもできます。 applyParagraphStyle
、 applyCharacterStyle
、 applyObjectStyle
の 3 つのメソッドを使用する方法を、次のスクリプトに示します
(完全なスクリプトについては、ApplyStylesToXMLElements を参照してください)。
第 12 章 XML レイアウトへの XML 要素の追加 180 var myDocument = app.documents.add(); myDocument.viewPreferences.horizontalMeasurementUnits = MeasurementUnits.points; myDocument.viewPreferences.verticalMeasurementUnits = MeasurementUnits.points;
//Create a series of XML tags.
var myHeading1XMLTag = myDocument.xmlTags.add("heading_1"); var myHeading2XMLTag = myDocument.xmlTags.add("heading_2"); var myPara1XMLTag = myDocument.xmlTags.add("para_1"); var myBodyTextXMLTag = myDocument.xmlTags.add("body_text");
//Create a series of paragraph styles.
var myHeading1Style = myDocument.paragraphStyles.add(); myHeading1Style.name = "heading 1"; myHeading1Style.pointSize = 24; var myHeading2Style = myDocument.paragraphStyles.add(); myHeading2Style.name = "heading 2"; myHeading2Style.pointSize = 14; myHeading2Style.spaceBefore = 12; var myPara1Style = myDocument.paragraphStyles.add(); myPara1Style.name = "para 1"; myPara1Style.pointSize = 12; myPara1Style.firstLineIndent = 0; var myBodyTextStyle = myDocument.paragraphStyles.add(); myBodyTextStyle.name = "body text"; myBodyTextStyle.pointSize = 12; myBodyTextStyle.firstLineIndent = 24;
//Create a character style.
var myCharacterStyle = myDocument.characterStyles.add(); myCharacterStyle.name = "Emphasis"; myCharacterStyle.fontStyle = "Italic";
//Add XML elements and apply paragraph styles.
var myRootXMLElement = myDocument.xmlElements.item(0); var myXMLElementA = myRootXMLElement.xmlElements.add(myHeading1XMLTag); myXMLElementA.contents = "Heading 1"; myXMLElementA.insertTextAsContent("¥r", XMLElementPosition.afterElement); myXMLElementA.applyParagraphStyle(myHeading1Style, true); var myXMLElementB = myRootXMLElement.xmlElements.add(myPara1XMLTag); myXMLElementB.contents = "This is the first paragraph in the article."; myXMLElementB.insertTextAsContent("¥r", XMLElementPosition.afterElement); myXMLElementB.applyParagraphStyle(myPara1Style, true); var myXMLElementC = myRootXMLElement.xmlElements.add(myBodyTextXMLTag); myXMLElementC.contents = "This is the second paragraph in the article."; myXMLElementC.insertTextAsContent("¥r", XMLElementPosition.afterElement); myXMLElementC.applyParagraphStyle(myBodyTextStyle, true); var myXMLElementD = myRootXMLElement.xmlElements.add(myHeading2XMLTag); myXMLElementD.contents = "Heading 2"; myXMLElementD.insertTextAsContent("¥r", XMLElementPosition.afterElement); myXMLElementD.applyParagraphStyle(myHeading2Style, true); var myXMLElementE = myRootXMLElement.xmlElements.add(myPara1XMLTag); myXMLElementE.contents = "This is the first paragraph following the subhead."; myXMLElementE.insertTextAsContent("¥r", XMLElementPosition.afterElement); myXMLElementE.applyParagraphStyle(myPara1Style, true); var myXMLElementF = myRootXMLElement.xmlElements.add(myBodyTextXMLTag); myXMLElementF.contents = "This is the second paragraph following the subhead."; myXMLElementF.insertTextAsContent("¥r", XMLElementPosition.afterElement); myXMLElementF.applyParagraphStyle(myBodyTextStyle, true); var myXMLElementG = myRootXMLElement.xmlElements.add(myBodyTextXMLTag); myXMLElementG.contents = "Note:"; myXMLElementG = myXMLElementG.move(LocationOptions.atBeginning, myXMLElementF) myXMLElementG.insertTextAsContent(" ", XMLElementPosition.afterElement); myXMLElementG.applyCharacterStyle(myCharacterStyle, true);
// Add text elements.
var myPage = myDocument.pages.item(0); var myTextFrame = myPage.textFrames.add({geometricBounds:myGetBounds(myDocument, myPage)}); var myStory = myTextFrame.parentStory; myStory.placeXML(myRootXMLElement);
第 12 章 XML レイアウトへの XML 要素の追加 181
XML 表の操作
HTML 標準の表タグでデータがマークアップされている場合、InDesign はその XML データを自動的に表セル
に読み込みます。 デフォルトの表マークアップを使用できないか、使用を避けたい場合は、 convertElementToTable
メソッドを使用して XML 要素を表に変換できます。
このメソッドを使用するには、表に変換する XML 要素が特定の構造になっている必要があります。 表の各行
が特定の XML 要素に対応しており、その要素の中に、行内の各セルに対応する一連の XML 要素が含まれてい
る必要があります。 このメソッドを使用する方法を、次のスクリプトに示します(完全なスクリプトについ
ては、ConvertXMLElementToTable を参照してください)。 テーブル行を表すために使用されている XML 要素
は、このプロセスによって変換されます。 var myDocument = app.documents.add();
//Create a series of XML tags.
var myRowTag = myDocument.xmlTags.add("row"); var myCellTag = myDocument.xmlTags.add("cell"); var myTableTag = myDocument.xmlTags.add("table");
//Add XML elements.
var myRootXMLElement = myDocument.xmlElements.item(0); with(myRootXMLElement){ var myTableXMLElement = xmlElements.add(myTableTag); with(myTableXMLElement){ for(var myRowCounter = 1;myRowCounter < 7;myRowCounter++){ with(xmlElements.add(myRowTag)){ myString = "Row " + myRowCounter; for(var myCellCounter = 1; myCellCounter < 5; myCellCounter++){ with(xmlElements.add(myCellTag)){ contents = myString + ":Cell " + myCellCounter;
}
}
}
}
}
} var myTable = myTableXMLElement.convertElementToTable(myRowTag, myCellTag);
// Add text elements.
var myPage = myDocument.pages.item(0); var myTextFrame = myPage.textFrames.add({geometricBounds:myGetBounds(myDocument, myPage)}); var myStory = myTextFrame.parentStory; myStory.placeXML(myRootXMLElement);
XML 要素で構成されている表では、XML 要素に関連付けられている表やセルにスタイルを適用するのではな
く、XML 要素に表スタイルやセルスタイルを直接適用することができます。 これを行うには、 applyTableStyle
メソッドや applyCellStyle
メソッドを使用します。次のスクリプトにその例を示します
(チュートリアルスクリプトの ApplyTableStyles より)。 var myDocument = app.documents.add();
//Create a series of XML tags.
var myRowTag = myDocument.xmlTags.add("row"); var myCellTag = myDocument.xmlTags.add("cell"); var myTableTag = myDocument.xmlTags.add("table");
//Create a table style and a cell style.
var myTableStyle = myDocument.tableStyles.add({name:"myTableStyle"}); myTableStyle.startRowFillColor = myDocument.colors.item("Black"); myTableStyle.startRowFillTint = 25; myTableStyle.endRowFillColor = myDocument.colors.item("Black"); myTableStyle.endRowFillTint = 10; var myCellStyle = myDocument.cellStyles.add(); myCellStyle.fillColor = myDocument.colors.item("Black"); myCellStyle.fillTint = 45
//Add XML elements.
var myRootXMLElement = myDocument.xmlElements.item(0); with(myRootXMLElement){ var myTableXMLElement = xmlElements.add(myTableTag);
第 12 章 XML レイアウトへの XML 要素の追加 182 with(myTableXMLElement){ for(var myRowCounter = 1;myRowCounter < 7;myRowCounter++){ with(xmlElements.add(myRowTag)){ myString = "Row " + myRowCounter; for(var myCellCounter = 1; myCellCounter < 5; myCellCounter++){ with(xmlElements.add(myCellTag)){ contents = myString + ":Cell " + myCellCounter;
}
}
}
}
}
} var myTable = myTableXMLElement.convertElementToTable(myRowTag, myCellTag); var myTableXMLElement = myDocument.xmlElements.item(0).xmlElements.item(0); myTableXMLElement.applyTableStyle(myTableStyle); myTableXMLElement.xmlElements.item(0).applyCellStyle(myCellStyle); myTableXMLElement.xmlElements.item(5).applyCellStyle(myCellStyle); myTableXMLElement.xmlElements.item(10).applyCellStyle(myCellStyle); myTableXMLElement.xmlElements.item(15).applyCellStyle(myCellStyle); myTableXMLElement.xmlElements.item(16).applyCellStyle(myCellStyle); myTableXMLElement.xmlElements.item(21).applyCellStyle(myCellStyle);
// Add text elements.
var myPage = myDocument.pages.item(0); var myTextFrame = myPage.textFrames.add({geometricBounds:myGetBounds(myDocument, myPage)}); var myStory = myTextFrame.parentStory; myStory.placeXML(myRootXMLElement); myTable.alternatingFills = AlternatingFillsTypes.alternatingRows;
13
XML ルール
CS6
概要
章の更新ステータス
変更なし
InDesign の XML ルール機能は、ドキュメントに含まれている XML コンテンツをスクリプトで処理するための
強力なツールです。 XML ルールを使用すれば、XML 要素を処理するスクリプトを簡単に記述できるようにな
るとともに、XML 要素の検索、変更、フォーマットを効率よく行えるようになります。
XML ルールは、オープン、配置、クローズなどのアプリケーションイベントによって実行することができま
す。一般的には、ドキュメントに XML を読み込んだ後に実行します (イベントへのスクリプトの割り当てに
を参照してください)。
この章では、XML ルールの構造と処理について簡単に説明した後で、次の方法について説明します。
XML ルールの定義
XML ルールの適用
XML ルールを使用した XML 要素の検索
XML ルールを使用した XML データのフォーマット
XML ルールに基づいたページアイテムの作成
XML ルールを使用したデータの再構築
XML ルールプロセッサーの使用
ここでは、読者が『Adobe InDesign スクリプティングチュートリアル』を既に読んでおり、スクリプトを作
成して実行する方法を理解しているものとして説明を行います。 また、XML に関する基礎知識を持っており、
第 12 章「XML」 を読み終えていることを前提としています。
InDesign の XML ルール機能は、次の 3 つの部分から構成されています。
XML ルールプロセッサー(単一のスクリプトオブジェクト)ー XPath を使用して、XML 構造の中から
数の XML ルールプロセッサーオブジェクトを含めることができます。それぞれの XML ルールプロセッ
サーオブジェクトには、それぞれ 1 つの XML ルールセットが関連付けられます。
グルーコード ー XML ルールを記述するときや、XML ルールプロセッサーとやり取りを行うときに便利な
一連の関数(Adobe 提供)。
つのルールは、XPath ベースの 1 つの条件と、その条件が満たされたときに適用する 1 つの関数に結び付
いています。 「apply」関数では、InDesign スクリプティングで定義可能な処理であれば、どのような処
理でも実行できます。例えば、XML 構造の変更、フォーマットの適用、ページ、ページアイテム、ド
キュメントの新規作成などが行えます。
1 つのスクリプトでは、いくつでもルールを定義できます。ルールは、InDesign ドキュメントの XML 構造全
体に適用することもできますし、XML 構造の中の一部の要素に適用することもできます。 XML ルールプロ
183
第 13 章 XML ルール 概要 184
セッサーによって XML ルールが実行されると、ドキュメント内の一致する XML 要素やその他のオブジェクト
に変更が加えられます。
素を検索し、何らかの変換を行いますが、XML ルールでは、XPath を使用して InDesign の内部で XML 要素を
検索し、何らかのアクションを行います。 XSLT のテンプレートでは、InDesign の外部にある XML パーサーを
使用して XML データに変換を適用しますが、InDesign のルールプロセッサーでは、XML ルールを使用して
InDesign の内部で XML データに変換を適用します。
XML ルールを使用する利点
以前のリリースの InDesign では、XPath を使用して InDesign ファイルの XML 構造をナビゲートすることはで
きませんでした。 XML 構造を処理するには、再帰スクリプト関数を作成して、各要素を繰り返し調べていく
必要がありました。 この処理は難しく、時間がかかりました。
XML ルールを使用すれば、構造内の XML 要素を簡単に検索できます。XML 要素の検索には、XPath と
素の繰り返し作業をスクリプトよりも高速に処理できます。
XML ルールのプログラミングモデル
XML ルールは、次の 3 つの要素で構成されます。
1.
名前(文字列)
2.
XPath
文(文字列)
3.
apply
関数
XPath 文では、XML 構造内の場所を定義します。XML ルールプロセッサーによって、これに一致する要素が
検索され、ルールで定義されている apply 関数が実行されます。
XML ルールのサンプルを次に示します。 function RuleName() { this.name = "RuleNameAsString"; this.xpath = "ValidXPathSpecifier"; this.apply = function (element, ruleSet, ruleProcessor){
//Do something here.
//Return true to stop further processing of the XML element return true;
}; // end of Apply function
}
この例では、ルールの名前は
RuleNameAsString
であり、
RuleName
に関連付けられます。XPath 式は
ValidXPathSpecifier
実際に使用できる様々な XML ルールの例については、この章の後の節を参照し
てください。
を参照してください。
第 13 章 XML ルール
XML ルールセット
概要 185
ルールは、配列に格納されている順番に適用されます。 XML ルールセットのサンプルを次に示します。 var myRuleSet = new Array (new SortByName, new AddStaticText, new LayoutElements, new FormatElements
);
この例では、 myRuleSet
という配列に列挙されているルールが、スクリプトの別の場所に定義されています。
XML ルールセットを利用した、実際に使用できる様々なスクリプトについては、この章の後述を参照してく
ださい。
「グルー」コード
InDesign のスクリプトモデルに組み込まれている XML ルールプロセッサーオブジェクトに加えて、XML ルー
ルの作成に役立つ一連の関数が用意されています。 glue code.jsx
というファイルに、次の関数が定義されて
います。
__processRuleSet(root, ruleSet)
— 一連の XML ルールを実行するには、
__processRuleSet
関数を呼び
出して、XML 要素や XML ルールセットを指定する必要があります。 この XML 要素では、ルールの処理を
開始する XML 構造内のポイントを定義します。
__processChildren(ruleProcessor)
— 一致する XML 要素の子要素に対して一致する XML ルールを適用
するように、XML ルールプロセッサーに指示します。 これを使用すれば、子 XML 要素が処理された後に、
親 XML 要素に適用したルールでコードを実行することができます。 デフォルトでは、XML ルールプロ
セッサーによって XML 要素の子にルールが適用されると、制御はそのルールに戻されません。
__processChildren
関数を使用すれば、子 XML 要素が処理された後に、ルールの apply
関数に制御を戻
すことができます。
__skipChildren(ruleProcessor)
— 現在の XML 要素の下位要素を XML ルールで処理しないようにプロ
セッサーに指示します。 これは、現在の XML 要素を移動または削除する場合や、XML 構造の不要な部分
をスキップしてパフォーマンスを向上させたい場合などに役立ちます。
XML 構造内の反復処理
方向に通過していき、構造内のそれぞれの XML 要素を 2 回訪れます(XML ファイル内でネストしているタグ
るすべての XML ルールを、現在の XML ルールセットに列挙されている順番で適用しようとします。
__processRuleSet
「深さ優先」の順番で XML 要素にルールを適用します。つまり、XML 要素とその
子要素は、XML 構造に現れる順番で処理されます。 XML ルールプロセッサーは、XML 構造の 1 つの「枝」に
含まれているすべての XML 要素を訪れてから、次の「枝」に移動します。
XML ルールプロセッサーは、ある XML 要素に XML ルールを適用すると、その XML 要素の下位要素に適用で
きるルールがあるかどうかを調べます。
__skipChildren
または
__processChildren
関数を XML ルールで使用
したり、他のルールの動作を変更したりすれば、この動作を変えることができます。
これらの関数の動作を確認するには、
DepthFirstProcessingOrder.xml
ファイルを新規ドキュメントに読み
込んで、
DepthFirstProcessingOrder.jsx
れ、サンプル XML ファイルに含まれている各要素の属性名が、各ルールの訪問順にリストされます。 このス
クリプトと AddAttribute チュートリアルスクリプトを組み合わせれば、作成した XML ドキュメントでの XML
検索の問題点を見つけることができます(XML 構造に合わせて AddAttribute スクリプトを編集する必要があ
第 13 章 XML ルール 概要 186
次の図に、通常の反復処理を示します(構造内のすべての XML 要素に一致するルールが 1 つある場合)。
1
Root
B
2
9
BA BB
3
BAA
4 5
BAB BAC
6
7
BACA BACB
8
BC
次の図に、
__processChildren
を使用した場合の反復処理を示します(構造内のすべての XML 要素に一致す
るルールが 1 つある場合)。
9
Root
B
8
6
5
4
BA
3
BB
7
BC
BAA BAB BAC
1
2
BACA BACB
次のルールセットを使用した場合の反復処理を、スクリプトの後の図に示します。 ルールセットには、すべ
ての要素に一致する 2 つのルールが含まれており、1 つのルールで
__processChildren
が使用されています。
すべての要素は 2 回処理されます (完全なスクリプトについては、ProcessChildren を参照してください)。
第 13 章 XML ルール function NormalRule(){ this.name = "NormalRule";
//XPath will match on every part_number XML element in the XML structure.
this.xpath = "//XMLElement";
// Define the apply function.
this.apply = function(myElement, myRuleProcessor){ app.documents.item(0).stories.item(0).insertionPoints.item(-1).contents = myElement.xmlAttributes.item(0).value + "¥r"; return false;
} //End of apply function
} function ProcessChildrenRule(){ this.name = "ProcessChildrenRule";
//XPath will match on every part_number XML element in the XML structure.
this.xpath = "//XMLElement";
// Define the apply function.
this.apply = function(myElement, myRuleProcessor){
__processChildren(myRuleProcessor); app.documents.item(0).stories.item(0).insertionPoints.item(-1).contents = myElement.xmlAttributes.item(0).value + "¥r"; return false;
} //End of apply function
}
概要 187
3
5
BA
2
Root
1
19
B
18
14
16
7
13
BB
15
BC
17
BAA
4
BAB
6
BAC
8
10
12
BACA BACB
9 11
反復処理時の構造の変更
XML ルールプロセッサーが一致する XML 要素に XML ルールを適用したときに、このルールによってドキュメ
ントの XML 構造が変更されることがあります。 XML ルールプロセッサーの現在のパスに含まれている XML 要
素が変更された場合は、他のルールの適用処理との間で競合が発生する可能性があります。 XML ルールで
XML 構造を変更する場合は、XML ルールプロセッサーでエラーが発生しないように、次の制限を守ってくだ
さい。
上位にある XML 要素の削除 — 一致した XML 要素の上位にある XML 要素を削除したい場合は、その上位
にある XML 要素に一致および処理を行うルールを別途作成します。
親 XML 要素の挿入 — 一致した XML 要素に上位の XML 要素を追加したい場合は、現在の XML 要素を処理
した後に追加します。 上位の XML 要素を追加しても、XML ルールプロセッサーで現在実行されている
ルールの反復処理では処理されません(追加した要素は現在の要素の「上」にあるからです)。
第 13 章 XML ルール 概要 188
現在の XML 要素の削除 — 一致した XML 要素に含まれている子 XML 要素がすべて処理されるまで、その
要素の削除や移動は行えません。 このような変更を行いたい場合は、
__skipChildren
関数を使用した上
で変更を行います。
処理は再実行されない — 処理済みのノードを変更しても、XML ルールが再実行されることはありませ
ん。
複数のルールが一致する場合の処理
複数のルールが 1 つの XML 要素に一致する場合は、XML ルールプロセッサーによって、一致するルールの一
部またはすべてが適用されます。 いずれかのルールの apply
関数が true
を返すまで、ルールセットに列挙さ
れている順に XML ルールが適用されます。 つまり、戻り値の true
は、要素の処理が完了したことを表しま
す。 true
が返されると、その XML 要素に一致する他の XML ルールがあっても無視されます。
XML ルールの apply
関数で false
を返せば、次に一致するルールが適用されるようになります。 apply
関数で false
を返すときは、XML ルールで定義された
XPath
プロパティ以外の条件(スクリプトの他
の変数の状態など)に基づいて、XML ルールの一致動作を制御することができます。
XPath の制限事項
InDesign の XML ルールでは、XPath 1.0 仕様の制限されたサブセットがサポートされています。その代表的な
ものを次に示します。
名前(ルートからのパス)による要素の検索(
/doc/title
ワイルドカードやノード一致を使用したパスの検索(
/doc/*/subtree/node()
指定の属性が指定の値である要素の検索(
/doc/para[@font='Courier']
など)
指定の属性が指定の値でない要素の検索(
/doc/para[@font !='Courier']
数字のインデックス(ただし last()
は除く)を使用した子要素の検索(
/doc/para[3]
など)
現在の要素(self)または子孫要素(descendant)の検索(
//para
など)
終端としてのコメント(comment())の検索(
/doc/comment()
など)
ターゲットなどによる PI の検索(
/doc/processing-instruction('foo')
など)
複数の述語(predicate)の検索(
/doc/para[@font='Courier'][@size=5][2]
など)
following-sibling 軸に沿った検索(
/doc/note/following-sibling::*
など)
この実装では 1 パスの性質があるので、特に次の XPath 式は使用できません。
..
、 ancestor::
、 preceding-sibling::
などの、上位の要素や preceding-sibling 軸は使用できません。
述語でのパス指定は行えません( foo[bar/c]
など)
last()
関数は使用できません
text()
関数の使用やテキストの比較は行えません。ただし、InDesign スクリプティングを使用して、目
的の XML ルールに一致する XML 要素のテキストコンテンツを調べることは可能です。
述語でのブール演算の組み合わせは行えません( foo[@bar=font or @c=size]
述語での比較は行えません( foo[@bar < font or @c > 3]
相対パスは使用できません( doc/chapter
第 13 章 XML ルール 概要 189
エラー処理
XML ルールは InDesign スクリプティングモデルの一部分なので、ルールを使用したスクリプトの基本的な性
質は、通常のスクリプトと同じです。したがって、エラー処理メカニズムも同じものを使用できます。
のエラーは、スクリプト言語に用意されている任意のエラー捕捉メカニズム( try...catch
ブロックなど)
を使用して捕捉できます。
指定がルールに使用されていると、XML ルールプロセッサーの初期化時に InDesign エラーが発生することが
を参照)
また、モデルの変更によって XML ルールプロセッ
サーが無効な状態になった場合にも InDesign エラーが発生することがあります。 XML ルールの処理で XML 構
造を変更すると、XML ルールプロセッサーが無効になる場合があります。 XML 構造に対するこのような変更
は、XML ルールプロセッサーを使用したスクリプト、同時に実行されている別のスクリプト、ユーザーイン
ターフェイスで実行されたユーザーアクションなどによって行われる可能性があります。
XML ルールプロセッサーを無効にするような変更が XML 構造に加えられた場合は、XML ルールプロセッサー
の反復処理が再開されるとエラーが発生します。 エラーメッセージには、エラーの原因となった XML 構造の
変更が表示されます。
XML ルールの制御フロー
XML ルールを含むスクリプトを実行すると、XML ルールを含むスクリプト関数から各 XML ルールに制御が渡
され、さらに各ルールからグルーコードで定義されている関数に制御が渡されます。 これらの関数から XML
ルールプロセッサーに制御が渡され、プロセッサーが構造内の XML 要素を反復処理します。 その結果やエ
ラーは、関数によって処理されるか、スクリプトエラーが発生するまで、このチェーンを逆方向に渡されて
いきます。 次の図に、XML ルールスクリプトの制御フローの概要を示します。
XML
䊦䊷䊦
䉴䉪䊥䊒䊃
XML
䊦䊷䊦
XPath
䈱᧦ઙ apply()
XM
L ru les
XML eleme nt
䉫䊦䊷䉮䊷䊄
XML
䊦䊷䊦
䊒䊨䉶䉾䉰䊷
__processRuleSet
XPath condition
XML element
XPath
䈱⹏ଔ
__processChildren
XML elemen t
XML
᭴ㅧౝ䈱
ᓳಣℂ
__skipChildren
第 13 章 XML ルール
XML ルールの例 190
XML ルールの例
XML ルールでは、XPath 文を使用して目的の XML 要素を指定します。したがって、XML ルールとドキュメン
トの XML 構造の間には緊密な関係があります。 この節では、実際に使用できる XML ルールスクリプトをいく
つか示しますが、そのためには、スクリプトの実行対象となる XML 構造も同時に示す必要があります。 この
章の以降の各節では、サンプル XML データファイルに基づいた XML ルールの例を示します。 この例では、架
空の IC メーカーの製品リストを使用します。 XML データファイルの各レコードの構造は、次のとおりです。
<device>
<name></name>
<type></type>
<part_number></part_number>
<supply_voltage>
<minimum></minimum>
<maximum></maximum>
</supply_voltage>
<package>
<type></type>
<pins></pins>
</package>
<price></price>
<description></description>
</device>
最初は簡単なスクリプトから始めて、徐々に複雑なスクリプトへと進んでいきます。
サンプルドキュメントのセットアップ
この章の各スクリプトを実行する前に、ドキュメントに
XMLRulesExampleData.xml
データファイルを読み込
みます。 XML を読み込む場合は、XML 読み込みオプションダイアログボックスの「空白のみの要素を読み込
まない」オプションをオンにします。 ファイルを保存し、ファイル/復帰を選択してから、この節の各サン
プルスクリプトを実行します。 または、次のスクリプトを実行してから、各サンプル XML ルールスクリプト
を実行します(
XMLRulesExampleSetup.jsx
というスクリプトファイルを参照してください)
//XMLRuleExampleSetup.jsx
// main(); function main(){ var myDocument = app.documents.add(); myDocument.xmlImportPreferences.allowTransform = false; myDocument.xmlImportPreferences.ignoreWhitespace = true; var myScriptPath = myGetScriptPath(); var myFilePath = myScriptPath.path + "/XMLRulesExampleData.xml" myDocument.importXML(File(myFilePath)); var myBounds = myGetBounds(myDocument, myDocument.pages.item(0)); myDocument.xmlElements.item(0).placeIntoFrame(myDocument.pages.item(0), myBounds); function myGetBounds(myDocument, myPage){ var myWidth = myDocument.documentPreferences.pageWidth; var myHeight = myDocument.documentPreferences.pageHeight;
第 13 章 XML ルール
XML ルールの例 191
} var myX1 = myPage.marginPreferences.left; var myY1 = myPage.marginPreferences.top; var myX2 = myWidth - myPage.marginPreferences.right; var myY2 = myHeight - myPage.marginPreferences.bottom; return [myY1, myX1, myY2, myX2];
} function myGetScriptPath() { try { return app.activeScript;
} catch(myError){ return File(myError.fileName);
}
}
最初の XML ルール
まず、非常に単純な XML ルールを作成します。このルールでは、ドキュメントの各 XML 要素の後に改行文字
を追加します。 XML ルールセットには 1 つのルールが含まれています。 完全なスクリプトについては、
AddReturns を参照してください。 main(); function main(){ if (app.documents.length != 0){ var myDocument = app.documents.item(0);
//This rule set contains a single rule.
var myRuleSet = new Array (new AddReturns); with(myDocument){ var elements = xmlElements;
__processRuleSet(elements.item(0), myRuleSet);
}
} else{ alert("No open document");
}
//Adds a return character at the end of every XML element.
function AddReturns(){ this.name = "AddReturns";
//XPath will match on every XML element in the XML structure.
this.xpath = "//*";
// Define the apply function.
this.apply = function(myElement, myRuleProcessor){ with(myElement){
//Add a return character at the end of the XML element.
insertTextAsContent("¥r", XMLElementPosition.ELEMENT_END);
} return true;// Succeeded
} //End of apply function
}
}
第 13 章 XML ルール
XML ルールの例 192
空白文字と静的テキストの追加
次の XML ルールスクリプトは、空白文字と静的テキストを追加するという点では前のスクリプトと似ていま
すが、 要素名に基づいて XML 要素の扱いを変えている点で少し複雑なものになっています。 完全なスクリプ
トについては、AddReturnsAndStaticText を参照してください。 main(); function main(){ if (app.documents.length != 0){ var myDocument = app.documents.item(0);
//This rule set contains a single rule.
var myRuleSet = new Array (new ProcessDevice, new ProcessName, new ProcessType, new ProcessPartNumber, new ProcessSupplyVoltage, new ProcessPackageType, new ProcessPackageOne, with(myDocument){ var elements = xmlElements; new ProcessPackages, new ProcessPrice);
__processRuleSet(elements.item(0), myRuleSet);
}
} else{ alert("No open document");
}
//Adds a return character at the end of the "device" XML element.
function ProcessDevice(){ this.name = "ProcessDevice"; this.xpath = "/devices/device";
// Define the apply function.
this.apply = function(myElement, myRuleProcessor){ with(myElement){
//Add a return character at the end of the XML element.
insertTextAsContent("¥r", XMLElementPosition.afterElement);
} return true;// Succeeded
} //End of apply function
}
//Adds a return character at the end of the "name" XML element.
function ProcessName(){ this.name = "ProcessName"; this.xpath = "/devices/device/name";
// Define the apply function.
this.apply = function(myElement, myRuleProcessor){ with(myElement){
//Add static text at the beginning of the XML element.
insertTextAsContent("Device Name: ",
XMLElementPosition.beforeElement);
//Add a return character at the end of the XML element.
insertTextAsContent("¥r", XMLElementPosition.afterElement);
} return true;// Succeeded
} //End of apply function
}
//Adds a return character at the end of the "type" XML element.
function ProcessType(){ this.name = "ProcessType"; this.xpath = "/devices/device/type";
// Define the apply function.
this.apply = function(myElement, myRuleProcessor){ with(myElement){
//Add static text at the beginning of the XML element.
第 13 章 XML ルール
XML ルールの例 193 insertTextAsContent("Circuit Type: ",
XMLElementPosition.beforeElement);
//Add a return character at the end of the XML element.
insertTextAsContent("¥r", XMLElementPosition.beforeElement);
} return true;// Succeeded
} //End of apply function
}
//Adds a return character at the end of the "part_number" XML element.
function ProcessPartNumber(){ this.name = "ProcessPartNumber"; this.xpath = "/devices/device/part_number";
// Define the apply function.
this.apply = function(myElement, myRuleProcessor){ with(myElement){
//Add static text at the beginning of the XML element.
insertTextAsContent("Part Number: ",
XMLElementPosition.beforeElement);
//Add a return character at the end of the XML element.
insertTextAsContent("¥r", XMLElementPosition.afterElement);
} return true;// Succeeded
} //End of apply function
}
//Adds static text around the "minimum" and "maximum"
//XML elements of the "supply_voltage" XML element.
function ProcessSupplyVoltage(){ this.name = "ProcessSupplyVoltage"; this.xpath = "/devices/device/supply_voltage";
// Define the apply function.
this.apply = function(myElement, myRuleProcessor){
//Note the positions at which we insert the static text. If we use
//XMLElementPosition.elementEnd, the static text will appear
//inside the XML element. If we use XMLElementPosition.afterElement,
//the static text appears outside the XML elment (as a text element of
//the parent element).
with(myElement){
//Add static text to the beginning of the voltage range.
insertTextAsContent("Supply Voltage: From ",
XMLElementPosition.elementStart); with(myElement.xmlElements.item(0)){ insertTextAsContent(" to ", XMLElementPosition.afterElement);
} with(myElement.xmlElements.item(-1)){
//Add static text to the beginning of the voltage range.
insertTextAsContent(" volts", XMLElementPosition.afterElement);
}
//Add a return at the end of the XML element.
insertTextAsContent("¥r", XMLElementPosition.afterElement);
} return true;// Succeeded
} //End of apply function
} function ProcessPackageType(){ this.name = "ProcessPackageType"; this.xpath = "/devices/device/package/type";
// Define the apply function.
this.apply = function(myElement, myRuleProcessor){ with(myElement){ insertTextAsContent("-", XMLElementPosition.afterElement);
} return true;
} //End of apply function
}
第 13 章 XML ルール
XML ルールの例 194
//Add the text "Package:" before the list of packages.
function ProcessPackageOne(){ this.name = "ProcessPackageOne"; this.xpath = "/devices/device/package[1]"; this.apply = function(myElement, myRuleProcessor){ with(myElement){ insertTextAsContent("Package: ", XMLElementPosition.elementStart);
} return false; //Return false to let other XML rules process the element.
} //End of apply function
}
//Add commas between the package types.
function ProcessPackages(){ this.name = "ProcessPackages"; this.xpath = "/devices/device/package"; this.apply = function(myElement, myRuleProcessor){ with(myElement){ if(myElement.parent.xmlElements.nextItem(myElement).markupTag.name ==
"package"){ insertTextAsContent(", ", XMLElementPosition.elementEnd);
} else{ insertTextAsContent("¥r", XMLElementPosition.afterElement);
}
} return true;
} //End of apply function
} function ProcessPrice(){ this.name = "ProcessPrice"; this.xpath = "/devices/device/price";
// Define the apply function.
this.apply = function(myElement, myRuleProcessor){ with(myElement){ insertTextAsContent("Price: $", XMLElementPosition.beforeElement);
//Add a return at the end of the XML element.
insertTextAsContent("¥r", XMLElementPosition.afterElement);
} return true;// Succeeded
} //End of apply function
}
}
注意 : このスクリプト(の
ProcessPackages
という XML ルール)では、繰り返される要素の間にカンマを追
加しています。 同じレベルに類似の要素が並んでいる場合は、forward-axis 一致を使用して同じことを実
行できます。 次のような XML 構造があるとします。
<xmlElement><item>1</item><item>2</item><item>3</item><item>4</item>
</xmlElement>
それぞれの item
という XML 要素の間にカンマを追加してレイアウトするには、次のような XML ルール
を使用します(チュートリアルスクリプトの ListProcessing より)。
第 13 章 XML ルール
XML ルールの例 195 var myRuleSet = new Array (new ListItems); var myDocument = app.documents.item(0); with(myDocument){ var elements = xmlElements;
__processRuleSet(elements.item(0), myRuleSet);
}
//Add commas between each "item" element.
function ListItems(){ this.name = "ListItems";
//Match all following sibling XML elements
//of the first "item" XML element.
this.xpath = "/xmlElement/item[1]/following-sibling::*"; this.apply = function(myElement, myRuleProcessor){ with(myElement){ insertTextAsContent(", ", XMLElementPosition.beforeElement);
} return false; //Let other XML rules process the element.
}
}
XML ルールを使用した XML 構造の変更
InDesign の XML の実装においては、XML 要素の順番が重要になるので、XML ルールを使用して構造内の要素
の順番を変更したい場合が考えられます。 一般に、XML ドキュメントの構造を大幅に変更する場合は、
InDesign に XML を読み込む前か読み込むときに、XSLT ファイルを使用してドキュメントを変換するのが最も
よい方法です。 move
XML プロセッサーが無
効にならないように、グルーコードで
__skipChildren
関数を使用している点に注意してください。
クリプトについては、MoveXMLElement を参照してください。 main(); function main(){ if (app.documents.length != 0){ var myDocument = app.documents.item(0);
//This rule set contains a single rule.
var myRuleSet = new Array (new MoveElement); with(myDocument){ var elements = xmlElements;
__processRuleSet(elements.item(0), myRuleSet);
}
} else{ alert("No open document");
}
//Adds a return character at the end of every XML element.
function MoveElement(){ this.name = "MoveElement";
//XPath will match on every part_number XML element in the XML structure.
this.xpath = "/devices/device/part_number";
// Define the apply function.
this.apply = function(myElement, myRuleProcessor){
//Moves the part_number XML element to the start of
//the device XML element (the parent).
__skipChildren(myRuleProcessor); myElement.move(LocationOptions.before, myElement.parent.xmlElements.item(0)); return true;// Succeeded
} //End of apply function
}
}
第 13 章 XML ルール
XML ルールの例 196
XML ルールを使用した XML 要素の複製
第 12 章「XML」 で説明したように、XML 要素とレイアウト内の対応する表現との間には、1 対 1 の関係があ
DuplicateXMLElement を参照してください。
__skipChildren
を使用して無効な XML オブ
ジェクト参照を回避しています。
#include "glue code.jsx" main(); function main(){ if (app.documents.length != 0){ var myDocument = app.documents.item(0);
//This rule set contains a single rule.
var myRuleSet = new Array (new DuplicateElement); with(myDocument){ var elements = xmlElements;
__processRuleSet(elements.item(0), myRuleSet);
}
} else{ alert("No open document");
}
//Duplicates the part number element in each XML element.
function DuplicateElement(){ this.name = "DuplicateElement"; this.xpath = "/devices/device/part_number"; this.apply = function(myElement, myRuleProcessor){
//Duplicates the part_number XML element.
__skipChildren(myRuleProcessor); myElement.duplicate(); return true;
}
}
}
XML ルールと XML 属性
次の XML ルールでは、「name」要素の内容に基づいて XML 要素に属性を追加しています。 XML ルールで、テ
キストコンテンツに基づいて要素を検索する必要がある場合は、XML 要素の内容を、親の XML 要素の XML 属
性にコピーまたは移動すると便利です。 XML ルールでサポートされている XPath のサブセットでは、要素の
テキストを検索することはできませんが、属性値に基づいて要素を検索することは可能です。 完全なスクリ
プトについては、AddAttribute を参照してください。
第 13 章 XML ルール
XML ルールの例 197 main(); function main(){ if (app.documents.length != 0){ var myDocument = app.documents.item(0); var myRuleSet = new Array (new AddAttribute); with(myDocument){ var elements = xmlElements;
__processRuleSet(elements.item(0), myRuleSet);
}
} else{ alert("No open document");
} function AddAttribute(){ this.name = "AddAttribute"; this.xpath = "/devices/device/part_number"; this.apply = function(myElement, myRuleProcessor){ myElement.parent.xmlAttributes.add("part_number", myElement.texts.item(0).contents); return true;
}
}
}
前述の XML ルールでは、ある XML 要素のデータを、親の XML 要素の XML 属性にコピーしました。 では、XML
要素のデータを属性に移動して、その XML 要素を削除したい場合はどうすればよいでしょうか。 その場合は、 convertToAttribute
メソッドを使用します。次のスクリプトにその例を示します(チュートリアルスクリプ
トの ConvertToAttribute より)。 main(); function main(){ if (app.documents.length != 0){ var myDocument = app.documents.item(0); var myRuleSet = new Array (new ConvertToAttribute); with(myDocument){ var elements = xmlElements;
__processRuleSet(elements.item(0), myRuleSet);
}
} else{ alert("No open document");
}
//Converts all part_number XML elements to XML attributes.
function ConvertToAttribute(){ this.name = "ConvertToAttribute"; this.xpath = "/devices/device/part_number";
// Define the apply function.
this.apply = function(myElement, myRuleProcessor){
//Use __skipChildren to prevent the XML rule processor from becoming
//invalid when we convert the XML element to an attribute.
__skipChildren(myRuleProcessor);
//Converts the XML element to an XML attribute of its parent XML element.
myElement.convertToAttribute("PartNumber"); return true;
}
}
}
convertToElement
メ
ソッドを使用します。
第 13 章 XML ルール
XML ルールの例 198
複数の一致ルールの適用
ある XML ルールの apply
関数で true を返すと、それ以降の XML ルールは XML 要素に適用されなくなります。 apply
次のスクリプトは、false
を返す XML ルール apply
関数の例を示しています。
素に一致する 2 つのルールが含まれています。 最初のルールは特定のカラーを適用して false を返しますが、2
番目のルールは( myCounter
という変数の状態に基づいて)1 つおきに XML 要素に別のカラーを適用する点
が異なります。 完全なスクリプトについては、ReturningFalse を参照してください。 main(); function main(){ myCounter = 0; if (app.documents.length != 0){ var myDocument = app.documents.item(0);
//Define two colors. var myColorA = myDocument.colors.add({model:ColorModel.process, colorValue:[0, 100, 80, 0], name:"ColorA"}); var myColorB = myDocument.colors.add({model:ColorModel.process, colorValue:[100, 0, 80, 0], name:"ColorB"}) var myRuleSet = new Array (new ReturnFalse, new ReturnTrue); with(myDocument){ var elements = xmlElements;
__processRuleSet(elements.item(0), myRuleSet);
}
} else{ alert("No open document");
}
//Adds a color to the text of every element in the structure.
function ReturnFalse(){ this.name = "ReturnFalse";
//XPath will match on every XML element in the XML structure.
this.xpath = "//*"; this.apply = function(myElement, myRuleProcessor){ with(myElement){ myElement.texts.item(0).fillColor = app.documents.item(0).colors.item("ColorA");
}
// Leaves the XML element available to further processing.
return false;
}
}
//Adds a color to the text of every other element in the structure.
function ReturnTrue(){ this.name = "ReturnTrue";
//XPath will match on every XML element in the XML structure.
this.xpath = "//*"; this.apply = function(myElement, myRuleProcessor){ with(myElement){ if(myCounter % 2 == 0){ myElement.texts.item(0).fillColor = app.documents.item(0).colors.item("ColorB");
} myCounter++;
}
//Do not process the element with any further matching rules.
return true;
}
}
}
第 13 章 XML ルール
XML ルールの例 199
XML 要素の検索
既に説明したように、XML ルールでサポートされている XPath のサブセットでは、XML 要素のテキストコン
テンツを検索することはできません。 この制約を回避するには、属性を使用して目的の XML 要素を検索する
か、一致する XML 要素のテキストを検索します。 属性を使用して XML 要素を検索する方法を、次のスクリプ
トに示します。 このスクリプトでは、検索した要素のテキストにカラーを適用していますが、実際のスクリ
プトではより意味のある処理を行うことになります。 完全なスクリプトについては、
FindXMLElementByAttribute を参照してください。 main(); function main(){ if (app.documents.length != 0){ var myDocument = app.documents.item(0); var myRuleSet = new Array(new AddAttribute); with(myDocument){ var elements = xmlElements;
__processRuleSet(elements.item(0), myRuleSet);
}
//Now that the attributes have been added, find and format
//the XML element whose attribute content matches a specific string.
var myRuleSet = new Array(new FindAttribute); with(myDocument){ var elements = xmlElements;
__processRuleSet(elements.item(0), myRuleSet);
}
} else{ alert("No open document");
} function AddAttribute(){ this.name = "AddAttribute"; this.xpath = "/devices/device/part_number"; this.apply = function(myElement, myRuleProcessor){ myElement.parent.xmlAttributes.add("part_number", myElement.texts.item(0).contents); return true;
}
} function FindAttribute(){ this.name = "FindAttribute"; this.xpath = "/devices/device[@part_number = 'DS001']"; this.apply = function(myElement, myRuleProcessor){ myElement.xmlElements.item(0).texts.item(0).fillColor = app.documents.item(0).swatches.item(-1); return true;
}
}
}
JavaScript の正規表現(RegExp)を使用して、コンテンツに基づいて XML 要素を検索およびフォーマットす
る方法を、次のスクリプトに示します(完全なスクリプトについては、FindXMLElementByRegExp を参照して
第 13 章 XML ルール
XML ルールの例 200 main(); function main(){ if (app.documents.length != 0){ var myDocument = app.documents.item(0); var myRuleSet = new Array (new FindByContent); with(myDocument){ var elements = xmlElements;
__processRuleSet(elements.item(0), myRuleSet);
}
} else{ alert("No open document");
} function FindByContent(){
//Find descriptions that contain both "triangle" and "pulse".
var myRegExp = /triangle.*?pulse|pulse.*?triangle/i
}
} function myResetFindChangeGrep(){ app.findGrepPreferences = NothingEnum.nothing; app.changeGrepPreferences = NothingEnum.nothing;
} this.name = "FindByContent";
//XPath will match on every description in the XML structure.
this.xpath = "/devices/device/description"; this.apply = function(myElement, myRuleProcessor){ if(myRegExp.test(myElement.texts.item(0).contents) == true){ myElement.texts.item(0).fillColor = app.documents.item(0).swatches.item(-1);
} return true;
} findText
メソッドを使用して、XML コンテンツを検索およびフォーマットする方法を、次のスクリプトに示
します(完全なスクリプトについては、FindXMLElementByFindText を参照してください)。 main(); function main(){ if (app.documents.length != 0){ var myDocument = app.documents.item(0); var myRuleSet = new Array (new FindByFindText); with(myDocument){ var elements = xmlElements;
__processRuleSet(elements.item(0), myRuleSet);
}
} else{ alert("No open document");
} function FindByFindText(){ this.name = "FindByFindText"; this.xpath = "/devices/device/description"; this.apply = function(myElement, myRuleProcessor){ if(myElement.texts.item(0).contents != ""){
//Clear the find text preferences.
myResetFindText();
//Search for the word "triangle" in the content of the element.
第 13 章 XML ルール
XML ルールの例 201 app.findTextPreferences.findWhat = "triangle"; var myFoundItems = myElement.texts.item(0).findText(); if(myFoundItems.length != 0){ myElement.texts.item(0).fillColor = app.documents.item(0).swatches.item(-1);
} myResetFindText();
} return true;
}
} function myResetFindText(){ app.findTextPreferences = NothingEnum.nothing; app.changeTextPreferences = NothingEnum.nothing;
}
} findGrep
メソッドを使用して、XML コンテンツを検索およびフォーマットする方法を、次のスクリプトに示
します(完全なスクリプトについては、FindXMLElementByFindGrep を参照してください)。 main(); function main(){ if (app.documents.length != 0){ var myDocument = app.documents.item(0); var myRuleSet = new Array (new FindByContent); myResetFindChangeGrep(); app.findGrepPreferences.findWhat = "(?i)pulse.*?triangle|triangle.*?pulse"; with(myDocument){ var elements = xmlElements;
__processRuleSet(elements.item(0), myRuleSet);
} myResetFindChangeGrep();
} else{ alert("No open document");
} function FindByContent(){
//Find descriptions that contain both "triangle" and "pulse".
this.name = "FindByContent";
//XPath will match on every description in the XML structure.
this.xpath = "/devices/device/description";
// Define the apply function.
this.apply = function(myElement, myRuleProcessor){ var myFoundItems = myElement.texts.item(0).findGrep(); if(myFoundItems.length != 0){ myElement.texts.item(0).fillColor = app.documents.item(0).swatches.item(-1);
} return true;
}
} function myResetFindChangeGrep(){ app.findGrepPreferences = NothingEnum.nothing; app.changeGrepPreferences = NothingEnum.nothing;
}
}
XML ルールを使用した XML 要素の抽出
ルを使用して行うことができます。 一連のサンプル XML 要素を複製して、XML 要素階層の別の場所に移動す
る方法を、次のサンプルスクリプトに示します。 複製した XML 要素は、XML ルールに一致しない XML 構造の
場所に追加する必要があることに注意してください。そうしなかった場合は、無限ループに陥る恐れがあり
ます。 完全なスクリプトについては、ExtractSubset を参照してください。
第 13 章 XML ルール
XML ルールの例 202 main(); function main(){ if (app.documents.length != 0){ var myDocument = app.documents.item(0); var myRuleSet = new Array (new ExtractVCO); var myMarkupTag = myDocument.xmlTags.add("VCOs"); var myContainerElement = myDocument.xmlElements.item(0).xmlElements.add(myMarkupTag); with(myDocument){ var elements = xmlElements;
__processRuleSet(elements.item(0), myRuleSet);
}
} else{ alert("No open document");
} function ExtractVCO(){ var myNewElement; this.name = "ExtractVCO"; this.xpath = "/devices/device/type"; this.apply = function(myElement, myRuleProcessor){ with(myElement){ if(myElement.texts.item(0).contents == "VCO"){ myNewElement = myElement.parent.duplicate(); myNewElement.move(LocationOptions.atEnd, app.documents.item(0).xmlElements.item(0).xmlElements.item(-1));
}
} return true;
}
}
}
XML ルールを使用したフォーマットの適用
これまでの XML ルールの例では、XML 要素の検索、XML 要素の並べ替え、XML 要素へのテキストの追加を行
う基本的な方法を示しました。 XML ルールはスクリプトの一部であるので、テキストフォーマットの適用か
らページアイテム、ページ、ドキュメントの新規作成まで、ほとんどすべてのアクションを実行できます。
次の XML ルールの例では、XML ルールを使用して XML 要素にフォーマットを適用する方法と、XML ルール
の一致に基づいて新規ページアイテムを作成する方法を示します。
次のスクリプトでは、XML のサンプルデータに静的テキストを追加し、フォーマットを適用しています(完
全なスクリプトについては、XMLRulesApplyFormatting を参照してください)。 main(); function main(){ if (app.documents.length != 0){ var myDocument = app.documents.item(0);
//Document set-up.
myDocument.viewPreferences.horizontalMeasurementUnits =
MeasurementUnits.points; myDocument.viewPreferences.verticalMeasurementUnits =
MeasurementUnits.points; myDocument.colors.add({model:ColorModel.process, colorValue:[0, 100, 100, 0], name:"Red"}); myDocument.paragraphStyles.add({name:"DeviceName", pointSize:24, leading:24, spaceBefore:24, fillColor:"Red", paragraphRuleAbove:true}); myDocument.paragraphStyles.add({name:"DeviceType", pointSize:12, fontStyle:"Bold", leading:12}); myDocument.paragraphStyles.add({name:"PartNumber", pointSize:12, fontStyle:"Bold", leading:12}); myDocument.paragraphStyles.add({name:"Voltage", pointSize:10, leading:12}); myDocument.paragraphStyles.add({name:"DevicePackage", pointSize:10, leading:12});
第 13 章 XML ルール myDocument.paragraphStyles.add({name:"Price", pointSize:10, leading:12, fontStyle:"Bold"}); var myRuleSet = new Array (new ProcessDevice, new ProcessName, new ProcessType, new ProcessPartNumber, new ProcessSupplyVoltage, new ProcessPackageType, new ProcessPackageOne, new ProcessPackages, new ProcessPrice); with(myDocument){ var elements = xmlElements;
__processRuleSet(elements.item(0), myRuleSet);
}
} else{ alert("No open document");
} function ProcessDevice(){ this.name = "ProcessDevice"; this.xpath = "/devices/device"; this.apply = function(myElement, myRuleProcessor){ with(myElement){ insertTextAsContent("¥r", XMLElementPosition.afterElement);
} return true;
}
} function ProcessName(){ this.name = "ProcessName"; this.xpath = "/devices/device/name"; this.apply = function(myElement, myRuleProcessor){ var myDocument = app.documents.item(0); with(myElement){ insertTextAsContent("¥r", XMLElementPosition.afterElement); applyParagraphStyle(myDocument.paragraphStyles.
item("DeviceName"));
} return true;
}
} function ProcessType(){ this.name = "ProcessType"; this.xpath = "/devices/device/type"; this.apply = function(myElement, myRuleProcessor){ var myDocument = app.documents.item(0); with(myElement){ insertTextAsContent("Circuit Type: ", XMLElementPosition.beforeElement); insertTextAsContent("¥r", XMLElementPosition.afterElement); applyParagraphStyle(myDocument.paragraphStyles.
item("DeviceType"));
} return true;
}
} function ProcessPartNumber(){ this.name = "ProcessPartNumber"; this.xpath = "/devices/device/part_number"; this.apply = function(myElement, myRuleProcessor){ var myDocument = app.documents.item(0); with(myElement){
//Add static text at the beginning of the XML element.
insertTextAsContent("Part Number: ", XMLElementPosition.beforeElement);
//Add a return character at the end of the XML element.
insertTextAsContent("¥r", XMLElementPosition.afterElement);
XML ルールの例 203
第 13 章 XML ルール
XML ルールの例 204 applyParagraphStyle(myDocument.paragraphStyles.
item("PartNumber"));
} return true;
}
}
//Adds static text around the "minimum" and "maximum"
//XML elements of the "supply_voltage" XML element.
function ProcessSupplyVoltage(){ this.name = "ProcessSupplyVoltage"; this.xpath = "/devices/device/supply_voltage"; this.apply = function(myElement, myRuleProcessor){ var myDocument = app.documents.item(0);
//Note the positions at which we insert the static text.
//If we use XMLElementPosition.elementEnd, the static text
//will appear inside the XML element. If we use
//XMLElementPosition.afterElement, the static text appears
//outside the XML elment (as a text element of the parent element).
with(myElement){
//Add static text to the beginning of the voltage range.
insertTextAsContent("Supply Voltage: From ",
XMLElementPosition.beforeElement); with(myElement.xmlElements.item(0)){ insertTextAsContent(" to ", XMLElementPosition.afterElement);
} with(myElement.xmlElements.item(-1)){
//Add static text to the beginning of the voltage range.
insertTextAsContent(" volts", XMLElementPosition.afterElement);
}
//Add a return at the end of the XML element.
insertTextAsContent("¥r", XMLElementPosition.afterElement); applyParagraphStyle(myDocument.paragraphStyles.item("Voltage"));
} return true;
}
} function ProcessPackageType(){ this.name = "ProcessPackageType"; this.xpath = "/devices/device/package/type"; this.apply = function(myElement, myRuleProcessor){ var myDocument = app.documents.item(0); with(myElement){ insertTextAsContent("-", XMLElementPosition.afterElement);
} return true;
}
}
//Add the text "Package:" before the list of packages.
function ProcessPackageOne(){ this.name = "ProcessPackageOne"; this.xpath = "/devices/device/package[1]"; this.apply = function(myElement, myRuleProcessor){ with(myElement){ insertTextAsContent("Package: ", XMLElementPosition.beforeElement);
} return false; //Return false to let other XML rules process the element.
}
}
//Add commas between the package types.
function ProcessPackages(){ this.name = "ProcessPackages"; this.xpath = "/devices/device/package"; this.apply = function(myElement, myRuleProcessor){ var myDocument = app.documents.item(0);
第 13 章 XML ルール
XML ルールの例 205
}
} with(myElement){ if(myElement.parent.xmlElements.nextItem(myElement).
markupTag.name == "package"){ insertTextAsContent(", ", XMLElementPosition.afterElement);
} else{ insertTextAsContent("¥r", XMLElementPosition.afterElement); applyParagraphStyle(myDocument.paragraphStyles.
item("DevicePackage"));
}
} return true;
} function ProcessPrice(){ this.name = "ProcessPrice"; this.xpath = "/devices/device/price"; this.apply = function(myElement, myRuleProcessor){ var myDocument = app.documents.item(0); with(myElement){ insertTextAsContent("Price: $", XMLElementPosition.beforeElement);
//Add a return at the end of the XML element.
insertTextAsContent("¥r", XMLElementPosition.afterElement); applyParagraphStyle(myDocument.paragraphStyles.item("Price"));
} return true;
}
}
XML ルールを使用したページアイテムの作成
次のスクリプトでは、新しいページアイテムを作成し、そのページアイテムに XML 要素の内容を挿入し、静
的テキストを追加して、フォーマットを適用しています。 ここでは、スクリプト内の該当する XML ルールの
部分のみを示します。詳しくは、完全なスクリプト(XMLRulesLayout)を参照してください。
最初のルールでは、それぞれの「device」という XML 要素に新規テキストフレームを作成します。
//Creates a new text frame on each page.
function ProcessDevice(){ this.name = "ProcessDevice"; this.xpath = "/devices/device"; this.apply = function(myElement, myRuleProcessor){ var myDocument = app.documents.item(0); with(myElement){ insertTextAsContent("¥r", XMLElementPosition.afterElement); if(myDocument.pages.item(0).textFrames.length == 0){ myPage = myDocument.pages.item(0);
} else{ myPage = myDocument.pages.add();
} var myBounds = myGetBounds(myDocument, myPage); var myTextFrame = placeIntoFrame(myPage, myBounds); myTextFrame.textFramePreferences.firstBaselineOffset =
FirstBaseline.leadingOffset;
} return true;
}
}
第 13 章 XML ルール
XML ルールを使用した表の作成 206
//Creates a new text frame at the top of the page to contain the "type" XML element.
function ProcessType(){ this.name = "ProcessType"; this.xpath = "/devices/device/type"; this.apply = function(myElement, myRuleProcessor){ var myDocument = app.documents.item(0); with(myElement){ var myBounds = myGetBounds(myDocument, myDocument.pages.item(-1)); myBounds = [myBounds[0]-24, myBounds[1], myBounds[0], myBounds[2]]; var myTextFrame = placeIntoFrame(myPage, myBounds); applyParagraphStyle(myDocument.paragraphStyles.item("DeviceType")); myTextFrame.textFramePreferences.insetSpacing = [6, 6, 6, 6]; myTextFrame.fillColor = myDocument.swatches.item("Red")
} return true;
}
}
XML ルールを使用した表の作成
convertElementToTable
ただし、このメ
ソッドで表に変換できるのは、すべての XML 要素が特定の XML タグ(行タグと、セルタグまたは列タグ)で
構成されている場合のみです。 多くの場合、表に変換したい XML データはそのような構造になっていません。
列に使用したい XML 要素は、「price」や「part number」などの異質な XML タグである場合が多いです。
この制限に対応するには、表の列として追加したい XML 要素を、コンテナ XML 要素を使用して「ラップ」し
ます。次のスクリプトにその例を示します(XMLRulesTable を参照してください)。 この例では、XML ルール
を使用して各行の XML 要素を作成しています。 function ProcessDevice(){ this.name = "ProcessDevice"; this.xpath = "//device[@type = 'VCO']"; this.apply = function(myElement, myRuleProcessor){ var myNewElement = myContainerElement.xmlElements.add( app.documents.item(0).xmlTags.item("Row")); return true;
}
}
次のルールでは、行 XML 要素内のコンテナ要素にその内容を移動してフォーマットしています。 function ProcessPrice(){ this.name = "ProcessPrice"; this.xpath = "//device[@type = 'VCO']/price"; this.apply = function(myElement, myRuleProcessor){ with(myElement){
__skipChildren(myRuleProcessor); var myNewElement = myContainerElement.xmlElements.item(-1)
.xmlElements.add(app.documents.item(0).xmlTags.item("Column")); var myElement = myElement.move(LocationOptions.atBeginning, myNewElement); myElement.insertTextAsContent("$",
XMLElementPosition.beforeElement);
} return true;
}
}
}
指定された XML 要素をすべて「ラップ」したら、コンテナ要素を表に変換します。 var myTable = myContainerElement.convertElementToTable(myRowTag, myColumnTag);
第 13 章 XML ルール
XML ルールプロセッサーオブジェクトのスクリプティング 207
XML ルールプロセッサーオブジェクトのスクリプティング
glue code.jsx
で一連のユーティリティ関数が既に提供されていますが、XML ルールプロセッサーオブジェ
クトをスクリプトで直接操作することもできます。 これは、XML ルールのサポート関数を開発したり、XML
ルールプロセッサーを別の方法で使用したりする場合に必要になります。
スクリプトを使用して、XML ルールのコンテキストの外部で XML 要素を操作した場合、XPath を使用して要
素を探すことはできません。 しかし、一致する XML 要素を単純に返す XML ルールを作成して、XML ルールプ
ロセッサーでルールを適用することが可能です。次のスクリプトにその例を示します (このスクリプトで
も、以前の節のサンプルスクリプトと同じ XML データファイルを使用します)。 完全なスクリプトについて
は、XMLRulesProcessor を参照してください。 main(); function main(){ var myXPath = ["/devices/device"]; var myXMLMatches = mySimulateXPath(myXPath);
//At this point, myXMLMatches contains all of the XML elements
//that matched the XPath expression provided in myXPath.
function mySimulateXPath(myXPath){ var myXMLElements = new Array; var myRuleProcessor = app.xmlRuleProcessors.add(myXPath); try{ var myMatchData = myRuleProcessor.startProcessingRuleSet(app.documents.
item(0).xmlElements.item(0)); while(myMatchData != undefined){ var myElement = myMatchData.element; myXMLElements.push(myElement); myMatchData = myRuleProcessor.findNextMatch();
} catch (myError){ myRuleProcessor.endProcessingRuleSet(); myRuleProcessor.remove(); throw myError;
}
} myRuleProcessor.endProcessingRuleSet(); myRuleProcessor.remove(); return myXMLElements;
}
}
14
変更のトラック
CS6
章の更新ステータス
変更なし
原稿作成や編集作業の進行中に、ドキュメントの変更のトラック、表示/非表示、適用、取り消しを実行で
このチュートリアルでは、変更のトラックに関する一般的な操作をスクリプトで実行する方法について説明
します。
ここでは、読者が『Adobe InDesign スクリプティングチュートリアル』を既に読んでおり、スクリプトを作
成、インストール、実行する方法を理解しているものとして説明を行います。 また、InDesign でテキストを
操作する方法や、組版に関する基本的な用語を理解しているものとしています。
変更のトラック
ここでは、スクリプトを使用して、トラックされた変更に移動したり、変更を適用および取り消しする方法
について説明します。
既存のストーリーに含まれているテキストの追加や削除、移動が行われると、その変更がゲラビューおよび
ストーリービューに示されます。
トラックされた変更への移動
トラックされた変更の記録がストーリーに含まれている場合、ユーザーはトラックされた変更に順次移動す
ることができます。 トラックされた変更に移動する方法を、次のスクリプトに示します(完全なスクリプト
については、GetTrackchange を参照してください)。
次のスクリプトでは、 nextItem
メソッドを使用して、挿入点の後の変更に移動します。 var myDocument = app.documents.item(0); var myStory = myDocument.stories.item(0);
//Story.trackChanges If true, track changes is turned on.
if(myStory.trackChanges==true)
{ var myChangeCount = myStory.changes.length; var myChange = myStory.changes.item(0); if(myChangeCount>1)
{ var myChange0 = myStory.changes.nextItem(myChange);
}
}
次のスクリプトでは、 previousItem
メソッドを使用して、挿入点の前の変更に移動します。
208
第 14 章 変更のトラック 変更のトラック 209 var myDocument = app.documents.item(0); var myStory = myDocument.stories.item(0);
//Story.trackChanges If true, track changes is turned on.
if(myStory.trackChanges==true)
{ var myChangeCount = myStory.changes.length; var myChange = myStory.changes.lastItem(); if(myChangeCount>1)
{ var myChange0 = myStory.changes.previousItem(myChange);
}
}
トラックされた変更の適用と取り消し
ストーリーに対する変更が行われた場合、変更のトラック機能を使用してすべての変更を見直したり、ス
トーリーにすべての変更を組み込むかどうかを決定できます。 ユーザーは、すべてのユーザーが行った変更
(テキストの追加や削除、移動)を適用および取り消しすることができます。
次のスクリプトでは、変更を適用します(完全なスクリプトについては、AcceptChange を参照してくださ var myDocument = app.documents.item(0); var myStory = myDocument.stories.item(0); var myChange = myStory.changes.item(0); myChange.accept() ;
次のスクリプトでは、変更を取り消します(完全なスクリプトについては、RejectChange を参照してくださ var myDocument = app.documents.item(0); var myStory = myDocument.stories.item(0); var myChange = myStory.changes.item(0); myChange.reject() ;
トラックされた変更に関する情報
変更の情報には日付や時間などが含まれています。 次のスクリプトでは、トラックされた変更の情報を表示
します(完全なスクリプトについては、GetChangeInfo を参照してください)。
第 14 章 変更のトラック 変更のトラックの環境設定 210 var myDocument = app.documents.item(0); var myStory = myDocument.stories.item(0); var myChange = myStory.changes.item(0);
//ChangeTypes.DELETED_TEXT (Read Only) Deleted text.
//ChangeTypes.DELETED_TEXT (Read Only) Deleted text.
//ChangeTypes.MOVED_TEXT (Read Only) Moved text.
var myChangeTypes = myChange.changeType;
//Characters A collection of characters.
var myCharacters = myChange.characters; var myDate = myChange.date;
//InsertionPoints A collection of insertion points.
var myInsertionPoints = myChange.insertionPoints;
//Change.lines (Read Only) A collection of lines.
var myLines = myChange.lines;
//Change.paragraphs (Read Only) A collection of paragraphs.
var myParagraphs = myChange.paragraphs; var myStoryOffset = myChange.storyOffset;
//Change.textColumns (Read Only) A collection of text columns.
var myTextColumns = myChange.textColumns;
//Change.textStyleRanges (Read Only) A collection of text style ranges.
var myTextStyleRanges = myChange.textStyleRanges;
//Change.textVariableInstances (Read Only) A collection of text variable instances.
var myTextVariableInstances = myChange.textVariableInstances;
//Change.texts (Read Only) A collection of text objects.
var myTexts = myChange.texts; var myUserName = myChange.userName; var myWords = myChange.words;
変更のトラックの環境設定
変更のトラックの環境設定とは、変更のトラックに関するユーザー設定です。 例えば、トラックされる変更
の種類(テキストの追加や削除、移動)を定義できます。 トラックされた変更の種類別の外観を指定したり、
マージンの色付きの変更バーで変更を識別したりできます。 これらの環境設定を設定して取得する方法を、
次のスクリプトに示します(完全なスクリプトについては、GetChangePreference を参照してください)。 var myTrackChangesPreference = app.trackChangesPreferences; with(myTrackChangesPreference)
{ addedBackgroundColorChoice =
ChangeBackgroundColorChoices.CHANGE_BACKGROUND_USES_CHANGE_PREF_COLOR; addedTextColorChoice = ChangeTextColorChoices.CHANGE_USES_CHANGE_PREF_COLOR; backgroundColorForAddedText = UIColors.gray; var myColor = backgroundColorForDeletedText; backgroundColorForDeletedText = UIColors.red; backgroundColorForMovedText = UIColors.pink; changeBarColor = UIColors.charcoal; deletedBackgroundColorChoice
=ChangeBackgroundColorChoices.CHANGE_BACKGROUND_USES_CHANGE_PREF_COLOR; deletedTextColorChoice = ChangeTextColorChoices.CHANGE_USES_CHANGE_PREF_COLOR;
//ChangebarLocations.LEFT_ALIGN (Read Only) Change bars are in the left margin.
//ChangebarLocations.RIGHT_ALIGN (Read Only) Change bars are in the right margin locationForChangeBar = ChangebarLocations.LEFT_ALIGN;
//ChangeMarkings.OUTLINE (Read Only) Outlines changed text.
//ChangeMarkings.NONE (Read Only) Does not mark changed text.
//ChangeMarkings.STRIKETHROUGH (Read Only) Uses a strikethrough to mark changed text.
//ChangeMarkings.UNDERLINE_SINGLE (Read Only) Underlines changed text.
第 14 章 変更のトラック 変更のトラックの環境設定 211 markingForAddedText = ChangeMarkings.OUTLINE; markingForDeletedText = ChangeMarkings.STRIKETHROUGH; markingForMovedText = ChangeMarkings.UNDERLINE_SINGLE; movedBackgroundColorChoice =
ChangeBackgroundColorChoices.CHANGE_BACKGROUND_USES_CHANGE_PREF_COLOR; movedTextColorChoice = ChangeTextColorChoices.CHANGE_USES_CHANGE_PREF_COLOR; showAddedText = true; shhowDeletedText = true; showMovedText = true; spellCheckDeletedtext = true; showChangeBar = true; textColorForAddedText = UIColors.blue; textColorForDeletedText = UIColors.yellow; textColorForMovedText = UIColors.green;
}
다운로드
광고