Adobe 0046100128056 - InDesign - Mac Manual

Javascript
Table of Contents

Advertisement

ADOBE
®
INDESIGN
®
CS5
ADOBE INDESIGN CS5
SCRIPTING GUIDE: JAVASCRIPT

Advertisement

Table of Contents
loading

Summary of Contents for Adobe 0046100128056 - InDesign - Mac

  • Page 1 ADOBE ® INDESIGN ® ADOBE INDESIGN CS5 SCRIPTING GUIDE: JAVASCRIPT...
  • 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.
  • Page 3: Table Of Contents

    Contents Introduction ............. . 9 How to Use the Scripts in this Document .
  • Page 4 Contents Resizing and reframing pages ............39 Transforming pages .
  • Page 5 Contents Text and Type ............71 Entering and Importing Text .
  • Page 6 Contents Creating a More Complex User Interface ........... . 113 Working with ScriptUI .
  • Page 7 Contents ADBE_ScaledType ..............151 ADBE_SmallText .
  • Page 8 Contents Why use XML rules? ..............179 XML-rules programming model .
  • Page 9: Introduction

    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.
  • Page 10: For More Information

    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.
  • Page 11: Scripting Features

    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.
  • Page 12: Getting The Current Script

    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.
  • Page 13: Targeting

    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 14: Sending Parameters To Doscript

    = "msgbox arguments(1), vbOKOnly, \"First argument: \" & arguments(0)"; app.doScript(myVBScript, ScriptLanguage.visualBasic, myParameters); else{ var myAppleScript = "tell application \"Adobe InDesign CS5\\rdisplay dialog(\"First argument\" & item 1 of arguments & return & \"Second argument: \" & item 2 of arguments & return & end tell"; app.doScript(myAppleScript, ScriptLanguage.applescriptLanguage, myParameters);...
  • 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);...
  • Page 16: Controlling Undo With Doscript

    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...
  • Page 18: Running Scripts At Startup

    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.
  • Page 19: Documents

    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.
  • Page 20: Basic Document Operations

    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();...
  • Page 21: Saving A Document

    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):...
  • Page 22: Basic Page Layout

    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.
  • Page 23: Defining Bleed And Slug Areas

    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).
  • Page 24: Setting Page Margins And Columns

    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];...
  • Page 25: Changing The Appearance Of The Pasteboard

    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();...
  • Page 26: Guides And Grids

    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;...
  • Page 27: Setting Grid Preferences

    3: Documents Basic Page Layout 27 HAPTER 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});...
  • Page 28: Changing Measurement Units And Ruler

    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.
  • Page 29: Defining And Applying Document Presets

    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;...
  • Page 31: Setting Up Master Spreads

    3: Documents Basic Page Layout 31 HAPTER 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";...
  • Page 32: Adding Xmp Metadata

    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.
  • Page 33: Creating A Document Template

    //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});...
  • Page 37: Creating Watermarks

    3: Documents Basic Page Layout 37 HAPTER 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";...
  • Page 38: Adjusting Page Sizes And Layout

    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;...
  • Page 39: Resizing And Reframing Pages

    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.
  • Page 40: Master Page Overlay

    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.
  • Page 41: Printing A Document

    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.
  • Page 44: Printing With Printer Presets

    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;...
  • Page 45: Exporting To Pdf

    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");...
  • Page 46: Exporting A Range Of Pages To Pdf

    = 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);...
  • Page 47: Exporting Individual Pages To Pdf

    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);...
  • Page 48: Exporting Pdf With Interactive Features

    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;...
  • Page 49: Exporting As Eps With File Naming

    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"...
  • Page 50: Working With Layers

    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.
  • Page 51: Scripting 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"...
  • Page 53: Deleting Layers

    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"...
  • Page 54: Assigning Page Items To Layers

    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,"...
  • Page 56: Working With Page Items

    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.
  • Page 57: Page-Item Geometry

    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.
  • Page 59: Grouping Page Items

    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).
  • Page 60: Creating Compound Paths

    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).
  • Page 61: Converting Page-Item Shapes

    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).
  • Page 62: Arranging Page Items

    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).
  • Page 63: Working With Transformation Matrices

    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.
  • Page 65: Coordinate Spaces

    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;...
  • Page 66: Transformation Origin

    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.");...
  • Page 67: Resolving Locations

    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);...
  • Page 68: Transforming Points

    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.
  • Page 69: Transforming Again

    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;...
  • Page 71: Text And Type

    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.
  • Page 72: Adding Text

    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;...
  • Page 73: Replacing Text

    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];...
  • Page 74: Placing Text And Setting Text-Import Preferences

    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...
  • Page 77: Exporting Text And Setting Text-Export Preferences

    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.
  • Page 81: Understanding Text Objects

    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.
  • Page 83: Working With Text Selections

    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.
  • Page 85: Text Objects And Iteration

    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)});...
  • Page 86: Working With Text Frames

    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();...
  • Page 87: Unlinking Text Frames

    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);...
  • Page 89: Splitting All Frames In A Story

    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.
  • Page 90: Formatting Text

    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;...
  • Page 91 = "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;...
  • Page 92 6: Text and Type Formatting Text 92 HAPTER leftIndent = 0; ligatures = true; maximumGlyphScaling = 100; maximumLetterSpacing = 0; maximumWordSpacing = 160; minimumGlyphScaling = 100; minimumLetterSpacing = 0; minimumWordSpacing = 80; noBreak = false; otfContextualAlternate = true; otfDiscretionaryLigature = false; otfFigureStyle = OTFFigureStyle.proportionalOldstyle;...
  • Page 93: Working With Fonts

    = 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"...
  • Page 94: Applying A Font

    = 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.
  • Page 95 6: Text and Type Formatting Text 95 HAPTER 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;...
  • Page 96 6: Text and Type Formatting Text 96 HAPTER 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");...
  • Page 97: Changing Text Color

    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);...
  • Page 99: Deleting A Style

    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.
  • Page 100: Finding And Changing Text

    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.
  • Page 101: Finding And Changing Text

    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.
  • Page 102: Using Grep

    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;...
  • Page 104: Using Glyph Search

    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");...
  • Page 108: Path Text

    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"...
  • Page 109: Span Columns

    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;...
  • Page 111: User Interfaces

    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.
  • Page 112: Your First Indesign Dialog

    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...
  • Page 113: Adding A User Interface To "Hello World

    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.
  • Page 116: Working With Scriptui

    = 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.
  • Page 118: Events

    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.”...
  • Page 119: Working With Event Listeners

    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.
  • Page 121: Sample Afternew Event Listener

    8: Events Sample afterNew Event Listener 121 HAPTER myString += "\rCurrent: " +myEvent.currentTarget + " " + myEvent.currentTarget.name; myString += "\r\rPhase: " + myGetPhaseName(myEvent.eventPhase ); myString += "\rBubbles: " + myEvent.bubbles; myString += "\r\rCancelable: " +myEvent.cancelable; myString += "\rStopped: " +myEvent.propagationStopped; myString += "\rCanceled: "...
  • Page 122: Sample Beforeprint Event Listener

    {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"...
  • Page 123: Sample Selection Event Listeners

    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);...
  • Page 124: Sample Onidle Event Listener

    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);...
  • Page 128: Menus

    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;...
  • Page 130: Localization And Menu Names

    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");...
  • Page 131: Running A Menu Action From A Script

    9: Menus Running a Menu Action from a Script 131 HAPTER 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;...
  • Page 132: Menus And Events

    9: Menus Menus and Events 132 HAPTER 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;...
  • Page 133: Working With Scriptmenuactions

    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...
  • Page 134: A More Complex Menu-Scripting Example

    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();...
  • Page 140: Working With Preflight

    (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.
  • Page 141: Listing Preflight Rules

    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;...
  • Page 142: Importing A Preflight Profile

    10: Working with Preflight Importing a Preflight Profile 142 HAPTER 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;...
  • Page 143: Creating A Preflight Profile

    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");...
  • Page 144: Adding Rules

    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";...
  • Page 145: Processing A Profile

    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);...
  • Page 146: Custom Rules

    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”...
  • Page 148: Adbe_Blankpages

    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...
  • Page 149: Adbe_Bleedtrimhazard

    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...
  • Page 150: Adbe_Fontusage

    10: Working with Preflight Available Rules 150 HAPTER ADBE_FontUsage Data Type Name Default value Boolean false no_ATC Boolean false no_Bitmap Boolean false no_CID Boolean false no_MultipleMaster Boolean false no_OpenTypeCFF Boolean false no_OpenTypeCID Boolean false no_OpenTypeTT Boolean false no_TrueType Boolean false no_Type1 Boolean true...
  • Page 151: Adbe_Pagesizeorientation

    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...
  • Page 152: Adbe_Smalltext

    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...
  • Page 153: Creating Dynamic Documents

    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.
  • Page 154: Creating Buttons

    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.
  • Page 156: Creating Multistate Objects

    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";...
  • Page 158: Working With Animation

    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.
  • Page 161: Animating Transformations

    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;...
  • Page 162: Motion Presets

    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.
  • Page 163: Key Frames

    11: Creating Dynamic Documents Working with Animation 163 HAPTER //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;...
  • Page 164: Adding Page Transitions

    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).
  • Page 165: Xml

    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.
  • Page 166: Scripting Xml Elements

    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;...
  • Page 167: Importing Xml

    12: XML Scripting XML Elements 167 HAPTER 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;...
  • Page 168: Loading Xml Tags

    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"));...
  • Page 169: Removing Items From The Xml Structure

    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...
  • Page 170: Working With Xml Stories

    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.
  • Page 171: Adding Xml Elements To A Layout

    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...
  • Page 172: Marking Up Existing Layouts

    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.
  • Page 174: Applying Styles To Xml Elements

    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;...
  • Page 175: Working With Xml Tables

    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);...
  • Page 178: Xml Rules

    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.”...
  • Page 179: Why Use Xml Rules

    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”...
  • Page 184: Error Handling

    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;...
  • Page 185: Xml Rules Examples

    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.
  • Page 186: Getting Started With Xml Rules

    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.
  • Page 190: Changing The Xml Structure Using Xml Rules

    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);...
  • Page 191: Duplicating Xml Elements With Xml Rules

    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.
  • Page 192: Xml Rules And Xml Attributes

    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";...
  • Page 194: Applying Multiple Matching Rules

    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.
  • Page 195: Finding Xml Elements

    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";...
  • Page 198: Extracting Xml Elements With Xml Rules

    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;...
  • Page 199: Applying Formatting With Xml Rules

    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;...
  • Page 202: Creating Page Items With Xml Rules

    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"));...
  • Page 203: Creating Tables Using Xml Rules

    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));...
  • Page 204: Scripting The Xml-Rules Processor Object

    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;...
  • Page 206: Track Changes

    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”...
  • Page 207: Accepting And Reject Tracked Changes

    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.
  • Page 208: Preferences For Tracking Changes

    Track Changes Preferences for Tracking Changes 208 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;...
  • Page 209 Track Changes Preferences for Tracking Changes 209 //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;...

This manual is also suitable for:

Indesign cs5

Table of Contents