Adobe InDesign CS6 Reference guide
Adobe InDesign CS6 is a powerful desktop publishing software that allows you to create professional-quality documents, such as brochures, magazines, and ebooks. The software offers a wide range of features, including advanced layout and typography tools, support for color management, and the ability to export documents in a variety of formats. The InDesign CS6 Scripting Guide provides information on how to use JavaScript to automate tasks and customize the software.
Advertisement
Advertisement
ADOBE® INDESIGN® CS6
2012 Adobe Systems Incorporated. All rights reserved.
更新
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.
目次
1
2
13
14
14
14
3
21
21
21
22
23
23
23
24
25
26
27
29
30
32
33
34
37
39
39
39
40
3
目次
4
41
41
43
43
44
45
45
45
48
48
48
49
50
50
51
52
52
54
54
54
55
4
5
59
59
60
61
61
61
61
62
62
67
68
68
69
70
目次
5
73
73
75
75
76
6
77
77
77
77
78
78
78
79
80
80
81
81
82
82
90
91
92
94
95
95
95
95
97
98
99
108
108
109
110
110
112
目次
6
7
118
118
118
119
8
9
10
146
147
147
147
目次
7
カスタムルール . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
使用可能なルール . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ADBE_BlankPages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ADBE_BleedSlug . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ADBE_BleedTrimHazard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ADBE_Colorspace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ADBE_CrossReferences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ADBE_FontUsage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ADBE_ImageColorManagement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ADBE_ImageResolution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ADBE_PageCount . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ADBE_PageSizeOrientation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ADBE_ScaledGraphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ADBE_ScaledType . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ADBE_SmallText . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ADBE_SpotColorSetup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ADBE_StrokeRequirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ADBE_TextOverrides . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ADBE_TransparencyBlending . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
11
153
154
154
155
156
156
156
156
157
157
157
158
158
158
158
158
159
159
164
165
165
168
168
169
169
12
172
172
172
173
173
174
174
174
174
174
174
175
175
175
175
176
176
目次
8
13
177
177
178
179
181
190
190
191
195
196
196
198
199
201
202
205
14
208
208
209
209
1
はじめに
小幅な更新
9
10
2.
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();
その他の JavaScript 開発の選択肢
11
2
更新
説明
enableRedraw
scriptsFolder
scriptsList
12
プロパティ
userInteractionLevel
version
13
14
Version 8.0 Scripts
CS6
Version 7.0 Scripts
Version 6.0 Scripts
CS4
Version 5.0 Scripts
CS3
Version 2.0 Scripts
CS2
15
の 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);
}
16
doScript からの戻り値
次のスクリプトは、doScript で実行されるスクリプトから値を返す方法を示しています。この例では、文字
列として実行される JavaScript を使用していますが、スクリプトファイルも同様に使用できます。また、この
例で返す値は 1 つですが、配列を使用すると複数の値を返すことができます(完全なスクリプトについては、
DoScriptReturnValues スクリプトを参照してください)。
//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 {
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);
り、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.
18
ます。
名前を持つアイテム(段落スタイル、カラー、レイヤーなど)がその name を使用して参照できるように、
ページアイテムはその label を使用して参照することができます。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;
}
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);
3
変更
20
21
ドキュメントプリセットを使用してドキュメントを作成するには、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();
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();
レートとして保存されます。次のスクリプトにその例を示します(チュートリアルスクリプトの
SaveDocumentAs より)。
//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);
23
トの 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);
}
24
この例のように、裁ち落としの距離がすべて等しい場合は、代わりに documentBleedUniformSize プロパ
ティを使用することもできます。次のスクリプトにその例を示します(チュートリアルスクリプトの
UniformBleed より)。
//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";
}
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];
}
特定のページのマージンを設定するには、そのページの 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"
}
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;
}
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)});
}
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 オブジェク
トのプロパティを設定します。次のスクリプトにその例を示します(チュートリアルスクリプトの
DocumentAndBaselineGrid より)
。
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;
}
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;
}
スクリプト全体で特定の測定単位系を使用する場合は、スクリプトの先頭で測定単位を変更し、スクリプト
の最後で元の測定単位に戻します。次のスクリプトにその例を示します(チュートリアルスクリプトの
ResetMeasurementUnits より)
。
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.");
}
}
30
既存の値をコピーしてプリセットを作成する
既存のドキュメントの設定をサンプルとして使用してドキュメントプリセットを作成するには、ドキュメン
トプリセットで使用したいドキュメント設定プロパティが含まれているドキュメントを開き、その後で次の
スクリプトを実行します(チュートリアルスクリプトの 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;
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";
}
32
マスタースプレッドの設定
基本的なドキュメントページのサイズ、印刷可能領域、裁ち落としを設定したら、ドキュメントのマスター
スプレッドを定義するのが一般的です。次のスクリプトにその例を示します (完全なスクリプトについては、
MasterSpread を参照してください)。
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;
}
}
}
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 の仕様を
参照してください。
InDesign スクリプティングでも、ドキュメントに XMP 情報を追加することができます。ドキュメントのすべ
ての XMP プロパティは、ドキュメントの metadataPreferences オブジェクトに含まれています。ドキュメン
トの標準 XMP データを入力する例を次に示します。
この例では、XMP 情報を拡張する方法も示されています。ドキュメントにメタデータを添付する必要があり、
そのデータが metadata preferences オブジェクトで定義されているカテゴリーに該当しない場合は、独自のメ
。(完全なスクリプトについては、MetadataExample
タデータコンテナを作成できます(この例では 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]");
}
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.
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";
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});
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();
//Body text master text frame.
var myRightFrame = textFrames.add(myDocument.layers.item("BodyText"), undefined,
undefined, {geometricBounds:[marginPreferences.top, marginPreferences.left, myBottomMargin,
myRightMargin], previousTextFrame:myLeftFrame});
}
}
//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);
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;
39
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]]);
2.
スクリプトを使用してページを変形する方法を、次のスクリプトに示します (完全なスクリプトについて
は、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);
}
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;
柔軟性のあるレイアウトの作成
レイアウトルールを使用して作成した 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];
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
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];
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 Page.contentPlace with full parameters
myPage1.contentPlace(myPage.rectangles, //One or more page items to place or load
true,
//Whether to link pageItems in content placer (Optional)
true,
//Whether to link stories in content placer (Optional)
true,
//Whether to map styles in content placer (Optional)
[0, 0, 40, 40],
//The point at which to place (Optional)
myDocument1.activeLayer,
//The layer on which to place (Optional)
true);
//Whether to display the link options dialog (Optional)
45
ページ範囲を使用したプリント
プリントするページの範囲を指定するには、プリントを行う前に、ドキュメントの 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 を設定する方法を、次のス
クリプトに示します (完全なスクリプトについては、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.
//-----------------------------------------------------------------------//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;
46
}
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;
47
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;
}
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;
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);
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();
}
}
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
(
{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
53
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)
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();
}
}
EPub の書き出し
56
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;
EPub の書き出し
//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);
57
4
変更なし
58
59
60
レイヤーインデックスによるレイヤーの参照
ドキュメントのレイヤーコレクションに含まれるレイヤーのインデックスを使用して、レイヤーへの参照を
取得できます。レイヤーのインデックスを使用して、レイヤーに対して繰り返し処理を行う方法を、次のス
クリプトに示します (完全なスクリプトについては、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;
}
}
相対参照の使用
あるレイヤーを基準として、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);
61
範囲内のレイヤーの参照
一連のレイヤーを参照するには、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;
レイヤーの移動
ドキュメント内のレイヤーの重なり順を変更するには、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);
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");
レイヤーガイドの操作
ページアイテムと同じように、特定のレイヤーにガイドを割り当てることができます。レイヤーのガイドは、
表示/非表示を選択でき、さらにロックをかけたり解除したりすることもできます。レイヤーのガイドを操
作する方法を、次のスクリプトに示します (完全なスクリプトについては、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;
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));
}
5
変更なし
65
ページアイテムの種類を判断するには、次の例を使用します。
var myPageItemType = myPageItem.constructor.name;
ページアイテムの種類の取得
汎用的なページアイテムへの参照があるときに、そのページアイテムの種類を確認する場合は、
constructor.name を使用して特定の種類を取得します。
//Given a generic page item "myPageItem"...
var myType = myPageItem.constructor.name;
alert(myType);
66
67
次の DeletePathPoint スクリプトは、パスからパスポイントを削除する方法を示しています。
//Given a polygon "myPolygon", remove the
//last path point in the first path.
myPolygon.paths.item(0).pathPoints.item(-1).remove();
ページアイテムのグループ化
InDesign のユーザーインターフェイスでページアイテムのグループを作成するには、ページアイテムを選択
し、次に、オブジェクトメニューから「グループ」を選択します(または、対応するキーボードショート
カットを押します)。InDesign スクリプティングでは、次の Group スクリプトのように、グループ化するペー
ジアイテムを格納しているオブジェクト(通常はページやスプレッド)に指示をして、ページアイテムをグ
ループ化します。
//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);
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));
69
convertShape メソッドには、反転パスの開閉方法も用意されています。次のスクリプトにその例を示します
(完全なスクリプトについては、OpenPath を参照してください)。
//Given a rectangle "myRectangle"...
myRectangle.convertShape(ConvertShapeOptions.convertToOpenPath);
70
ドキュメント内でのレイヤーの重なり順は、レイヤー自体の 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));
2.
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);
変形マトリックスの操作
一度作成した変形マトリックスは変更できませんが、様々な方法で変形マトリックスを操作して、既存の変
形マトリックスに基づいて新規の変換マトリックスを作成できます。次のスクリプトに、変形マトリックス
に複数の変形を適用し、元のマトリックスを置き換える方法の例を示します (完全なスクリプトについて
は、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 を参照してください)。マトリックスの効
果は、反転させた変形マトリックスを使用して元に戻すことができます。
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);
73
CoordinateSpaces.parentCoordinates は、オブジェクトの親の座標スペースです。親に適用した変形は、
CoordinateSpaces.innerCoordinates は、オブジェクト自体が作成された座標スペースです。
スプレッドの中心にあり、ユーザーインターフェイスに表示される定規には対応していません。
次のスクリプトは、座標スペース間の相違を示します (完全なスクリプトについては、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();
74
アンカー、境界線の種類 - オブジェクトの境界線(BoundingBoxLimits.geometricPathBounds)また
はオブジェクトの表示可能な境界線(BoundingBoxLimits.outerStrokeBounds)との相対位置で指定
されたアンカーポイント。
[AnchorPoint.bottomLeftAnchor, BoundingBoxLimits.outerStrokeBounds]
アンカー、境界線の種類、座標系 - 特定の座標スペースにおいて、オブジェクトの境界線
(BoundingBoxLimits.geometricPathBounds)またはオブジェクトの表示可能な境界線
(BoundingBoxLimits.outerStrokeBounds)として指定されたアンカーポイント。
[AnchorPoint.bottomLeftAnchor, BoundingBoxLimits.outerStrokeBounds,
CoordinateSpaces.pasteboardCoordinates]
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.
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;
}
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();
77
reframe メソッドの使用方法を、次のスクリプトに示します。完全なスクリプトについては、Reframe を参照
してください。
//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]]);
78
アーティクルの順序変更
アーティクルの順序を変更するには、次のスクリプトに示すように、移動対象のアーティクルに対して参照
アーティクルと参照アーティクルを基準にした相対位置を指示します(完全なスクリプトについては、
ReorderArticles を参照してください)。
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);
アーティクルへの新規メンバーの追加
アーティクルに新規メンバーを追加するには、次のスクリプトを使用します(完全なスクリプトについては、
AddRemoveArticleMember を参照してください)。
var myDocument = app.documents.item(0);
//Retrieve the articles for the document.
var articles = myDocument.articles;
//Create new
var article1
var article2
var article3
articles
= articles.add("Article1", true);
= articles.add("Article2", true);
= 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);
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));
6
更新
テキストフレームの作成
次のスクリプトでは、テキストフレームを作成し、フレームの境界(サイズ)を設定し、フレームにテキス
トを入力しています(完全なスクリプトについては、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."});
80
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;
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);
テキストの置換
次のスクリプトでは、適当なオブジェクトの内容を変更することで、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."
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";
テキストの配置とテキスト読み込み環境設定の指定
テキスト文字列の入力だけでなく、ワードプロセッサーやテキストエディターで作成したテキストファイル
を配置することもできます。ドキュメントページにテキストファイルを配置する方法を、次のスクリプトに
示します(完全なスクリプトについては、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.
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 ページの「テキストフレームの作成」または
InsertTextFile というチュートリアルスクリプトを参照してください)。
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;
}
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 読み込み環境設定の指定方法を、次のスクリプトに示します(完全なスクリプトについては、
ExcelImportPreferences を参照してください)。
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 = "";
}
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 関数は省略していま
す。この関数については、80 ページの「テキストフレームの作成」または ExportTextRange というチュート
リアルスクリプトを参照してください)。
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;
}
87
このスクリプトで参照されている 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);
}
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;
88
}
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;
}
89
90
story
spread, page, layer
insertion points
characters
text containers
text frame
words
insertion points
lines
characters
paragraphs
words
text columns
lines
text style ranges
paragraphs
texts
text columns
notes
text style ranges
texts
notes
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)
テキスト選択の操作
テキスト関連のスクリプトでよく行われる操作の 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
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.");
}
}
スクリプトにその例を示します(完全なスクリプトについては、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.
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 関数は省略しています。この関数については、
80 ページの「テキストフレームの作成」または 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();
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;
}
}
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 スクリプティングで、テキストフレームのリンクをたどっていく際に重要になるのが、テキストフ
レームの nextTextFrame プロパティと previousTextFrame プロパティです。これらのプロパティは、InDesign
テキストフレームの入力ポートと出力ポートに相当します。次のスクリプトにその例を示します(完全なス
クリプトについては、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;
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;
96
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;
}
}
}
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;
}
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";
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;
100
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
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;
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;
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;
104
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]});
}
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.
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"));
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);
//find/change text preferences
app.findTextPreferences = NothingEnum.nothing;
app.changeTextPreferences = NothingEnum.nothing;
//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.
109
テキストの検索と変更
指定したテキスト文字列を検索する方法を、次のスクリプトに示します。このスクリプトではドキュメント
全体を検索していますが、ストーリー、テキストフレーム、段落、テキスト列などのテキストオブジェクト
を検索することもできます。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;
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;
111
このスクリプトで参照されている 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;
}
表の操作
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;
表の操作
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;
}
}
表の操作
114
表にヘッダー行とフッター行を作成する方法を、次のスクリプトに示します(完全なスクリプトについては、
HeaderAndFooterRows を参照してください)。
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;
表にフォーマットを適用する方法を、次のスクリプトに示します(完全なスクリプトについては、
TableFormatting を参照してください)。
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;
表に反復行フォーマットを追加する方法を、次のスクリプトに示します(完全なスクリプトについては、
AlternatingRows を参照してください)。
//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;
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;
}
}
}
自動修正の使用
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.";
}
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;
}
テキスト環境設定の指定
一般的なテキスト環境設定の指定方法を、次のスクリプトに示します(完全なスクリプトについては、
TextPreferences を参照してください)。
//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;
}
117
118
親ストーリーのリンクストーリーの作成を Spread オブジェクトに対して指示する場合、placeAndLink メソッ
ドでは Page オブジェクトの placeAndLink メソッドと同じパラメーターを取ります。次のスクリプトにその例
を示します(完全なスクリプトについては、CreateLinkedStories を参照してください)。
var newSpread = myDocument.spreads.add();
newSpread.placeAndLink(myTextFrame.parentStory, [originY, originX], myDocument.activeLayer,
false);
119
7
変更なし
dialog column
static text
border panel
checkbox control
radiobutton group
radiobutton control
measurement editbox
dropdown
120
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
121
最初の 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();
122
「Hello World」へのユーザーインターフェイスの追加
次の例は、
『Adobe InDesign スクリプティングチュートリアル』で作成した 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;
var myPointSize = myPointSizeField.editValue;
//Remove the dialog box from memory.
myDialog.destroy();
myMakeDocument(myString, myPointSize);
}
else{
myDialog.destroy();
}
このスクリプトで参照されている 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;
}
}
完全なスクリプトについては、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"});
}
}
123
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;
}
}
}
}
ScriptUI の使用
125
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
myString = myString & "myProgressPanel.hide();" & vbcr
myInDesign.DoScript myString, idScriptLanguage.idJavascript
myDocument.Close idSaveOptions.idNo
End If
Next
8
イベント
変更なし
126
127
説明
Bubbles
Cancelable
CurrentTarget
を参照してください。
DefaultPrevented
EventPhase
EventType
PropagationStopped
Target
TimeStamp
event が発生した日時。
全なスクリプトについては、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);
128
このスクリプトを実行してファイルを配置すると、ドキュメントの名前を示す警告と、アプリケーションの
名前を示す警告が順に表示されます。このスクリプトで追加したイベントリスナーを削除するには、
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 );
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;
}
}
ドキュメントに追加したい場合に便利です。ドキュメントの最初のマスタースプレッドの印刷可能領域にあ
るテキストフレームにこのような情報を追加する方法を、次のチュートリアルスクリプトに示します(完全
なスクリプトについては、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;
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 を参照してください)。
#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();
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){
var myFontCheck = true;
for(var myCounter = 0; myCounter < myDocument.fonts.length;
myCounter ++){
if(myDocument.fonts.item(myCounter).status != FontStatus.installed){
myFontCheck = false;
}
}
return myFontCheck;
}
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;
}
}
このスクリプトで参照されているイベントハンドラーを次に示します。
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);
}
}
}
132
このスクリプトで参照されているイベントハンドラーを次に示します。
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?");
}
}
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);
}
}
}
#targetengine "session"
main();
function main()
{
var length = app.idleTasks.length;
if (length == 0)
{
alert("There is no idle task.");
}
else
{
for (var i = length-1; i >=0; i--)
{
app.idleTasks.item(i).remove();
}
alert(length + " idle task(s) removed.");
}
}
既存のアイドルタスクを表示するには、次のスクリプトを実行します(完全なスクリプトについては、
ListIdleTasks を参照してください)。
#targetengine "session"
main();
function main()
{
var length = app.idleTasks.length;
if (length == 0)
{
alert("There is no idle task.");
}
else
{
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);
}
}
134
9
メニュー
変更なし
menuElements — メニューに表示されるすべての menuItems、menuSeparators、submenus
ナー
135
136
application
menuActions
menuAction
area
checked
enabled
eventListeners
eventListener
id
eventListener
...
index
label
name
events
event
parent
event
title
...
scriptMenuActions
scriptMenuAction
same as menuAction
すべてのメニューアクションのリスト(テキストファイル)を作成するには、次のスクリプトを実行します
(チュートリアルスクリプトの 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();
}
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;
}
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);
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){}
イベント
説明
menu
beforeDisplay
menuAction
afterInvoke
beforeInvoke
afterInvoke
beforeInvoke
beforeDisplay
scriptMenuAction
beforeDisplay
scriptMenuAction の操作
140
scriptMenuAction の操作
scriptMenuAction を使用すると、menuAction を新しく作成して、onInvoke event の発生時に指定のスクリプ
プトについては、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 のリストを作成することができます。次のスクリプトにその例を示します
(チュートリアルスクリプトの 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();
}
141
スクリプトが実行されます。これは、スクリプトでメニュー名を変更したり、有効/チェックのステータス
を設定したりする場合に特に役立ちます。
次のサンプルスクリプトでは、beforeDisplay event に対する eventListener を追加して、現在の選択を確認
するようにしています。何も選択されていない場合は、eventListener のスクリプトによってメニュー項目が
無効化されます。アイテムが選択されている場合は、メニュー項目が有効化されます。メニュー項目を選択
すると、選択されている最初のアイテムの種類が表示されます (完全なスクリプトについては、
BeforeDisplay を参照してください)。
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;
}
});
//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;
142
//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
}
143
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});
144
}
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();
}
}
}
}
}
145
10
変更なし
146
147
profiles = app.preflightProfiles;
profileCount = profiles.length;|
str = "Preflight profiles: ";
(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);
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)
{
return "String";
}
else
{
return type;
}
}
148
149
また、スクリプトでプロファイルを読み込むこともできます。次のスクリプトでは、Test という名前のプロ
ファイルを読み込みます。完全なスクリプトについては、ImportPreflightProfile を参照してください。
var myProfile = app.loadPreflightProfile(File("/c/Test.idpp"));
if (myProfile == null)
{
alert("The profile did not load successfully");
}
else
{
alert("Preflight profile " + myProfile.name + " is loaded.")
}
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 + ".")
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();
}
}
プロファイルに、名前による指定方式でルールを追加します。
名前による指定方式でルールが追加されます。 ルール名について詳しくは、153 ページの「使用可能な
ルール」を参照してください。次のスクリプトでは、プロファイルに 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.
//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.
//set the rule to return an error
myRule.flag = PreflightRuleFlag.returnAsError;
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();
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)
}
ADBE_BlankPages
154 ページの「ADBE_BlankPages」
ADBE_BleedSlug
154 ページの「ADBE_BleedSlug」
ADBE_BleedTrimHazard
155 ページの「ADBE_BleedTrimHazard」
ADBE_CMYPlates
なし
ADBE_Colorspace
156 ページの「ADBE_Colorspace」
ADBE_ConditionIndicators
なし
ADBE_CrossReferences
156 ページの「ADBE_CrossReferences」
ADBE_FontUsage
ADBE_ImageColorManagement
156 ページの「ADBE_ImageColorManagement」
ADBE_ImageResolution
157 ページの「ADBE_ImageResolution」
ADBE_InteractiveContent
なし
ルール名
ADBE_LayerVisibility
なし
ADBE_MissingFonts
なし
ADBE_MissingGlyph
なし
ADBE_MissingModifiedGraphics
なし
ADBE_OPI
なし
ADBE_Overprint
なし
ADBE_OversetText
なし
ADBE_PageCount
ADBE_PageSizeOrientation
157 ページの「ADBE_PageSizeOrientation」
ADBE_Registration
なし
ADBE_ScaledGraphics
158 ページの「ADBE_ScaledGraphics」
ADBE_ScaledType
158 ページの「ADBE_ScaledType」
ADBE_SmallText
ADBE_SpellCheck
なし
ADBE_SpotColorSetup
158 ページの「ADBE_SpotColorSetup」
ADBE_StrokeRequirements
158 ページの「ADBE_StrokeRequirements」
ADBE_TextOverrides
159 ページの「ADBE_TextOverrides」
ADBE_TransparencyBlending
159 ページの「ADBE_TransparencyBlending」
ADBE_TransparencyUsage
なし
ADBE_WhiteOverprint
なし
ADBE_BlankPages
データ型
名前
Boolean
ignore_master
true
Boolean
ignore_nonprinting
true
データ型
名前
Real
bleed_b
9
Real
bleed_b_aux
9
Integer
bleed_comparison_type
3
ADBE_BleedSlug
154
データ型
名前
Boolean
bleed_enabled
true
Real
bleed_l
9
Real
bleed_l_aux
9
Real
bleed_r
9
Real
bleed_r_aux
9
Real
bleed_t
9
Real
bleed_t_aux
9
Real
slug_b
18
Real
slug_b_aux
18
Integer
slug_comparison_type
3
Boolean
slug_enabled
false
Real
slug_l
18
Real
slug_l_aux
18
Real
slug_r
18
Real
slug_r_aux
18
Real
slug_t
18
Real
slug_t_aux
18
Real
tolerance
0.01
データ型
名前
Boolean
binding_enabled
false
Real
binding_width
1
Real
live_b
18
Real
live_l
18
Real
live_r
18
Real
live_t
18
Real
tolerance
0.01
ADBE_BleedTrimHazard
155
ADBE_Colorspace
データ型
名前
Boolean
no_cmyk
false
Boolean
no_gray
false
Boolean
no_lab
false
Boolean
no_rgb
false
Boolean
no_spot
false
データ型
名前
Boolean
xrefs_out_of_date
true
Boolean
xrefs_unresolved
true
データ型
名前
Boolean
no_ATC
false
Boolean
no_Bitmap
false
Boolean
no_CID
false
Boolean
no_MultipleMaster
false
Boolean
no_OpenTypeCFF
false
Boolean
no_OpenTypeCID
false
Boolean
no_OpenTypeTT
false
Boolean
no_TrueType
false
Boolean
no_Type1
false
Boolean
no_protected
true
ADBE_CrossReferences
ADBE_FontUsage
ADBE_ImageColorManagement
データ型
名前
Boolean
no_cmyk_profiles
true
Boolean
no_image_overrides
true
Boolean
overrides_exclude_uncal
true
156
ADBE_ImageResolution
データ型
名前
Boolean
bw_max_enabled
false
Real
bw_max_res
2400
Boolean
bw_min_enabled
true
Real
bw_min_res
800
Boolean
color_max_enabled
false
Real
color_max_res
1200
Boolean
color_min_enabled
true
Real
color_min_res
250
Boolean
gray_max_enabled
false
Real
gray_max_res
1200
Boolean
gray_min_enabled
true
Real
gray_min_res
250
Real
tolerance
0.5
データ型
名前
Integer
comparison_type
2
Integer
comparison_value
1
Integer
comparison_value_aux
1
データ型
名前
Real
height
792
Boolean
ignore_orientation
false
Real
tolerance
0.01
Real
width
612
ADBE_PageCount
ADBE_PageSizeOrientation
157
ADBE_ScaledGraphics
データ型
名前
Real
max_scale
100.5
データ型
名前
Boolean
ignore_justification
true
Real
max_scale
100.5
データ型
名前
Real
minSize
4
Boolean
minSize_trap_safe_only
false
データ型
名前
Boolean
lab_spots
true
Boolean
lab_spots_enabled
false
Integer
max_spots
1
Boolean
max_spots_enabled
true
データ型
名前
Real
min_width
0.125
Boolean
min_width_trap_safe_only
false
ADBE_ScaledType
ADBE_SmallText
ADBE_SpotColorSetup
ADBE_StrokeRequirements
158
ADBE_TextOverrides
データ型
名前
Boolean
ignore_color_overrides
false
Boolean
ignore_font_overrides
false
Boolean
ignore_kerning_tracking_overrides
false
Boolean
ignore_language_overrides
false
ADBE_TransparencyBlending
データ型
名前
Integer
space
3
159
11
変更なし
160
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");
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],
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]];
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});
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 を参照してください)。
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.
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 に追加しようとすると、エラーが発生することに注意してください。
ページ上のオブジェクトに適用されるアニメーションの順番を制御する方法を、次のスクリプトに示します
(完全なスクリプトについては、MultipleTimingGroups を参照してください)。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;
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);
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);
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 です。
モーションパスにキーフレームを追加する方法と、アニメーション化するページアイテムに適用される変形
を各キーフレームで変更する方法を、次のスクリプトに示します (完全なスクリプトについては、
TransformAnimation を参照してください)。
//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;
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
変更なし
171
第 12 章 XML
172
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";
第 12 章 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"]];
または、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 要素の名前のことです。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
174
XML 要素の作成
通常、XML 要素は XML ファイルを読み込んで作成しますが、InDesign スクリプティングを使用して XML 要素
を作成することもできます。次のスクリプトにその例を示します(チュートリアルスクリプトの
CreateXMLElement より)。
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 構造内の元の 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
175
XML コメントの作成
XML コメントは、XML データ構造に注釈を作成する場合に使用します。XML コメントを追加する方法を、次
のスクリプトに示します(チュートリアルスクリプトの MakeXMLComment より)。
var myRootXMLElement = myDocument.xmlElements.item(0);
var myXMLElementB = myRootXMLElement.xmlElements.item(1);
myXMLElementB.xmlComments.add("This is an XML comment.");
XML 処理命令を追加する方法を、次のスクリプトに示します(完全なスクリプトについては、
MakeProcessingInstruction を参照してください)。
var myRootXMLElement = myDocument.xmlElements.item(0);
var myXMLProcessingInstruction = myRootXMLElement.xmlInstructions.add("xml-stylesheet
type=¥"text/css¥" ", "href=¥"generic.css¥"");
XML 属性の操作
XML 属性とは、XML 要素に関連付けられている「メタデータ」のことです。XML 要素に 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!");
第 12 章 XML
176
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 ストーリーに格納されます。テキストフレーム内のテキストと同じように、配置されていない
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
177
ページアイテムへの XML の配置
XML 要素をページアイテムに関連付ける別の方法として、placeIntoFrame メソッドを使用する方法がありま
す。このメソッドでは、XML を配置するときにフレームを作成できます。次のスクリプトにその例を示しま
す(完全なスクリプトについては、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
178
XML テキスト要素の内部や周囲へのテキストの挿入
XML データを InDesign レイアウトに配置する際に、空白文字(改行やタブ文字など)や静的テキスト(「名
前」や「住所」などのラベル)を XML 要素のテキストに追加したいことがあります。XML 要素の内部や周囲
にテキストを追加する方法を、次のサンプルスクリプトに示します(完全なスクリプトについては、
InsertTextAsContent を参照してください)。
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 テキスト要素にフォーマットを適用する最も簡単な方法の 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
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 要素を関連付ける方法を、次のスクリプトに示します(完全なスクリプトについては、
MarkingUpGraphics を参照してください)。
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);
第 12 章 XML
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);
180
第 12 章 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
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;
182
13
変更なし
183
概要
184
名前(文字列)
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
}
概要
185
SortByName,
AddStaticText,
LayoutElements,
FormatElements
__processRuleSet(root, ruleSet) — 一連の XML ルールを実行するには、__processRuleSet 関数を呼び
__processChildren(ruleProcessor) — 一致する XML 要素の子要素に対して一致する XML ルールを適用
__skipChildren(ruleProcessor) — 現在の XML 要素の下位要素を XML ルールで処理しないようにプロ
概要
186
Root
1
B
2
9
BA
BB
BC
3
4
5
8
BAA
BAB
BAC
6
7
BACA
BACB
Root
9
B
8
6
BA
7
BB
BC
5
4
BAA
3
BAB
BAC
2
1
BACA
BACB
概要
187
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
}
Root
1
19
B
2
18
14
16
BA
BB
3
13
5
BAA
15
17
7
BAB
4
BC
BAC
6
8
12
10
BACA
BACB
9
11
概要
188
指定の属性が指定の値である要素の検索(/doc/para[@font='Courier'] など)。
指定の属性が指定の値でない要素の検索(/doc/para[@font !='Courier'] など)。
現在の要素(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::* など)。
..、ancestor::、preceding-sibling:: などの、上位の要素や preceding-sibling 軸は使用できません。
述語での比較は行えません(foo[@bar < font or @c > 3] など)。
概要
189
XML 䊦䊷䊦
䊒䊨䉶䉾䉰䊷
䉫䊦䊷䉮䊷䊄
XM
Lr
ule
s
XPath condition
XPath 䈱᧦ઙ
XPath 䈱⹏ଔ
__processRuleSet
XML element
t
XML elemen
apply()
__processChildren
__skipChildren
t
XML elemen
XML ᭴ㅧౝ䈱
ᓳಣℂ
190
サンプルドキュメントのセットアップ
この章の各スクリプトを実行する前に、ドキュメントに 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;
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
}
}
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,
new ProcessPackages,
new ProcessPrice);
with(myDocument){
var elements = xmlElements;
__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.
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
}
193
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
}
}
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.
}
}
クリプトについては、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
}
}
196
XML ルールを使用した XML 要素の複製
第 12 章「XML」で説明したように、XML 要素とレイアウト内の対応する表現との間には、1 対 1 の関係があ
ります。ある XML 要素の内容をレイアウト内で複数表示したい場合は、その要素を複製する必要があります。
XML ルールを使用して要素を複製する方法を、次のスクリプトに示します。完全なスクリプトについては、
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;
}
}
}
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;
}
}
}
198
複数の一致ルールの適用
ある XML ルールの apply 関数で true を返すと、それ以降の XML ルールは XML 要素に適用されなくなります。
apply 関数で false を返すと、他のルールが必要に応じて XML 要素に適用されます。次のスクリプトは、false
を返す XML ルール apply 関数の例を示しています。このスクリプトには、ドキュメント内のすべての XML 要
素に一致する 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;
}
}
}
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;
}
}
}
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
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;
}
}
function myResetFindChangeGrep(){
app.findGrepPreferences = NothingEnum.nothing;
app.changeGrepPreferences = NothingEnum.nothing;
}
}
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.
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;
}
}
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});
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);
203
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);
204
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;
}
}
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 要素内のコンテナ要素にその内容を移動してフォーマットしています。
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);
207
クトをスクリプトで直接操作することもできます。これは、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();
}
myRuleProcessor.endProcessingRuleSet();
myRuleProcessor.remove();
return myXMLElements;
}
catch (myError){
myRuleProcessor.endProcessingRuleSet();
myRuleProcessor.remove();
throw myError;
}
}
}
14
変更なし
トラックされた変更への移動
トラックされた変更の記録がストーリーに含まれている場合、ユーザーはトラックされた変更に順次移動す
ることができます。トラックされた変更に移動する方法を、次のスクリプトに示します(完全なスクリプト
については、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);
}
}
208
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);
}
}
次のスクリプトでは、変更を取り消します(完全なスクリプトについては、RejectChange を参照してくださ
い)
。
var myDocument = app.documents.item(0);
var myStory = myDocument.stories.item(0);
var myChange = myStory.changes.item(0);
myChange.reject() ;
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.
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;
}
211">
Download
Advertisement
Key features
Text and image editing
Color management
Layout tools
Scripting support
Professional-quality output
Cross-platform compatibility
Frequently asked questions
The scripting features in InDesign CS6 are documented in the InDesign CS6 Scripting Guide. This guide provides information on how to write and execute scripts, as well as how to use the scripting objects and methods.
You can create a variety of scripts in InDesign CS6, such as scripts to automate repetitive tasks, create custom menus and tools, and integrate with other applications.
JavaScript is the programming language used for scripting in InDesign CS6.