Page 2
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.
Apply XML rules, a new scripting feature that makes working with XML in InDesign faster and easier. We assume that you have already read the Adobe InDesign CS5 Scripting Tutorial and know how to create, install, and run scripts. If you need to know how to connect with your scripting environment or view the InDesign scripting object model from your script editor, that information can be found in the Adobe InDesign CS5 Scripting Tutorial.
CS5 extensions. An example of a CS5 extension that ships with the point products is Adobe Kuler. Kuler has a consistent user interface across the different suite applications, but has different logic in each, adapted to the host application.
Running scripts at InDesign start-up. Controlling the ExtendScript engine in which scripts execute. We assume you already read Adobe InDesign CS5 Scripting Tutorial and know how to write, install, and run InDesign scripts in the scripting language of your choice.
2: Scripting Features Getting the Current Script 12 HAPTER Property Description This property controls the alerts and dialogs InDesign presents to the user. userInteractionLevel When you set this property to UserInteractionLevels.neverInteract InDesign does not display any alerts or dialogs. Set it to to enable alerts but UserInteractionLevels.interactWithAlerts disable dialogs.
2: Scripting Features Using the doScript Method 13 HAPTER Compilation — This involves mapping the names in the script to the underlying script ids, which are what the application understands. The mechanics of compilation are language specific. Interpretation — This involves matching the ids to the appropriate request handler within the application.
Page 15
2: Scripting Features Using the doScript Method 15 HAPTER //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);...
Controlling Undo with doScript 16 HAPTER //Create a string to be run as a AppleScript. p1 = "tell application \"Adobe InDesign CS5\"\r"; p2 = "tell script args" +"\r"; p3 = "set value name\"" + nameA +"\" value "; p4 = "\"This is the firest AppleScript script argument value.\"" +"\r";...
Page 17
2: Scripting Features Working with Script Labels 17 HAPTER property can contain any form of text data, such as tab- or comma-delimited text, HTML, or label XML. Because scripts also are text, they can be stored in the property. label Page items can be referred to by their , just like named items (such as paragraph styles, colors, or label...
To run a script when InDesign starts, put the script in the Startup Scripts folder in the Scripts folder (for more information, see “Installing Scripts” in Adobe InDesign CS5 Scripting Tutorial). : Scripts run in the session ExtendScript engine when InDesign starts can create objects and functions that will be available to other scripts for the duration of the session.
Apply different sizes to different pages (multiple pages sizes). Print a document. Export a document as Adobe PDF. Export pages of a document as EPS. We assume that you have already read Adobe InDesign CS5 Scripting Tutorial and know how to create, install, and run a script.
3: Documents Basic Document Operations 20 HAPTER Basic Document Operations Opening, closing, and saving documents are some of the most basic document tasks. This section shows how to do them using scripting. Creating a new document The following script shows how to make a new document using scripting. (For the complete script, see MakeDocument.) var myDocument = app.documents.add();...
3: Documents Basic Document Operations 21 HAPTER Saving a document In the InDesign user interface, you save a file by choosing File > Save, and you save a file to another file name by choosing File > Save As. In InDesign scripting, the method can do either operation, as save shown in the following script fragment (from the SaveDocument tutorial script):...
3: Documents Basic Page Layout 22 HAPTER //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.
3: Documents Basic Page Layout 23 HAPTER Defining bleed and slug areas Within InDesign, a bleed or a slug is an area outside the page margins that can be printed or included in an exported PDF. Typically, these areas are used for objects that extend beyond the page edges (bleed) and job/document information (slug).
3: Documents Basic Page Layout 24 HAPTER 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];...
3: Documents Basic Page Layout 25 HAPTER There are two solutions. The first is to set the margins of the existing pages before you try to change the page size, as shown in the following script fragment (from the PageMarginsForSmallPages tutorial script): var myDocument = app.documents.add();...
3: Documents Basic Page Layout 26 HAPTER 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;...
3: Documents Basic Page Layout 28 HAPTER Snapping to guides and grids All snap settings for a document’s grids and guides are in the properties of the guidePreferences objects. The following script fragment shows how to set guide and grid snap gridPreferences properties.
3: Documents Basic Page Layout 29 HAPTER 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.
Page 30
3: Documents Basic Page Layout 30 HAPTER //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;...
File Info dialog (choose File > File Info). This metadata includes the document’s creation and modification dates, author, copyright status, and other information. All this information is stored using XMP (Adobe Extensible Metadata Platform), an open standard for embedding metadata in a document.
//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]", "someone@adobe.com"); Creating a document template This example creates a new document, defines slug and bleed areas, adds information to the document’s XMP metadata, sets up master pages, adds page footers, and adds job information to a table in the slug area.
Page 34
3: Documents Basic Page Layout 34 HAPTER 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;...
Page 35
= "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]", "okvern@adobe.com"); //Set up the master spread. with(myDocument.masterSpreads.item(0)){ with(pages.item(0)){...
Page 36
//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});...
3: Documents Adjusting Page Sizes and Layout 38 HAPTER The same preferences can be applied to a document object by referring to a document, rather than to the application. (For the complete script for setting document preferences, see DocumentWatermark.) var myDocument = app.documents.item(0); myDocument.watermarkPreferences.watermarkVisibility = true;...
3: Documents Adjusting Page Sizes and Layout 39 HAPTER Resizing and reframing pages You can resize or reframe page items on a page by scripting. With InDesign CS5, you can also apply the resize and reframe operations to pages to change their sizes. NOTE: Your minimum page size is determined by the page’s margins.
3: Documents Adjusting Page Sizes and Layout 40 HAPTER //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.
3: Documents Printing a Document 41 HAPTER Printing a Document The following script prints the active document using the current print preferences. (For the complete script, see PrintDocument.) app.activeDocument.print(); Printing using page ranges To specify a page range to print, set the property of the document’s pageRange print preferences...
Page 42
3: Documents Printing a Document 42 HAPTER 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.
Page 43
3: Documents Printing a Document 43 HAPTER pagePosition = PagePositions.centered; paperGap = 0; paperOffset = 0; paperTransverse = false; scaleHeight = 100; scaleWidth = 100; scaleMode = ScaleModes.scaleWidthHeight; scaleProportional = true; catch(myError){} //If trapping is on, attempting to set the //following properties will produce an error.
3: Documents Exporting a Document as PDF 44 HAPTER //------------------------------------------------------------------------ //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;...
3: Documents Exporting a Document as PDF 45 HAPTER Exporting to PDF The following script exports the current document as PDF, using the current PDF export options. (For the complete script, see ExportPDF.) app.activeDocument.exportFile(ExportFormat.pdfType, File("/c/myTestDocument.pdf"), false); The following script fragment shows how to export to PDF using a PDF export preset. (For the complete script, see ExportPDFWithPreset.) var myPDFExportPreset = app.pdfExportPresets.item("prepress");...
= 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);...
3: Documents Exporting a Document as PDF 47 HAPTER 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);...
3: Documents Exporting Pages as EPS 48 HAPTER Exporting PDF with Interactive Features The following script shows how to export a document with interactive features as a PDF. (For the complete script, see ExportInteractivePDF.) //Given a document "myDocument," add page transitions... for(var myCounter = 0;...
3: Documents Exporting Pages as EPS 49 HAPTER Exporting as EPS with file naming The following script exports each page as an EPS, but it offers more control over file naming than the earlier example. (For the complete script, see ExportEachPageAsEPS.) //Display a "choose folder"...
Working with Layers InDesign’s layers are the key to controlling the stacking order of objects in your layout. You can think of layers as transparent planes stacked on top of each other. You also can use layers as an organizational tool, putting one type of content on a given layer or set of layers.
4: Working with Layers Scripting Layers 51 HAPTER Scripting Layers In InDesign’s user interface, you add, delete, rearrange, duplicate, and merge layers using the Layers panel. You also can change the layer to which a selected page item is assigned by dragging and dropping the layer proxy in the Layers panel.
Page 52
4: Working with Layers Scripting Layers 52 HAPTER Getting the active layer The active layer is the layer on which new objects are created. You can get the active layer using scripting, as shown in the following script fragment. (For the complete script, see ActiveLayer.) //Given a document "myDocument"...
4: Working with Layers Scripting Layers 53 HAPTER Referring to ranges of layers To refer to a series of layers, you can use the method. The following script fragment shows itemByRange how to get a reference to a range of layers, then set a property on all layers in the range. (For the complete script, see HideLayersAbove.) //Given a document "myDocument"...
4: Working with Layers Scripting Layers 54 HAPTER Assigning page items to layers You can assign a page item to a layer by either referring to the layer when you create the page item (the method of all page items can take a layer as a parameter) or setting the property of an itemLayer existing page item.
Page 55
4: Working with Layers Scripting Layers 55 HAPTER Controlling layer printing and visibility You can control the printing and visibility of objects on a layer, as shown in the following script fragment. (For the complete script, see LayerControl.) //Given a document "myDocument" containing layers named "Background," //"Language A,", "Language B,"...
Working with Page Items This chapter covers scripting techniques related to the page items (rectangles, ellipses, graphic lines, polygons, text frames, buttons, and groups) that can appear in an InDesign layout. This document discusses the following: Creating page items. Page item geometry. Working with paths and path points Creating groups.
5: Working with Page Items Creating Page Items 57 HAPTER change the type to a graphic line. The only things that define the type of a rectangle, ellipse, graphic line, or polygon are: The number of paths in the object. Any page item with more than one path is a polygon. The number and location of points on the first path in the object.
Page 58
5: Working with Page Items Creating Page Items 58 HAPTER Changing the zero point location by either dragging the zero point or by changing the ruler origin changes the coordinates on the rulers. Page items are made up of one or more paths, which, in turn, are made up of two or more path points. Paths can be open or closed.
5: Working with Page Items Grouping Page Items 59 HAPTER //Given a polygon "myPolygon", remove the //last path point in the first path. myPolygon.paths.item(0).pathPoints.item(-1).remove(); Grouping Page Items In the InDesign user interface, you create groups of page items by selecting them and then choosing Group from the Object menu (or by pressing the corresponding keyboard shortcut).
5: Working with Page Items Duplicating and Moving Page Items 60 HAPTER Note that the move method truly moves the object—when you move a page item to another document, it is deleted from the original document. To move the object to another while retaining the original, use the duplicate method (see below).
5: Working with Page Items Duplicating and Moving Page Items 61 HAPTER item supports the following methods related to the Pathfinder features: AddPath, ExcludeOverlapPath, IntersectPath, MinusBack, and SubtractPath. All of the Pathfinder methods work the same way--you provide an array of page items to use as the basis for the operation (just as you select a series of page items before choosing the Pathfinder operation in the user interface).
5: Working with Page Items Transforming Page Items 62 HAPTER //Given a rectangle "myRectangle"... myRectangle.convertShape(ConvertShapeOptions.convertToOpenPath); Arranging page items Page items in an InDesign layout can be arranged in front of or behind each other by adjusting their stacking order within a layer, or can be placed on different layers. The following script fragment shows how to bring objects to the front or back of their layer, and how to control the stacking order of objects relative to each other (for the complete script, refer to StackingOrder).
5: Working with Page Items Transforming Page Items 63 HAPTER The following scripting example demonstrates the basic process of transforming a page item. (For the complete script, see TransformExamples.) //Rotate a rectangle "myRectangle" around its center point. var myRotateMatrix = app.transformationMatrices.add({counterclockwiseRotationAngle:27});...
Page 64
5: Working with Page Items Transforming Page Items 64 HAPTER //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); You can get the inverse of a transformation matrix using the method, as shown in the invertMatrix following example.
5: Working with Page Items Transforming Page Items 65 HAPTER //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;...
5: Working with Page Items Transforming Page Items 66 HAPTER 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.");...
5: Working with Page Items Transforming Page Items 67 HAPTER (x, y), bounds type, coordinate space — A point specified relative to the geometric bounds of the object ( ) or the visible bounds of the object BoundingBoxLimits.geometricPathBounds ) in a given coordinate space. In this case, the top-left BoundingBoxLimits.outerStrokeBounds corner of the bounding box is (0, 0);...
5: Working with Page Items Transforming Page Items 68 HAPTER Transforming points You can transform points as well as objects, which means scripts can perform a variety of mathematical operations without having to include the calculations in the script itself. The ChangeCoordinates sample script shows how to draw a series of regular polygons using this approach: //General purpose routine for drawing regular polygons from their center point.
5: Working with Page Items Resize and Reframe 69 HAPTER Transforming again Just as you can apply a transformation or sequence of transformations again in the user interface, you can do so using scripting. There are four methods for applying transformations again: transformAgain transformAgainIndividually transformSequenceAgain...
Page 70
5: Working with Page Items Resize and Reframe 70 HAPTER The following script fragment shows how to use the reframe method. For the complete script, see Reframe. //Given a reference to a rectangle "myRectangle"... var myBounds = myRectangle.geometricBounds; var myX1 = myBounds[1]-72; var myY1 = myBounds[0]-72;...
We assume that you have already read Adobe InDesign CS5 Scripting Tutorial and know how to create, install, and run a script. We also assume that you have some knowledge of working with text in InDesign and understand basic typesetting terms.
6: Text and Type Entering and Importing Text 72 HAPTER 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;...
6: Text and Type Entering and Importing Text 73 HAPTER 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];...
6: Text and Type Placing Text and Setting Text-Import Preferences 74 HAPTER function from this listing; you can find it in “Creating a text frame” on page 71” or in the SpecialCharacters tutorial script.) var myDocument = app.documents.item(0); //Create a text frame on the current page. var myTextFrame = myDocument.pages.item(0).textFrames.add();...
Page 75
6: Text and Type Placing Text and Setting Text-Import Preferences 75 HAPTER The following script shows how to place a text file in an existing text frame. (We omitted the myGetBounds function from this listing; you can find it in “Creating a text frame”...
Page 76
6: Text and Type Placing Text and Setting Text-Import Preferences 76 HAPTER The following script shows how to set Word and RTF import preferences (for the complete script, see WordRTFImportPreferences): with(app.wordRTFImportPreferences){ //convertPageBreaks property can be: //ConvertPageBreaks.columnBreak //ConvertPageBreaks.none //ConvertPageBreaks.pageBreak convertPageBreaks = ConvertPageBreaks.none; //convertTablesTo property can be: //ConvertTablesOptions.unformattedTabbedText //ConvertTablesOptions.unformattedTable...
6: Text and Type Exporting Text and Setting Text-Export Preferences 77 HAPTER Exporting Text and Setting Text-Export Preferences The following script shows how to export text from an InDesign document. Note that you must use text or story objects to export into text file formats; you cannot export all text in a document in one operation. (We omitted the function from this listing;...
Page 78
6: Text and Type Exporting Text and Setting Text-Export Preferences 78 HAPTER 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; You cannot export all text in a document in one step. Instead, you need to either combine the text in the document into a single story and then export that story, or combine the text files by reading and writing files via scripting.
Page 79
6: Text and Type Exporting Text and Setting Text-Export Preferences 79 HAPTER //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";...
Page 80
6: Text and Type Exporting Text and Setting Text-Export Preferences 80 HAPTER 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.
6: Text and Type Understanding Text Objects 81 HAPTER "</td>"; myTextFile.writeln(myString); myTextFile.writeln("</tr>"); myTextFile.writeln("</table>"); //Close the text file. myTextFile.close(); Here is the function referred to in the above script: myFindTag function myFindTag (myStyleName, myStyleToTagMapping){ var myTag = ""; var myDone = false; var myCounter = 0;...
Page 82
6: Text and Type Understanding Text Objects 82 HAPTER document story spread, page, layer insertion points text containers characters 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 There are many ways to get a reference to a given text object.
6: Text and Type Understanding Text Objects 83 HAPTER For a text frame, the of the text frame usually is the page or spread containing the text frame. If the parent text frame is inside a group or was pasted inside another page item, the of the text frame is the parent containing page item.
Page 84
6: Text and Type Understanding Text Objects 84 HAPTER 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.befor e, myTextFrameC.parentStory.paragraphs.item(0).words.item(1)) //Move WordB after the word in TextFrameB.
6: Text and Type Understanding Text Objects 85 HAPTER 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)});...
6: Text and Type Working with Text Frames 86 HAPTER 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();...
6: Text and Type Working with Text Frames 87 HAPTER 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.
Page 88
6: Text and Type Working with Text Frames 88 HAPTER 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); Here is the myBreakFrames function referred to in the preceding script. function myBreakFrames(myObjectList){ myObjectList.sort(myReverseSortByTextFrameIndex);...
6: Text and Type Working with Text Frames 89 HAPTER Splitting all frames in a story The following script fragment shows how to split all frames in a story into separate, independent stories, each containing one unlinked text frame (for the complete script, see SplitStory): if(app.documents.length != 0){ if(app.selection.length != 0){ //Get the first item in the selection.
6: Text and Type Formatting Text 90 HAPTER 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;...
= myString; : Font names typically are of the form , where is the name familyName<tab>fontStyle familyName of the font family, is a tab character, and is the name of the font style. For example: <tab> fontStyle "Adobe Caslon Pro<tab>Semibold Italic"...
= app.fonts.item(myFontName); You also can apply a font by specifying the font family name and font style, as shown in the following script fragment: myText.appliedFont = app.fonts.item("Adobe Caslon Pro"); myText.fontStyle = "Semibold Italic"; Changing text properties Text objects in InDesign have literally dozens of properties corresponding to their formatting attributes.
6: Text and Type Formatting Text 97 HAPTER Changing text color You can apply colors to the fill and stroke of text characters, as shown in the following script fragment (from the TextColors tutorial script): var myColorA, myColorB, myName; //Access the active document and page. var myDocument = app.activeDocument;...
Page 98
6: Text and Type Formatting Text 98 HAPTER the keys to text formatting productivity and should be a central part of any script that applies text formatting. The following example script fragment shows how to create and apply paragraph and character styles (for the complete script, see CreateStyles): var myDocument = app.documents.item(0);...
6: Text and Type Formatting Text 99 HAPTER Why use the method instead of setting the property of applyParagraphStyle appliedParagraphStyle the text object? The method gives the ability to override existing formatting; applyParagraphStyle setting the property to a style retains local formatting. Why check for the existence of a style when creating a new document? It always is possible that the style exists as an application default style.
6: Text and Type Finding and Changing Text 100 HAPTER Finding and Changing Text The find/change feature is one of the most powerful InDesign tools for working with text. It is fully supported by scripting, and scripts can use find/change to go far beyond what can be done using the InDesign user interface.
6: Text and Type Finding and Changing Text 101 HAPTER Finding and changing text The following script fragment shows how to find a specified string of text. While the following script fragment searches the entire document, you also can search stories, text frames, paragraphs, text columns, or any other text object.
6: Text and Type Finding and Changing Text 102 HAPTER 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;...
Page 103
6: Text and Type Finding and Changing Text 103 HAPTER <heading1>This is a heading. <body_text>This is body text. We can create a script that uses grep find in conjunction with text find/change operations to apply formatting to the text and remove the mark-up tags, as shown in the following script fragment (from the ReadPMTags tutorial script): var myDocument = app.documents.item;...
6: Text and Type Working with Tables 104 HAPTER 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;...
Page 105
6: Text and Type Working with Tables 105 HAPTER 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...
Page 106
6: Text and Type Working with Tables 106 HAPTER 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;...
Page 107
6: Text and Type Working with Tables 107 HAPTER The following script fragment shows how to add alternating row formatting to a table (for the complete script, see AlternatingRows): //Given a table "myTable," apply alternating fills to the table. myTable.alternatingFills = AlternatingFillsTypes.alternatingRows; myTable.startRowFillColor = myDocument.swatches.item("DGC1_446a");...
6: Text and Type Path Text 108 HAPTER Path Text You can add path text to any rectangle, oval, polygon, graphic line, or text frame. The following script fragment shows how to add path text to a page item (for the complete script, see PathText): //Given a document "myDocument"...
6: Text and Type Span Columns 109 HAPTER Span Columns A paragraph layout can span multiple columns or split into subcolumns with the Span Columns attribute or Split Column attribute applied. The following script fragment shows how to set the Span Columns and Split Column style for a paragraph (for the complete script, see SpanColumns): var myDocument = app.activeDocument;...
Page 110
6: Text and Type Setting Text Preferences 110 HAPTER 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;...
ScriptUI component. This chapter includes some ScriptUI scripting tutorials; for more information, see Adobe CS5 JavaScript Tools Guide. We assume you already read Adobe InDesign CS5 Scripting Tutorial and know how to create and run a script. Dialog Overview An InDesign dialog box is an object like any other InDesign scripting object. The dialog box can contain several different types of elements (known collectively as “widgets”), as shown in the following figure.
7: User Interfaces Your First InDesign Dialog 112 HAPTER Dialog box element InDesign name Text-edit fields Text editbox control Numeric-entry fields Real editbox, integer editbox, measurement editbox, percent editbox, angle editbox Pop-up menus Drop-down control Control that combines a text-edit field with a Combo-box control pop-up menu Check box...
Adding a User Interface to “Hello World” In this example, we add a simple user interface to the Hello World tutorial script presented in Adobe InDesign CS5 Scripting Tutorial. The options in the dialog box provide a way for you to specify the sample text and change the point size of the text: var myDialog = app.dialogs.add({name:"Simple User Interface Example...
Page 114
7: User Interfaces Creating a More Complex User Interface 114 HAPTER For the complete script, see 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:"});...
Page 115
7: User Interfaces Creating a More Complex User Interface 115 HAPTER ({staticLabel:"Left", checkedState:true}); var myCenterRadioButton = radiobuttonControls.add ({staticLabel:"Center"}); var myRightRadioButton = radiobuttonControls.add({staticLabel:"Right"}); //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.
= myVerticalJustification; Working with ScriptUI JavaScripts can make create and define user-interface elements using an Adobe scripting component named ScriptUI. ScriptUI gives scripters a way to create floating palettes, progress bars, and interactive dialog boxes that are far more complex than InDesign’s built-in object.
Page 117
7: User Interfaces Working with ScriptUI 117 HAPTER The following script fragment shows how to call the progress bar created in the above script using a separate JavaScript (for the complete script, see 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.
We assume that you have already read Adobe InDesign CS5 Scripting Tutorial and know how to create, install, and run a script. For a discussion of events related to menus, see Chapter 9, “Menus.”...
8: Events Working with Event Listeners 119 HAPTER triggering any qualifying registered to objects above the in the scripting eventListeners target object model hierarchy. The following table provides more detail on the properties of an and the ways in which they relate event to event propagation through the scripting object model.
Page 120
InDesign session, add the script to the startup scripts folder. (For more on installing scripts, see "Installing Scripts" in Adobe InDesign CS5 Scripting Tutorial.) When you add an eventListener script to a document, it is not saved with the document or exported to IDML.
8: Events Sample Selection Event Listeners 123 HAPTER #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);...
8: Events Sample onIdle Event Listener 124 HAPTER The following script fragment shows how to get and display the type of an object when the selection changes. For the complete script, see AfterSelectionChanged. var myDocument = app.documents.add(); myDocument.addEventListener("afterSelectionChanged", myDisplaySelectionType); The event handler referred to in the preceding script fragment looks like this: function myDisplaySelectionType(myEvent){ if(app.documents.length != 0){ if(app.documents.item(0).selection.length != 0){...
Page 125
8: Events Sample onIdle Event Listener 125 HAPTER can be used to automatically execute a script when InDesign/InCopy is idle. Its event target is IdleTask and its event object is IdleEvent property of the idle task is the amount of time that elapses before InDesign calls the task again. sleep It should be obvious that you need to set the sleep time to a value high enough that it does not interfere with your work, though this value will vary depending on what tasks the script performs.
Page 126
8: Events Sample onIdle Event Listener 126 HAPTER #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); To remove all idle tasks, run the following script (for the complete script, see RemoveAllIdleTasks): #targetengine "session"...
Page 127
8: Events Sample onIdle Event Listener 127 HAPTER #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);...
We assume you already read Adobe InDesign CS5 Scripting Tutorial and know how to create, install, and run a script. Understanding the Menu Model The InDesign menu-scripting model is made up of a series of objects that correspond to the menus you see in the application’s user interface, including menus associated with panels as well as those displayed...
Page 129
9: Menus Understanding the Menu Model 129 HAPTER application menuActions menuAction area checked enabled eventListeners eventListener eventListener index label name events event event parent title scriptMenuActions scriptMenuAction same as menuAction To create a list (as a text file) of all menu actions, run the following script fragment (from the GetMenuActions tutorial script): var myMenuActionNames = app.menuActions.everyItem().name;...
9: Menus Understanding the Menu Model 130 HAPTER 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");...
9: Menus Working with scriptMenuActions 133 HAPTER the wording of menu item, or performs other tasks related to the menu. This mechanism is used internally to change the menu listing of available fonts, recent documents, or open windows. Working with scriptMenuActions You can use to create a new whose behavior is implemented through the...
9: Menus A More Complex Menu-scripting Example 134 HAPTER 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.
Page 135
9: Menus A More Complex Menu-scripting Example 135 HAPTER graphic, and to avoid adding multiple menu choices to the context menu. The then eventListener checks the selection to see if it contains a graphic; if so, it creates a new scriptMenuItem //The locale-independent name (aka "key string") for the //Layout context menu is "$ID/RtMouseLayout".
Page 136
9: Menus A More Complex Menu-scripting Example 136 HAPTER 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; //Does the selection contain any graphics? for(var myCounter = 0;...
Page 137
9: Menus A More Complex Menu-scripting Example 137 HAPTER 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 catch(myError){ myLabel = "No author available."; break; var myFrame = myGraphic.parent;...
Page 138
9: Menus A More Complex Menu-scripting Example 138 HAPTER ({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}); with(dialogColumns.add()){ var myLabelStyleDropdown = dropdowns.add ({stringList:myStyleNames, selectedIndex:0}); //Layer with(dialogRows.add()){ with(dialogColumns.add()){...
Page 139
9: Menus A More Complex Menu-scripting Example 139 HAPTER myAddLabel(myGraphic, myLabelType, myLabelHeight, myLabelOffset, myLabelStyle, myLayerName); app.documents.item(0).viewPreferences. horizontalMeasurementUnits = myOldXUnits; app.documents.item(0).viewPreferences. verticalMeasurementUnits = myOldYUnits; else{ myDialog.destroy();...
(8.5" x 11"). We briefly highlight how it is done in the user interface, then show how to achieve the same results through scripting. We assume you already read Adobe InDesign CS5 Scripting Tutorial and know how to create, install, and run a script.
10: Working with Preflight Exploring Preflight Profiles 141 HAPTER Listing preflight rules This script fragment shows how to list all preflight rules in a profile. For the complete script, see ListPreflightRules. // Assume the [Basic] profile exists var myProfile = app.preflightProfiles.item(0); var myRules = myProfile.preflightProfileRules;...
10: Working with Preflight Creating a Preflight Profile 143 HAPTER You also can load a profile with scripting. The following script fragment imports a profile called Test. For the complete script, see ImportPreflightProfile. var myProfile = app.loadPreflightProfile(File("/c/Test.idpp")); if (myProfile == null) alert("The profile did not load successfully");...
10: Working with Preflight Adding Rules 144 HAPTER //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";...
10: Working with Preflight Processing a Profile 145 HAPTER //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);...
10: Working with Preflight Custom Rules 146 HAPTER If you would rather produce a text file, simply name your output file with a extension. .txt Alternately, you may prefer to iterate the errors yourself. The following demonstrates how to access the errors array.
Page 147
10: Working with Preflight Available Rules 147 HAPTER Rule name Rule properties “ADBE_BlankPages” on page 148 ADBE_BlankPages “ADBE_BleedSlug” on page 148 ADBE_BleedSlug “ADBE_BleedTrimHazard” on page 149 ADBE_BleedTrimHazard ADBE_CMYPlates “ADBE_Colorspace” on page 149 ADBE_Colorspace ADBE_ConditionIndicators “ADBE_CrossReferences” on page 149yes ADBE_CrossReferences “ADBE_FontUsage” on page 150 ADBE_FontUsage “ADBE_ImageColorManagement”...
10: Working with Preflight Available Rules 148 HAPTER Rule name Rule properties ADBE_TransparencyUsage ADBE_WhiteOverprint ADBE_BlankPages Data Type Name Default value Boolean true ignore_master Boolean true ignore_nonprinting ADBE_BleedSlug Data Type Name Default value Real bleed_b Real bleed_b_aux Integer bleed_comparison_type Boolean true bleed_enabled Real bleed_l...
10: Working with Preflight Available Rules 149 HAPTER Data Type Name Default value Real slug_t_aux Real 0.01 tolerance ADBE_BleedTrimHazard Data Type Name Default value Boolean false binding_enabled Real binding_width Real live_b Real live_l Real live_r Real live_t Real 0.01 tolerance ADBE_Colorspace Data Type Name...
10: Working with Preflight Available Rules 151 HAPTER Data Type Name Default value Real 1200 gray_max_res Boolean true gray_min_enabled Real gray_min_res Real tolerance ADBE_PageCount Data Type Name Default value Integer comparison_type Integer comparison_value Integer comparison_value_aux ADBE_PageSizeOrientation Data Type Name Default value Real height Boolean...
10: Working with Preflight Available Rules 152 HAPTER ADBE_SmallText Data Type Name Default value Real minSize Boolean false minSize_trap_safe_only ADBE_SpotColorSetup Data Type Name Default value Boolean true lab_spots Boolean false lab_spots_enabled Integer max_spots Boolean true max_spots_enabled ADBE_StrokeRequirements Data Type Name Default value Real 0.125...
Creating Dynamic Documents InDesign can create documents for web and online use, also known as Rich Interactive Documents (RID). Dynamic documents contain sounds, animations, hyperlinks, and other interactive content. InDesign documents can be exported to SWF, XFL, or PDF. For SWF and XFL files, documents can include animations, buttons, multistate objects, movies, and sound clips.
11: Creating Dynamic Documents Creating Buttons 154 HAPTER Creating Buttons Buttons are often used for navigation in dynamic documents. Buttons contain three states, known as “Normal, ” “Rollover, ” and “Click, ” which, in turn, can contain page items such as rectangles, ovals, text frames, or images.
Page 155
11: Creating Dynamic Documents Creating Buttons 155 HAPTER //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.
11: Creating Dynamic Documents Creating Multistate Objects 156 HAPTER 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], fillColor:myDocument.colors.item("Gray")});...
Page 157
11: Creating Dynamic Documents Creating Multistate Objects 157 HAPTER //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";...
11: Creating Dynamic Documents Working with Animation 158 HAPTER 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;...
Page 159
11: Creating Dynamic Documents Working with Animation 159 HAPTER , which define the trigger event (page load, page click, and so on) that start the timingLists animation. , which associate a page item or series of page items with a specific timing and define timingGroups the sequence in which animations are shown.
Page 160
11: Creating Dynamic Documents Working with Animation 160 HAPTER , and having the trigger event requires five mouse timingTarget DynamicTriggerEvents.onPageClick clicks to process all the animations. //Given a document "myDocument" and a page "myPage" and the color "myColorA", //"myColorB", and "myColorC"... //Add a page items to animate.
11: Creating Dynamic Documents Working with Animation 161 HAPTER , by (for the complete DynamicTriggerEvents.onPageLoad DynamicTriggerEvents.onPageClick script, refer to 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;...
11: Creating Dynamic Documents Working with Animation 162 HAPTER //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.
11: Creating Dynamic Documents Adding Page Transitions 164 HAPTER Adding Page Transitions Page transitions are special effects that appear when you change pages in an exported dynamic document. Adding page transitions using scripting is easy, as shown in the following script fragment (for the complete script, refer to PageTransitions).
XML data into page layouts, and these features can be controlled using scripting. We assume you already read Adobe InDesign CS5 Scripting Tutorial and know how to create and run a script. We also assume you have some knowledge of XML, DTDs, and XSLT.
12: XML Scripting XML Elements 166 HAPTER Scripting XML Elements This section shows how to set XML preferences and XML import preferences, import XML, create XML elements, and add XML attributes. The scripts in this section demonstrate techniques for working with the XML content itself;...
12: XML Scripting XML Elements 168 HAPTER Loading XML tags You can import XML tags from an XML file without importing the XML contents of the file. You might want to do this to work out a tag-to-style or style-to-tag mapping before you import the XML data., as shown in the following script fragment (from the LoadXMLTags tutorial script): myDocument.loadXMLTags(File("/c/test.xml"));...
12: XML Scripting XML Elements 169 HAPTER 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"; Removing items from the XML structure To break the association between a page item or text and an XML element, use the method, as untag...
12: XML Scripting XML Elements 170 HAPTER 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!"); In addition to creating attributes directly using scripting, you can convert XML elements to attributes. When you do this, the text contents of the XML element become the value of an XML attribute added to the parent of the XML element.
12: XML Adding XML Elements to a Layout 171 HAPTER //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")); In addition, you can use the property of the object to exportFromSelected...
12: XML Adding XML Elements to a Layout 172 HAPTER var myPage = myDocument.pages.item(0); var myXMLElement = myDocument.xmlElements.item(0); myXMLElement.placeIntoCopy(myPage, [288, 72], myPage.textFrames.item(0), true); To associate an existing page item (or a copy of an existing page item) with an XML element and insert the page item into the XML structure at the location of the element, use the method, placeIntoInlineCopy...
Page 173
12: XML Adding XML Elements to a Layout 173 HAPTER Mapping tags to styles One of the quickest ways to apply formatting to XML text elements is to use , also known XMLImportMaps as tag-to-style mapping. When you do this, you can associate a specific XML tag with a paragraph or character style.
12: XML Adding XML Elements to a Layout 174 HAPTER 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;...
12: XML Adding XML Elements to a Layout 175 HAPTER //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);...
Page 176
12: XML Adding XML Elements to a Layout 176 HAPTER 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);...
Page 177
12: XML Adding XML Elements to a Layout 177 HAPTER 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);...
Restructure data using XML rules. Use the XML-rules processor. We assume you already read Adobe InDesign CS5 Scripting Tutorial and know how to create and run a script. We also assume you have some knowledge of XML and have read Chapter 12, “XML.”...
13: XML Rules Overview 179 HAPTER locate and act on XML elements inside InDesign. Just as an XSLT template uses an XML parser outside InDesign to apply transformations to XML data, InDesign's XML Rules Processor uses XML rules to apply transformations to XML data inside InDesign.
Page 180
XML-rule sets. “Glue” code In addition to the XML-rules processor object built into InDesign’s scripting model, Adobe provides a set of functions intended to make the process of writing XML rules much easier. These functions are defined...
Page 181
13: XML Rules Overview 181 HAPTER Root BACA BACB Iteration with (assuming a rule that matches every XML element in the structure) is __processChildren shown in the following figure: Root BACA BACB Iteration given the following rule set is shown in the figure after the script fragment. The rule set includes two rules that match every element, including one that uses .
Page 182
13: XML Rules Overview 182 HAPTER 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;...
Page 183
13: XML Rules Overview 183 HAPTER Inserting a parent XML element — To add an ancestor XML element to the matched XML element, do so after processing the current XML element. The ancestor XML element you add is not processed by the XML-rules processor during this rule iteration (as it appears “above”...
13: XML Rules Overview 184 HAPTER No path specifications in predicates; for example, foo[bar/c] function. last() function or text comparisons; however, you can use InDesign scripting to examine the text text() content of an XML element matched by a given XML rule. No compound Boolean predicates;...
13: XML Rules XML Rules Examples 185 HAPTER XML rule XML rules script glue code processor XML rule XPath condition XPath XPath condition __processRuleSet evaluation XML element apply() XML structure iteration __processChildren __skipChildren XML Rules Examples Because XML rules rely on XPath statements to find qualifying XML elements, XML rules are closely tied to the structure of the XML in a document.
13: XML Rules XML Rules Examples 186 HAPTER //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;...
Page 187
13: XML Rules XML Rules Examples 187 HAPTER 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");...
Page 188
13: XML Rules XML Rules Examples 188 HAPTER 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"...
Page 189
13: XML Rules XML Rules Examples 189 HAPTER //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.
13: XML Rules XML Rules Examples 190 HAPTER 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);...
13: XML Rules XML Rules Examples 191 HAPTER structure of an XML document are best done using an XSLT file to transform the document before or during XML import into InDesign. The following XML rule script shows how to use the method to accomplish this.
13: XML Rules XML Rules Examples 192 HAPTER #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);...
Page 193
13: XML Rules XML Rules Examples 193 HAPTER 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";...
13: XML Rules XML Rules Examples 194 HAPTER Applying multiple matching rules When the function of an XML rule returns true, the XML-rules processor does not apply any further apply XML rules to the matched XML element. When the function returns false, however, the XML-rules apply processor can apply other rules to the XML element.
13: XML Rules XML Rules Examples 195 HAPTER //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;...
Page 196
13: XML Rules XML Rules Examples 196 HAPTER 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; The following script shows how to use a JavaScript regular expression (RegExp) to find and format XML elements by their content (for the complete script, see FindXMLElementByRegExp): main();...
Page 197
13: XML Rules XML Rules Examples 197 HAPTER 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";...
13: XML Rules XML Rules Examples 198 HAPTER //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;...
13: XML Rules XML Rules Examples 199 HAPTER Applying formatting with XML rules The previous XML-rule examples have shown basic techniques for finding XML elements, rearranging the order of XML elements, and adding text to XML elements. Because XML rules are part of scripts, they can perform almost any action—from applying text formatting to creating entirely new page items, pages, and documents.
Page 200
13: XML Rules XML Rules Examples 200 HAPTER 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);...
Page 201
13: XML Rules XML Rules Examples 201 HAPTER 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;...
13: XML Rules XML Rules Examples 202 HAPTER 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"));...
13: XML Rules Creating Tables using XML Rules 203 HAPTER //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));...
13: XML Rules Scripting the XML-rules Processor Object 204 HAPTER 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; Once all of the specified XML elements have been “wrapped, ”...
Page 205
13: XML Rules Scripting the XML-rules Processor Object 205 HAPTER 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;...
Track Changes Writers can track, show, hide, accept, and reject changes as a document moves through the writing and editing process. All changes are recorded and visualized to make it easier to review a document. This tutorial shows how to script the most common operations involving tracking changes. We assume you already read Chapter 2, “Getting Started”...
Track Changes Tracking Changes 207 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); Accepting and reject tracked changes When changes are made to a story, by you or others, the change-tracking feature enables you to review all changes and decide whether to incorporate them into the story.