Working With Documents Js
Working With Documents Js
Working with
Documents
JavaScript Version
The work you do in InDesign revolves around documentscreating them, saving them, and populating them with
page items, colors, styles, and text. Almost every document-related task can be automated using scripting.
This tutorial will show you how to:
Close a document
Save a document
Create guides
Print a document
If you have not already worked through the chapter, Getting Started with InDesign Scripting in the Adobe
InDesign CS Scripting Guide, you might want to do so before continuing with this tutorial. This tutorial assumes
that you have already read that chapter, and know how to create a script.
For more information on InDesign scripting, go to http://www.adobe.com/products/indesign/scripting.html, or
visit the InDesign Scripting User to User forum at http://www.adobeforums.com.
To use the scripts in this document, copy the scripts out of the PDF and paste them into a text editor (such as
Notepad in Windows or BBEdit on the Mac OS). Save the scripts as plain text with the le extension .js and place
the saved le (or an alias/shortcut to it) in the Scripts folder inside the Presets folder in your InDesign folder (create
the Scripts folder if it does not already exist). Once you've done this, you can run the script by double-clicking the
script name in the Scripts palette (choose Window>Scripting>Scripts to display the Scripts palette).
Due to the layout of this document and the nature of the copy/paste process, some long lines of code may include
unwanted line breaks when you paste them into your text editor. In some cases, these line breaks will cause the
script to fail. To x the script, you'll need to remove the unnecessary line breaks. In this document, all noncomment lines (lines that start with // are comments) will end with either {, }, or ;. The following is an
example of a long line:
guides.add(myDocument.layers.item("GuideLayer"), {orientation:HorizontalOrVertical.
horizontal, location:marginPreferences.top, fitToPage:false});
When you paste this line into a text editor, remove the line breakthe line should end with the semicolon (;). If
you don't remove the line break, the script will generate an error.
The document.add method can take two optional parameters, as shown in the following script:
//MakeDocumentWithParameters.js
//An InDesign CS JavaScript
//Shows how to use the parameters of the document.add method.
//The first parameter (showingWindow) controls the visibility of the document. Hidden documents
//are not minimized, and will not appear until you add a new window to the document.
//The second parameter (documentPreset) specifies the document preset to use.
//The following line assumes that you have a document preset named "Flyer" on your system.
var myDocument = app.documents.add(true, app.documentPresets.item("Flyer"));
Opening a Document
The following example script shows how to open an existing document using scripting.
//OpenDocument.js
//An InDesign CS JavaScript
//Opens an existing document. You'll have to fill in your own file path.
app.open(File("/c/myTestDocument.indd"));
You can choose to hide the document after you open it by setting the showingWindow parameter of the open
method to false (the default value is true). You might want to do this to improve performance of a script. To show a
hidden document, create a new window, as shown in the following script:
//OpenDocumentInBackground.js
//An InDesign CS JavaScript
//Opens an existing document in the background, then shows the document.
//You'll have to fill in your own file path.
var myDocument = app.open(File("/c/myTestDocument.indd"), false);
//At this point, you can do things with the document without showing the document window.
//In some cases, scripts will run faster when the document window is not visible.
//When you want to show the hidden document, create a new window.
var myLayoutWindow = myDocument.windows.add();
Closing a Document
The close method closes a document:
//CloseDocument.js
//Closes the active document.
app.activeDocument.close();
//Note that you could also use:
//app.documents.item(0).close();
Saving a Document
In InDesigns user interface, you save a le using the Save command, and you save a le to another le name using
the Save As command. In InDesign scripting, the save method takes care of both operations.
//SaveDocument.js
//If the active document has been changed since it was last saved, save it.
if(app.activeDocument.modified == true){
app.activeDocument.save();
}
The save method has two optional parameters: the rst (To) species the le to save to; the second (Stationery) can
be set to true to save the document as a template.
//SaveDocumentAs.js
//If the active document has not been saved (ever), save it.
if(app.activeDocument.saved == false){
//If you do not provide a file name, InDesign will display the Save dialog box.
app.activeDocument.save(new File("/c/myTestDocument.indd"));
}
Note that the application object also has a document preferences object, and that you can set the application
defaults for page height, page width, and other properties by changing the properties of this object.
If all of the bleed distances are equal, as in the above example, you can use the documentBleedUniformSize
property:
//UniformBleed.js
//An InDesign CS JavaScript
//Create a new document.
myDocument = app.documents.add();
//The bleed properties belong to the documentPreferences object.
with(myDocument.documentPreferences){
//Bleed
documentBleedUniformSize = true;
documentBleedBottomOffset = "3p";
}
If all of the slug distances are equal, you can use the documentSlugUniformSize property:
//UniformSlug.js
//An InDesign CS JavaScript
//Create a new document.
myDocument = app.documents.add();
//The slug properties belong to the documentPreferences object.
with(myDocument.documentPreferences){
//Slug:
documentSlugUniformSize = true;
slugBottomOffset = "3p";
}
In addition to setting the bleed and slug widths/heights, you can also control the color used to draw the guides
dening the bleed and slug. This property is not found in the documentPreferences object--instead, its in the
pasteboardPreferences object.
//BleedSlugGuideColors.js
//Set the colors used to display the bleed and slug guides.
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];
}
If youre creating very small pages (for individual newspaper advertisements, for example), you may have found
that InDesign will not allow you to create a page that is smaller than the sum of the relevant margins (i.e., the width
of the page must be greater than the sum of the left and right default page margins, the height of the page must be
greater than the sum of the top and bottom margins). In the user interface, you can easily x this by entering new
values in the document default page margin elds in the New Document dialog box as you create the document.
From scripting, however, the solution is not as clearthe document is created using the application default margin
preferences. These margins are applied to the pages of the document, including master pages. Setting the document
margin preferences aects only new pages, and has no eect on existing pages. If you try to set the page height and
page width to values smaller than the sum of the corresponding margins on any of the existing pages, InDesign will
not change the page size.
There are really two solutions to this problem. The rst is to set the margins of the existing pages before you try to
change the page size, as shown in the following example:
//PageMargins.js
//Creates a new document and sets up page margins.
var myDocument = app.documents.add();
//The following assumes that your default document contains a single page.
myDocument.pages.item(0).marginPreferences.top = 0;
myDocument.pages.item(0).marginPreferences.left = 0;
myDocument.pages.item(0).marginPreferences.bottom = 0;
myDocument.pages.item(0).marginPreferences.right = 0;
//The following assumes that your default master spread contains two pages.
myDocument.masterSpreads.item(0).pages.item(0).marginPreferences.top = 0;
myDocument.masterSpreads.item(0).pages.item(0).marginPreferences.left = 0;
myDocument.masterSpreads.item(0).pages.item(0).marginPreferences.bottom = 0;
myDocument.masterSpreads.item(0).pages.item(0).marginPreferences.right = 0;
myDocument.masterSpreads.item(0).pages.item(1).marginPreferences.top = 0;
myDocument.masterSpreads.item(0).pages.item(1).marginPreferences.left = 0;
myDocument.masterSpreads.item(0).pages.item(1).marginPreferences.bottom = 0;
myDocument.masterSpreads.item(0).pages.item(1).marginPreferences.right = 0;
Alternatively, you can change the application default margin preferences before you create the document, as shown
in the following example:
//ApplicationPageMargins.js
//Sets the application default page margins. All new documents will be created
//using these settings; existing documents will be unaffected.
with (app.marginPreferences){
//Save the current application default margin preferences.
var myY1 = top;
var myX1 = left;
var myY2 = bottom;
var myX2 = right;
//Set the application default margin preferences.
top = 0;
left = 0;
bottom = 0;
right = 0;
}
//Create a new example document to demonstrate the change.
var myDocument = app.documents.add();
myDocument.documentPreferences.pageHeight = "2cm";
myDocument.documentPreferences.pageWidth = "2cm";
//Reset the application default margin preferences to their former state.
with (app.marginPreferences){
top = myY1;
left = myX1 ;
bottom = myY2;
right = myX2;
}
Pasteboard
The pasteboard is an area that surrounds InDesign pages. It can be used for temporary storage of page items. You
can change the size of the pasteboard and its color using scripting. The pasteboardColor property controls the
color of the pasteboard in Normal mode; the previewBackgroundColor property sets the color of the pasteboard in
Preview mode.
//PasteboardPreferences.js
//Create a new document and change the size of the pasteboard.
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 pasteboard color to any of the predefined UIColor constants...
pasteboardColor = UIColors.white;
previewBackgroundColor = UIColors.gray;
//...or you can specify an array of RGB values (with values from 0 to 255)
//pasteboardColor = [0, 0, 0];
//previewBackgroundColor = [192, 192, 192];
}
Guides
InDesigns guides give you an easy way to position objects on the pages of your document. Heres an example use of
guides.
//Guides.js
marginPreferences.right)});
marginPreferences.bottom)});
Horizontal guides can be limited to a given page, or can extend across all of the pages in a spread. In InDesign
scripting, you can control this using the tToPage property. (This property is ignored by vertical guides.
//SpreadAndPageGuides.js
//Demonstrate the difference between spread guides and page guides.
var myDocument = app.documents.add();
myDocument.documentPreferences.facingPages = true;
myDocument.documentPreferences.pagesPerDocument = 3;
with(myDocument.spreads.item(1)){
//Note the difference between these two guides on pages 2 and 3.
guides.add(undefined, {orientation:HorizontalOrVertical.horizontal, location:"6p", fitToPage:true});
guides.add(undefined, {orientation:HorizontalOrVertical.horizontal, location:"9p", fitToPage:false});
}
You can use scripting to change the layer, color, and visibility of guides, just as you can from the user interface.
//GuideOptions.js
//Shows how to set guide options.
var myGuide;
var myDocument = app.documents.add();
//Create a layer named "guide layer".
var myLayer = myDocument.layers.add({name:"guide layer"});
//Add a series of guides to page 1.
with(myDocument.pages.item(0)){
//Create a guide on the layer we created above.
myGuide = guides.add(myLayer, {orientation:HorizontalOrVertical.horizontal, location:"12p"});
//Another way to make a guide on a specific layer.
myGuide = guides.add(undefined, {itemLayer:myLayer, orientation:HorizontalOrVertical.horizontal,
location:"14p"});
//Make a locked guide.
myGuide = guides.add(myLayer,{locked:true, orientation:HorizontalOrVertical.horizontal, location:"16p"});
//Set the view threshold of a guide.
myGuide = guides.add(myLayer,{viewThreshold:100, orientation:HorizontalOrVertical.horizontal,
location:"18p"});
//Set the guide color of a guide using a UIColors constant.
myGuide = guides.add(myLayer,{guideColor:UIColors.gray, orientation:HorizontalOrVertical.horizontal,
location:"20p"});
//Set the guide color of a guide using an RGB array.
myGuide = guides.add(myLayer,{guideColor:[192, 192, 192], orientation:HorizontalOrVertical.horizontal,
location:"22p"});
}
You can also create guides using the createGuides method of spreads and master spreads.
//CreateGuides.js
//Add a series of guides using the createGuides method.
var myDocument = app.documents.add();
with (myDocument.spreads.item(0)){
//Parameters (all optional): row count, column count, row gutter, column gutter,
//guide color, fit margins, remove existing, layer.
//Note that the createGuides method does not take an RGB array for the guide color parameter.
createGuides(4, 4, "1p", "1p", UIColors.gray, true, true, myDocument.layers.item(0));
}
10
11
Measurement Units
In the example scripts weve presented, youll see that weve used measurement strings (strings that force
InDesign to use a specic measurement unit, 8.5i, for example, for 8.5 inches). We do this because we dont know
what default measurement system you might be using when you run the script.
To specify the measurement system used in a script, you need to use the documents viewPreferences object.
//ViewPreferences.js
//Changes the measurement units used by the active document.
//Assumes you have a document open.
var myDocument = app.activeDocument;
with(myDocument.viewPreferences){
//Measurement unit choices are:
//* MeasurementUnits.picas
//* MeasurementUnits.points
//* MeasurementUnits.inches
//* MeasurementUnits.inchesDecimal
//* MeasurementUnits.millimeters
//* MeasurementUnits.centimeters
//* MeasurementUnits.ciceros
//Set horizontal and vertical measurement units to points.
horizontalMeasurementUnits = MeasurementUnits.points;
verticalMeasurementUnits = MeasurementUnits.points;
}
If youre writing a script that needs to work with a specic measurement system, you can change the measurement
units at the beginning of the script and then restore the original measurement units at the end of the script, as
shown in the following example:
//ResetMeasurementUnits.js
//Changes, then resets the active document's measurement units.
//Assumes you have a document open.
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 units to their original state.
with (myDocument.viewPreferences){
try{
horizontalMeasurementUnits = myOldXUnits;
verticalMeasurementUnits = myOldYUnits;
}
catch(myError){
alert("Could not reset custom measurement units.");
}
}
Note that InDesign scripting does not support setting the horizontal or vertical measurement units to a custom
value, as InDesigns user interface does.
12
Document Presets
InDesigns document presets give you a way to store and apply commonly-used document setup information
(page size, page margins, columns, and bleed and slug areas). When you create a new document, you can base the
document on a document preset.
To create a document preset by example, open a document that has the document setup properties you want
dened in the document preset, then run the following script:
//DocumentPresetByExample.js
//Creates a document preset based on the current document settings.
//Assumes you have a document open.
var myDocumentPreset;
if(app.documents.length > 0){
var myDocument = app.activeDocument;
//If the document preset "myDocumentPreset" does not already exist, create it.
myDocumentPreset = app.documentPresets.item("myDocumentPreset");
try {
var myPresetName = myDocumentPreset.name;
}
catch (myError){
myDocumentPreset = app.documentPresets.add({name:"myDocumentPreset"});
}
//Fill in the properties of the document preset with the corresponding
//properties of the active document.
with(myDocumentPreset){
//Note that the following gets the page margins from the margin preferences
//of the document; to get the margin preferences from the active page,
//replace "app.activeDocument" with "app.activeWindow.activePage" in the
//following six lines (assuming the active window is a layout window).
left = app.activeDocument.marginPreferences.left;
right = app.activeDocument.marginPreferences.right;
top = app.activeDocument.marginPreferences.top;
bottom = app.activeDocument.marginPreferences.bottom;
columnCount = app.activeDocument.marginPreferences.columnCount;
columnGutter = app.activeDocument.marginPreferences.columnGutter;
documentBleedBottom = app.activeDocument.documentPreferences.documentBleedBottomOffset;
documentBleedTop = app.activeDocument.documentPreferences.documentBleedTopOffset;
documentBleedLeft = app.activeDocument.documentPreferences.documentBleedInsideOrLeftOffset;
documentBleedRight = app.activeDocument.documentPreferences.documentBleedOutsideOrRightOffset;
facingPages = app.activeDocument.documentPreferences.facingPages;
pageHeight = app.activeDocument.documentPreferences.pageHeight;
pageWidth = app.activeDocument.documentPreferences.pageWidth;
pageOrientation = app.activeDocument.documentPreferences.pageOrientation;
pagesPerDocument = app.activeDocument.documentPreferences.pagesPerDocument;
slugBottomOffset = app.activeDocument.documentPreferences.slugBottomOffset;
slugTopOffset = app.activeDocument.documentPreferences.slugTopOffset;
slugInsideOrLeftOffset = app.activeDocument.documentPreferences.slugInsideOrLeftOffset;
slugRightOrOutsideOffset = app.activeDocument.documentPreferences.slugRightOrOutsideOffset;
}
}
13
The following example script shows how to create a document preset from scratch:
//DocumentPreset.js
//Creates a new document preset.
var myDocumentPreset;
//If the document preset "myDocumentPreset" does not already exist, create it.
myDocumentPreset = app.documentPresets.item("myDocumentPreset");
try {
var myPresetName = myDocumentPreset.name;
}
catch (myError){
myDocumentPreset = app.documentPresets.add({name:"myDocumentPreset"});
}
//Fill in the properties of the document preset.
with(myDocumentPreset){
pageHeight = "9i";
pageWidth = "7i";
left = "4p";
right = "6p";
top = "4p";
bottom = "9p";
columnCount = 1;
documentBleedBottom = "3p";
documentBleedTop = "3p";
documentBleedLeft = "3p";
documentBleedRight = "3p";
facingPages = true;
pageOrientation = PageOrientation.portrait;
pagesPerDocument = 1;
slugBottomOffset = "18p";
slugTopOffset = "3p";
slugInsideOrLeftOffset = "3p";
slugRightOrOutsideOffset = "3p";
}
To create a new document using a document preset, use the document preset parameter of the add method:
//MakeDocumentWithPreset.js
//Creates a new document using a specified document preset.
//Replace "myDocumentPreset" in the following line with the name
//of the document preset you want to use.
var myDocument = app.documents.add(true, app.documentPresets.item("myDocumentPreset"));
14
Master Spreads
After youve set up the basic document page size, slug, and bleed, youll probably want to dene the documents
master pages.
//MasterSpread.js
//Creates a document, then demonstrates setting master spread properties.
//Set up the first master spread in a new document.
myDocument = app.documents.add();
//Set up the document.
with(myDocument.documentPreferences){
pageHeight = "11i";
pageWidth = "8.5i";
facingPages = true;
pageOrientation = PageOrientation.portrait;
}
//Set the document's ruler origin to page origin. This is very important
//--if you don't do this, getting objects to the correct position on the
//page is much more difficult.
myDocument.viewPreferences.rulerOrigin = RulerOrigin.pageOrigin;
with(myDocument.masterSpreads.item(0)){
//Set up the left page (verso).
with(pages.item(0)){
with(marginPreferences){
columnCount = 3;
columnGutter = "1p";
bottom = "6p";
//"left" means inside; "right" means outside.
left = "6p";
right = "4p";
top = "4p";
}
//Add a simple footer with a section number and page number.
with(textFrames.add()){
geometricBounds = ["61p", "4p", "62p", "45p"];
insertionPoints.item(0).contents = SpecialCharacters.sectionMarker;
insertionPoints.item(0).contents = SpecialCharacters.emSpace;
insertionPoints.item(0).contents = SpecialCharacters.autoPageNumber;
paragraphs.item(0).justification = Justification.leftAlign;
}
}
//Set up the right page (recto).
with(pages.item(1)){
with(marginPreferences){
columnCount = 3;
columnGutter = "1p";
bottom = "6p";
//"left" means inside; "right" means outside.
left = "6p";
right = "4p";
top = "4p";
}
//Add a simple footer with a section number and page number.
15
with(textFrames.add()){
geometricBounds = ["61p", "6p", "62p", "47p"];
insertionPoints.item(0).contents = SpecialCharacters.autoPageNumber;
insertionPoints.item(0).contents = SpecialCharacters.emSpace;
insertionPoints.item(0).contents = SpecialCharacters.sectionMarker;
paragraphs.item(0).justification = Justification.rightAlign;
}
To apply a master spread to a document page, use the appliedMaster property of the document page.
//ApplyMaster.js
//Applies a master spread to a page.
//Assumes that the active document has a master page named "B-Master"
//and at least three pages--page 3 is pages.item(2) because JavaScript arrays are zero-based.
app.activeDocument.pages.item(2).appliedMaster = app.activeDocument.masterSpreads.item("BMaster");
You use the same property to apply a master spread to a master spread page.
//ApplyMasterToMaster.js
//Applies a master spread to a master page.
//Assumes that the active document has master spread named "B-Master"
//that is not the same as the first master spread in the document.
app.activeDocument.masterSpreads.item(0).pages.item(0).appliedMaster = app.activeDocument.
masterSpreads.item("B-Master");
16
17
rightIndent = 0;
ruleAbove = false;
if(ruleAbove == true){
ruleAboveColor = app.colors.item("Black");
ruleAboveGapColor = app.swatches.item("None");
ruleAboveGapOverprint = false;
ruleAboveGapTint = 100;
ruleAboveLeftIndent = 0;
ruleAboveLineWeight = .25;
ruleAboveOffset = 14;
ruleAboveOverprint = false;
ruleAboveRightIndent = 0;
ruleAboveTint = 100;
ruleAboveType = app.strokeStyles.item("Solid");
ruleAboveWidth = RuleWidth.columnWidth;
}
ruleBelow = false;
if(ruleBelow == true){
ruleBelowColor = app.colors.item("Black");
ruleBelowGapColor = app.swatches.item("None");
ruleBelowGapOverprint = false;
ruleBelowGapTint = 100;
ruleBelowLeftIndent = 0;
ruleBelowLineWeight = .25;
ruleBelowOffset = 0;
ruleBelowOverprint = false;
ruleBelowRightIndent = 0;
ruleBelowTint = 100;
ruleBelowType = app.strokeStyles.item("Solid");
ruleBelowWidth = RuleWidth.columnWidth;
}
singleWordJustification = SingleWordJustification.leftAlign;
skew = 0;
spaceAfter = 0;
spaceBefore = 0;
startParagraph = StartParagraph.anywhere;
strikeThru = false;
if(strikeThru == true){
strikeThroughColor = app.colors.item("Black");
strikeThroughGapColor = app.swatches.item("None");
strikeThroughGapOverprint = false;
strikeThroughGapTint = 100;
strikeThroughOffset = 3;
strikeThroughOverprint = false;
strikeThroughTint = 100;
strikeThroughType = app.strokeStyles.item("Solid");
strikeThroughWeight = .25;
}
strokeColor = app.swatches.item("None");
strokeTint = 100;
strokeWeight = 0;
tracking = 0;
underline = false;
if(underline == true){
18
underlineColor = app.colors.item("Black");
underlineGapColor = app.swatches.item("None");
underlineGapOverprint = false;
underlineGapTint = 100;
underlineOffset = 3;
underlineOverprint = false;
underlineTint = 100;
underlineType = app.strokeStyles.item("Solid");
underlineWeight = .25;
}
verticalScale = 100;
to:
with(app.activeDocument.textDefaults){
19
XMP Metadata
Metadata is information that describes the content, origin, or other attributes of a le. In InDesign, you enter,
edit, and view metadata using the File Info dialog box (File>File Info). This metadata includes the creation and
modication dates of the document, the author of the document, the copyright status of the document, and
other information. All of this information is stored using XMP (Adobe Extensible Metadata Platform)an open
standard for embedding metadata in a document.
You can add XMP information to a document using InDesign scripting. All of the XMP properties for a document
can be found in the documents metadataPreferences object. Heres an example that lls in the standard XMP data
for a document. To learn more about XMP, see the XMP specication at http://partners.adobe.com/asn/developer/
pdf/MetadataFramework.pdf.
//MetadataExample.js
//Adds metadata to an example document.
var myDocument = app.documents.add();
with (myDocument.metadataPreferences){
author = "Olav Martin Kvern";
copyrightInfoURL = "http://www.adobe.com";
copyrightNotice = "This document is copyrighted.";
copyrightStatus = CopyrightStatus.yes;
description = "Example of xmp metadata scripting in InDesign CS";
documentTitle = "XMP Example";
jobName = "XMP_Example_2004";
keywords = ["animal", "mineral", "vegetable"];
//The metadata preferences object also includes the read-only
//creator, format, creationDate, modificationDate, and serverURL properties that are
//automatically entered and maintained by InDesign.
//Create a custom XMP container, "email"
createContainerItem("http://ns.adobe.com/xap/1.0/", "email");
setProperty("http://ns.adobe.com/xap/1.0/", "email/*[1]", "[email protected]");
}
As you can see from the example above, XMP information is extensibleif you need to attach metadata to a
document that does not fall into one of the categories provided by the metadata preferences object, you can create
your own metadata container (email, in this example).
20
21
22
catch (myError){
myDocument.layers.add({name:"BodyText"});
}
with(myDocument.viewPreferences){
rulerOrigin = RulerOrigin.pageOrigin;
horizontalMeasurementUnits = MeasurementUnits.points;
verticalMeasurementUnits = MeasurementUnits.points;
}
//Document baseline grid and document grid
with(myDocument.gridPreferences){
baselineStart = 56;
baselineDivision = 14;
baselineShown = false;
horizontalGridlineDivision = 14;
horizontalGridSubdivision = 5;
verticalGridlineDivision = 14;
verticalGridSubdivision = 5;
documentGridShown = false;
}
//Document XMP information.
with (myDocument.metadataPreferences){
author = "Olav Martin Kvern";
copyrightInfoURL = "http://www.adobe.com";
copyrightNotice = "This document is not copyrighted.";
copyrightStatus = CopyrightStatus.no;
description = "Example 7 x 9 book layout";
documentTitle = "Example";
jobName = "7 x 9 book layout template";
keywords = ["7 x 9", "book", "template"];
createContainerItem("http://ns.adobe.com/xap/1.0/", "email");
setProperty("http://ns.adobe.com/xap/1.0/", "email/*[1]", "[email protected]");
}
//Set up the master spread.
with(myDocument.masterSpreads.item(0)){
with(pages.item(0)){
//Left and right are reversed for left-hand pages (becoming "inside" and "outside"-//this is also true in the InDesign user interface).
var myBottomMargin = myDocument.documentPreferences.pageHeight - marginPreferences.bottom;
var myRightMargin = myDocument.documentPreferences.pageWidth - marginPreferences.left;
guides.add(myDocument.layers.item("GuideLayer"), {orientation:HorizontalOrVertical.
vertical,location:marginPreferences.right});
guides.add(myDocument.layers.item("GuideLayer"), {orientation:HorizontalOrVertical.vertical,
location:myRightMargin});
guides.add(myDocument.layers.item("GuideLayer"), {orientation:HorizontalOrVertical.
horizontal, location:marginPreferences.top, fitToPage:false});
guides.add(myDocument.layers.item("GuideLayer"), {orientation:HorizontalOrVertical.
horizontal, location:myBottomMargin, fitToPage:false});
guides.add(myDocument.layers.item("GuideLayer"), {orientation:HorizontalOrVertical.
horizontal, location:myBottomMargin + 14, fitToPage:false});
guides.add(myDocument.layers.item("GuideLayer"), {orientation:HorizontalOrVertical.
horizontal, location:myBottomMargin + 28, fitToPage:false});
var myLeftFooter = textFrames.add(myDocument.layers.item("Footer"), undefined, undefined,
{geometricBounds:[myBottomMargin+14, marginPreferences.right, myBottomMargin+28, myRightMargin]})
23
myLeftFooter.parentStory.insertionPoints.item(0).contents = SpecialCharacters.sectionMarker;
myLeftFooter.parentStory.insertionPoints.item(0).contents = SpecialCharacters.emSpace;
myLeftFooter.parentStory.insertionPoints.item(0).contents = SpecialCharacters.
autoPageNumber;
myLeftFooter.parentStory.characters.item(0).appliedCharacterStyle = myDocument.
characterStyles.item("page_number");
myLeftFooter.parentStory.paragraphs.item(0).applyStyle(myDocument.paragraphStyles.
item("footer_left", false));
//Slug information.
with(myDocument.metadataPreferences){
var myString = "Author:\t" + author + "\tDescription:\t" + description + "\rCreation
Date:\t" + new Date +
"\tEmail Contact\t" + getProperty("http://ns.adobe.com/xap/1.0/", "email/*[1]");
}
var myLeftSlug = textFrames.add(myDocument.layers.item("Slug"), undefined, undefined, {geom
etricBounds:[myDocument.documentPreferences.pageHeight+36, marginPreferences.right, myDocument.
documentPreferences.pageHeight + 144, myRightMargin], contents:myString});
myLeftSlug.parentStory.tables.add();
//Body text master text frame.
var myLeftFrame = textFrames.add(myDocument.layers.item("BodyText"), undefined,
undefined, {geometricBounds:[marginPreferences.top, marginPreferences.right, myBottomMargin,
myRightMargin]});
}
with(pages.item(1)){
var myBottomMargin = myDocument.documentPreferences.pageHeight - marginPreferences.bottom;
var myRightMargin = myDocument.documentPreferences.pageWidth - marginPreferences.right;
guides.add(myDocument.layers.item("GuideLayer"), {orientation:HorizontalOrVertical.
vertical,location:marginPreferences.left});
guides.add(myDocument.layers.item("GuideLayer"), {orientation:HorizontalOrVertical.vertical,
location:myRightMargin});
var myRightFooter = textFrames.add(myDocument.layers.item("Footer"), undefined, undefined,
{geometricBounds:[myBottomMargin+14, marginPreferences.left, myBottomMargin+28, myRightMargin]})
myRightFooter.parentStory.insertionPoints.item(0).contents = SpecialCharacters.
autoPageNumber;
myRightFooter.parentStory.insertionPoints.item(0).contents = SpecialCharacters.emSpace;
myRightFooter.parentStory.insertionPoints.item(0).contents = SpecialCharacters.
sectionMarker;
myRightFooter.parentStory.characters.item(-1).appliedCharacterStyle = myDocument.
characterStyles.item("page_number");
myRightFooter.parentStory.paragraphs.item(0).applyStyle(myDocument.paragraphStyles.
item("footer_right", false));
//Slug information.
var myRightSlug = textFrames.add(myDocument.layers.item("Slug"), undefined, undefined, {geo
metricBounds:[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";
24
//When you link the master page text frames, one of the frames
//sometimes becomes selected. Deselect it.
app.select(NothingEnum.nothing, undefined);
Printing a Document
The following script shows how to print the active document using the current print preferences.
//PrintDocument.js
//Prints the active document.
app.activeDocument.print();
To specify a page range to print, set the pageRange property of the documents printPreferences object before
printing:
//PrintPageRange.js
//Prints a page range from the active document.
//Assumes that you have a document open, that it contains a page named "22".
//The page range can be either PageRange.allPages or a page range string.
//A page number entered in the page range must correspond to a page
//name in the document (i.e., not the page index). If the page name is
//not found, InDesign will display an error message.
app.activeDocument.printPreferences.pageRange = "22"
app.activeDocument.print(false);
The printPreferences object contains properties corresponding to the options you see in the panels of the Print
dialog box. Here's an example script that shows how to set print preferences.
//PrintPreferences.js
//Sets the print preferences of the active document.
with(app.activeDocument.printPreferences){
//Properties corresponding to the controls in the General panel of the Print dialog box.
//activePrinterPreset is ignored in this example--we'll set our own print preferences.
//printer can be either a string (the name of the printer) or
//Printer.postscriptFile.
printer = "AGFA-SelectSet 5000SF v2013.108";
//If the printer property is the name of a printer, then the ppd property
//is locked (and will return an error if you try to set it).
//ppd = "AGFA-SelectSet5000SF";
//If the printer property is set to Printer.postscript file, the copies
//property is unavailable. Attempting to set it will generate an error.
copies = 1;
//If the printer property is set to Printer.postscript file, or if the
//selected printer does not support collation, then the collating
//property is unavailable. Attempting to set it will generate an error.
//collating = false;
reverseOrder = false;
//pageRange can be either PageRange.allPages or a page range string.
pageRange = PageRange.allPages;
printSpreads = false;
printMasterPages = false;
25
//-------------------------------------------------------------------------------//Properties corresponding to the controls in the Marks and Bleed panel of the Print dialog
box.
//-------------------------------------------------------------------------------//Set the following property to true to print all printer's marks.
//allPrinterMarks = true;
useDocumentBleedToPrint = false;
//If useDocumentBleedToPrint = false then setting any of the bleed properties
//will result in an error.
//Get the bleed amounts from the document's bleed and add a bit.
bleedBottom = app.activeDocument.documentPreferences.documentBleedBottomOffset+3;
bleedTop = app.activeDocument.documentPreferences.documentBleedTopOffset+3;
bleedInside = app.activeDocument.documentPreferences.documentBleedInsideOrLeftOffset+3;
bleedOutside = app.activeDocument.documentPreferences.documentBleedOutsideOrRightOffset+3;
//If any bleed area is greater than zero, then export the bleed marks.
26
27
}
catch(e){}
try{
postScriptLevel = PostScriptLevels.level3;
}
catch(e){}
//-------------------------------------------------------------------------------//Properties corresponding to the Color Management panel of the Print dialog box.
//-------------------------------------------------------------------------------//If the useColorManagement property of app.colorSettings is false,
//attempting to set the following properties will return an error.
try{
sourceSpace = SourceSpaces.useDocument;
intent = RenderingIntent.useColorSettings;
crd = ColorRenderingDictionary.useDocument;
profile = Profile.postscriptCMS;
}
catch(e){}
//-------------------------------------------------------------------------------//Properties corresponding to the controls in the Advanced panel of the Print dialog box.
//-------------------------------------------------------------------------------opiImageReplacement = false;
omitBitmaps = false;
omitEPS = false;
omitPDF = false;
//The following line assumes that you have a flattener preset named "high quality flattener".
try{
flattenerPresetName = "high quality flattener";
}
catch(e){}
ignoreSpreadOverrides = false;
To print a document using a printer preset, include the printer preset in the print method.
//PrintDocumentWithPreset.js
//Prints the active document using the specified printer preset.
//Assumes you have a printer preset named "myPreset" and that a document is open.
app.activeDocument.print(false, app.printerPresets.item("myPreset"));
To create a document preset from the print preferences of a document, use the following script.
//CreatePrinterPreset.js
//Creates a new printer preset.
//If the preset does not already exist, then create it;
//otherwise, fill in the properties of the existing preset.
var myPreset;
myPreset = app.printerPresets.item("myPreset");
try{
myPreset.name;
}
catch(myError){
28
myPreset = app.printerPresets.add({name:"myPreset"});
}
with(app.activeDocument.printPreferences){
//Because many printing properties are dependent on other printing properties,
//we've surrounded each property-setting line with try...catch statements-//these will make it easier for you to experiment with print preset settings.
try{
myPreset.printer = printer;
}
catch(e){}
try{
myPreset.ppd = ppd;
}
catch(e){}
try{
myPreset.copies = copies;
}
catch(e){}
try{
myPreset.collating = collating;
}
catch(e){}
try{
myPreset.reverseOrder = reverseOrder;
}
catch(e){}
try{
myPreset.pageRange = pageRange;
}
catch(e){}
try{
myPreset.printSpreads = printSpreads;
}
catch(e){}
try{
myPreset.printMasterPages = printMasterPages;
}
catch(e){}
try{
myPreset.printFile = printFile;
}
catch(e){}
try{
myPreset.sequence = sequence;
}
catch(e){}
try{
myPreset.printBlankPages = printBlankPages;
}
catch(e){}
try{
myPreset.printGuidesGrids = printGuidesGrids;
}
catch(e){}
29
try{
myPreset.printNonprinting = printNonprinting;
}
catch(e){}
try{
myPreset.paperSize = paperSize;
}
catch(e){}
try{
myPreset.paperHeight = paperHeight;
}
catch(e){}
try{
myPreset.paperWidth = paperWidth;
}
catch(e){}
try{
myPreset.printPageOrientation = printPageOrientation;
}
catch(e){}
try{
myPreset.pagePosition = pagePosition;
}
catch(e){}
try{
myPreset.paperGap = paperGap;
}
catch(e){}
try{
myPreset.paperOffset = paperOffset;
}
catch(e){}
try{
myPreset.paperTransverse = paperTransverse;
}
catch(e){}
try{
myPreset.scaleHeight = scaleHeight;
}
catch(e){}
try{
myPreset.scaleWidth = scaleWidth;
}
catch(e){}
try{
myPreset.scaleMode = scaleMode;
}
catch(e){}
try{
myPreset.scaleProportional = scaleProportional;
}
catch(e){}
try{
30
myPreset.textAsBlack = textAsBlack;
}
catch(e){}
try{
myPreset.thumbnails = thumbnails;
}
catch(e){}
try{
myPreset.thumbnailsPerPage = thumbnailsPerPage;
}
catch(e){}
try{
myPreset.tile = tile;
}
catch(e){}
try{
myPreset.tilingType = tilingType;
}
catch(e){}
try{
myPreset.tilingOverlap = tilingOverlap;
}
catch(e){}
try{
myPreset.allPrinterMarks = allPrinterMarks;
}
catch(e){}
try{
myPreset.useDocumentBleedToPrint = useDocumentBleedToPrint;
}
catch(e){}
try{
myPreset.bleedBottom = bleedBottom;
}
catch(e){}
try{
myPreset.bleedTop = bleedTop;
}
catch(e){}
try{
myPreset.bleedInside = bleedInside;
}
catch(e){}
try{
myPreset.bleedOutside = bleedOutside;
}
catch(e){}
try{
myPreset.bleedMarks = bleedMarks;
}
catch(e){}
try{
myPreset.colorBars = colorBars;
}
31
catch(e){}
try{
myPreset.cropMarks = cropMarks;
}
catch(e){}
try{
myPreset.includeSlugToPrint = includeSlugToPrint;
}
catch(e){}
try{
myPreset.markLineWeight = markLineWeight;
}
catch(e){}
try{
myPreset.markOffset = markOffset;
}
catch(e){}
try{
myPreset.markType = markType;
}
catch(e){}
try{
myPreset.pageInformationMarks = pageInformationMarks;
}
catch(e){}
try{
myPreset.registrationMarks = registrationMarks;
}
catch(e){}
try{
myPreset.negative = negative;
}
catch(e){}
try{
myPreset.colorOutput = colorOutput ;
}
catch(e){}
try{
myPreset.trapping = trapping;
}
catch(e){}
try{
myPreset.screening = screening;
}
catch(e){}
try{
myPreset.flip = flip;
}
catch(e){}
try{
myPreset.printBlack = printBlack;
}
catch(e){}
try{
32
myPreset.printCyan = printCyan;
}
catch(e){}
try{
myPreset.printMagenta = printMagenta;
}
catch(e){}
try{
myPreset.printYellow = printYellow;
}
catch(e){}
try{
myPreset.blackAngle = blackAngle;
}
catch(e){}
try{
myPreset.blackFrequency = blackFrequency;
}
catch(e){}
try{
myPreset.cyanAngle = cyanAngle;
}
catch(e){}
try{
myPreset.cyanFrequency = cyanFrequency;
}
catch(e){}
try{
myPreset.magentaAngle = magentaAngle;
}
catch(e){}
try{
myPreset.magentaFreqency = magentaFreqency;
}
catch(e){}
try{
myPreset.yellowAngle = yellowAngle;
}
catch(e){}
try{
myPreset.yellowFrequency = yellowFrequency;
}
catch(e){}
try{
myPreset.compositeAngle = compositeAngle;
}
catch(e){}
try{
myPreset.compositeFrequency = compositeFrequency;
}
catch(e){}
try{
myPreset.simulateOverprint = simulateOverprint;
}
33
catch(e){}
try{
myPreset.sendImageData = sendImageData;
}
catch(e){}
try{
myPreset.fontDownloading = fontDownloading;
}
catch(e){}
try{
myPreset.downloadPPDFOnts = downloadPPDFOnts;
}
catch(e){}
try{
myPreset.dataFormat = dataFormat;
}
catch(e){}
try{
myPreset.postScriptLevel = postscriptLevel;
}
catch(e){}
try{
myPreset.sourceSpace = sourceSpace;
}
catch(e){}
try{
myPreset.intent = intent;
}
catch(e){}
try{
myPreset.crd = crd;
}
catch(e){}
try{
myPreset.profile = profile;
}
catch(e){}
try{
myPreset.opiImageReplacement = opiImageReplacement;
}
catch(e){}
try{
myPreset.omitBitmaps = omitBitmaps;
}
catch(e){}
try{
myPreset.omitEPS = omitEPS;
}
catch(e){}
try{
myPreset.omitPDF = omitPDF;
}
catch(e){}
try{
34
myPreset.flattenerPresetName = flattenerPresetName ;
}
catch(e){}
try{
myPreset.ignoreSpreadOverrides = ignoreSpreadOverrides;
}
catch(e){}
alert("Done!");
The above example exports the le as a PDF using the current PDF export options. The following examples shows
how to set the PDF export options before exporting.
//ExportEachPageAsPDF.js
//Exports each page of an InDesign CS document as a separate PDF to a selected folder using the
current PDF export settings.
//Display a "choose folder" dialog box.
if(app.documents.length != 0){
var myFolder = Folder.selectDialog ("Choose a Folder");
if(myFolder != null){
myExportPages(myFolder);
}
}
else{
alert("Please open a document and try again.");
}
function myExportPages(myFolder){
var myDocument = app.activeDocument;
var myDocumentName = myDocument.name;
var myDialog = app.dialogs.add();
with(myDialog.dialogColumns.add().dialogRows.add()){
staticTexts.add({staticLabel:"Base name:"});
var myBaseNameField = textEditboxes.add({editContents:myDocumentName, minWidth:160});
}
var myResult = myDialog.show({name:"ExportPages"});
35
if(myResult == true){
//The name of the exported files will be the base name + the value of the counter + ".pdf".
var myBaseName = myBaseNameField.editContents;
//Remove the dialog box from memory.
myDialog.destroy();
for(var myCounter = 0; myCounter < myDocument.pages.length; myCounter++){
app.pdfExportPreferences.pageRange = (myCounter+1) + "";
//Generate a file path from the folder name, the base document name, and the counter
value.
var myFilePath = myFolder + "/" + myBaseName + (myCounter+1) + ".pdf";
var myFile = new File(myFilePath);
app.activeDocument.exportFile(ExportFormat.pdfType, myFile, false);
}
}
else{
myDialog.destroy();
}
}
The next example shows an example set of PDF export preferences (this set is not completeno security features
are changed).
//ExportPDFWithOptions.js
//Sets PDF export options, then exports the active document as PDF.
with(app.pdfExportPreferences){
//Basic PDF output options.
pageRange = PageRange.allPages;
acrobatCompatibility = AcrobatCompatibility.acrobat6;
exportGuidesAndGrids = false;
exportLayers = false;
exportNonPrintingObjects = false;
exportReaderSpreads = false;
generateThumbnails = false;
ignoreSpreadOverrides = false;
includeBookmarks = true;
includeHyperlinks = true;
includeICCProfiles = true;
includeSlugWithPDF = false;
includeStructure = false;
interactiveElements = false;
//Setting subsetFontsBelow to zero disallows font subsetting;
//set subsetFontsBelow to some other value to use font subsetting.
subsetFontsBelow = 0;
//Bitmap compression/sampling/quality options.
colorBitmapCompression = BitmapCompression.zip;
colorBitmapQuality = CompressionQuality.eightBit;
colorBitmapSampling = Sampling.none;
//thresholdToCompressColor is not needed in this example.
//colorBitmapSamplingDPI is not needed when colorBitmapSampling is set to none.
grayscaleBitmapCompression = BitmapCompression.zip;
grayscaleBitmapQuality = CompressionQuality.eightBit;
grayscaleBitmapSampling = Sampling.none;
//thresholdToCompressGray is not needed in this example.
//grayscaleBitmapSamplingDPI is not needed when grayscaleBitmapSampling is set to none.
36
monochromeBitmapCompression = BitmapCompression.zip;
monochromeBitmapSampling = Sampling.none;
//thresholdToCompressMonochrome is not needed in this example.
//monochromeBitmapSamplingDPI is not needed when monochromeBitmapSampling is set to none.
//Other compression options.
compressionType = PDFCompressionType.compressNone;
compressTextAndLineArt = true;
contentToEmbed = embedAll;
cropImagesToFrames = true;
optimizePDF = true;
//Printers marks and prepress options.
//Get the bleed amounts from the document's bleed.
bleedBottom = app.activeDocument.documentPreferences.documentBleedBottomOffset;
bleedTop = app.activeDocument.documentPreferences.documentBleedTopOffset;
bleedInside = app.activeDcoument.documentPreferences.documentBleedInsideOrLeftOffset;
bleedOutside = app.activeDocument.documentPreferences.documentBleedOutsideOrRightOffset;
//If any bleed area is greater than zero, then export the bleed marks.
if(bleedBottom == 0 && bleedTop == 0 && bleedInside == 0 && bleedOutside == 0){
bleedMarks = true;
}
else{
bleedMarks = false;
}
colorBars = true;
//The colorTileSize and grayTileSize properties are only applicable when
//the corresponding bitmap compression properties are set to BitmapCompression.jpeg2000.
//colorTileSize = 256;
//grayTileSize = 256;
cropMarks = true;
omitBitmaps = false;
omitEPS = false;
omitPDF = false;
pageInformationMarks = true;
pageMarksOffset = 12;
pdfColorSpace = PDFColorSpace.unchangedColorSpace;
pdfMarkType = MarkType.default;
printerMarkWeight = pdfMarkWeight.p125pt;
registrationMarks = true;
simulateOverprint = false;
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, "/c/myTestDocument.pdf", false);
37
38
To control the pages exported as EPS, set the pageRange property of the EPS export preferences to a page range
string containing the page or pages you want to export before exporting.
//ExportSelectedPagesAsEPS.js
//Enter the name of the page you want to export in the following line.
//Note that the page name is not necessarily the index of the page in the
//document (e.g., the first page of a document whose page numbering starts
//with page 21 will be "21", not 1).
app.epsExportPreferences.pageRange = "1-3, 6, 9";
var myFile = new File("/d/test/myFile.eps");
app.activeDocument.exportFile(ExportFormat.epsType, myFile, false);</pre>
In addition to the page range, you can control other EPS export options using scripting by setting the properties of
the epsExportPreferences object.
//ExportEachPageAsEPS.js
//An InDesign CS JavaScript.
//Exports each page of an InDesign CS document as a separate EPS to a
//selected folder using the current EPS export settings.
//Display a choose folder dialog box.
if(app.documents.length != 0){
var myFolder = Folder.selectDialog (Choose a Folder);
if(myFolder != null){
myExportPages(myFolder);
}
}
else{
alert(Please open a document and try again.);
}
function myExportPages(myFolder){
var myFilePath, myPageName, myFile;
var myDocument = app.activeDocument;
var myDocumentName = myDocument.name;
var myDialog = app.dialogs.add({name:ExportPages});
with(myDialog.dialogColumns.add().dialogRows.add()){
staticTexts.add({staticLabel:Base name:});
var myBaseNameField = textEditboxes.add({editContents:myDocumentName, minWidth:160});
}
var myResult = myDialog.show();
if(myResult == true){
39
//The name of the exported files will be the base name + the page name + .eps.
var myBaseName = myBaseNameField.editContents;
//Remove the dialog box from memory.
myDialog.destroy();
//Generate a file path from the folder name, the base document name, page name.
for(var myCounter = 0; myCounter < myDocument.pages.length; myCounter++){
myPageName = myDocument.pages.item(myCounter).name;
app.epsExportPreferences.pageRange = myPageName;
//The name of the exported files will be the base name + the page name + .eps.
//If the page name contains a colon (as it will if the document contains sections),
//then remove the colon.
var myRegExp = new RegExp(:,gi);
myPageName = myPageName.replace(myRegExp, _);
myFilePath = myFolder + / + myBaseName + _ + myPageName + .eps;
myFile = new File(myFilePath);
app.activeDocument.exportFile(ExportFormat.epsType, myFile, false);
}
40
}
else{
myDialog.destroy();
}