# Adobe InDesign CS6 VBScript Scripting Guide In Design Guide: VB

User Manual: adobe InDesign - CS6 - Scripting Guide: VBScript Free User Guide for Adobe InDesign Software, Manual

Open the PDF directly: View PDF .
Page Count: 231 [warning: Documents this large are best viewed by clicking the View PDF Link!]

SCRIPTING GUIDE: VBSCRIPT
Adobe® InDesign® CS6 Scripting Guide: VBScript
If this guide is distributed with software that includes an end user agreement, this guide, as well as the software
described in it, is furnished under license and may be used or copied only in accordance with the terms of such license.
Except as permitted by any such license, no part of this guide may be reproduced, stored in a retrieval system, or
transmitted, in any form or by any means, electronic, mechanical, recording, or otherwise, without the prior written
permission of Adobe Systems Incorporated. Please note that the content in this guide is protected under copyright law
even if it is not distributed with software that includes an end user license agreement.
The content of this guide is furnished for informational use only, is subject to change without notice, and should not be
construed as a commitment by Adobe Systems Incorporated. Adobe Systems Incorporated assumes no responsibility or
liability for any errors or inaccuracies that may appear in the informational content contained in this guide.
Please remember that existing artwork or images that you may want to include in your project may be protected under
copyright law. The unauthorized incorporation of such material into your new work could be a violation of the rights of
the copyright owner. Please be sure to obtain any permission required from the copyright owner.
Any references to company names in sample templates are for demonstration purposes only and are not intended to
refer to any actual organization.
Adobe, the Adobe logo, Creative Suite, and InDesign are either registered trademarks or trademarks of Adobe Systems
Incorporated in the United States and/or other countries. Microsoft and Windows are either registered trademarks or
trademarks of Microsoft Corporation in the United States and/or other countries. Mac OS is a trademark of Apple
Computer, Incorporated, registered in the United States and other countries. All other trademarks are the property of
their respective owners.
Adobe Systems Incorporated, 345 Park Avenue, San Jose, California 95110, USA. Notice to U.S. Government End Users.
The Software and Documentation are “Commercial Items,” as that term is defined at 48 C.F.R. §2.101, consisting of
“Commercial Computer Software” and “Commercial Computer Software Documentation,” as such terms are used in 48
C.F.R. §12.212 or 48 C.F.R. §227.7202, as applicable. Consistent with 48 C.F.R. §12.212 or 48 C.F.R. §§227.7202-1 through
227.7202-4, as applicable, the Commercial Computer Software and Commercial Computer Software Documentation are
being licensed to U.S. Government end users (a) only as Commercial Items and (b) with only those rights as are granted
to all other end users pursuant to the terms and conditions herein. Unpublished-rights reserved under the copyright
laws of the United States. Adobe Systems Incorporated, 345 Park Avenue, San Jose, CA 95110-2704, USA. For U.S.
Government End Users, Adobe agrees to comply with all applicable equal opportunity laws including, if appropriate, the
provisions of Executive Order 11246, as amended, Section 402 of the Vietnam Era Veterans Readjustment Assistance Act
of 1974 (38 USC 4212), and Section 503 of the Rehabilitation Act of 1973, as amended, and the regulations at 41 CFR
Parts 60-1 through 60-60, 60-250, and 60-741. The affirmative action clause and regulations contained in the preceding
sentence shall be incorporated by reference.
Document Update Status
(for entire document; see each chapter for chapter-specific update status)
CS6 Updated Throughout document, changed CS5 to CS6 and version 7.0 to 8.0.
3
Contents
1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
How to Use the Scripts in this Document . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
About the Structure of the Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
For More Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
2 Scripting Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Script Preferences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Getting the Current Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Script Versioning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Targeting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Compilation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Interpretation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Using the DoScript Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Sending parameters to DoScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Returning values from DoScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Controlling Undo with DoScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Working with Script Labels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Running Scripts at Startup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
3 Documents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
Basic Document Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Creating a new document . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Opening a document . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Saving a document . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Closing a document . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Basic Page Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Defining page size and document length . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Defining bleed and slug areas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Setting page margins and columns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
Changing the appearance of the pasteboard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Guides and grids . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
Changing measurement units and ruler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
Defining and applying document presets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
Setting up master spreads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
Adding XMP metadata . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
Creating a document template . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
Creating watermarks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Adjusting Page Sizes and Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
Selecting pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
Resizing and reframing pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Transforming pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
4
Master page overlay . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Making an Adaptive Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Making a flexible layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Adding guides for a guide-based layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
Setting constraints for an object-based layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Creating alternative layouts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Collecting and Dropping Content . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
Printing a Document . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
Printing using page ranges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
Setting print preferences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
Printing with printer presets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
Exporting a Document as PDF . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
Exporting to PDF . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
Setting PDF export options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
Exporting to grayscale PDF . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
Exporting a range of pages to PDF . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
Exporting individual pages to PDF . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
Exporting PDF with interactive features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
Exporting as a PDF form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
Exporting Pages as EPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
Exporting all pages to EPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
Exporting a range of pages to EPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
Exporting as EPS with file naming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
Exporting to EPub . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
Exporting the current document . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
Setting EPub export options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
4 Working with Layers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
Understanding the Layer Object Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
Scripting Layers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
Creating layers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
Referring to layers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
Deleting layers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
Moving layers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
Duplicating layers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
Merging layers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
Assigning page items to layers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
Setting layer properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
5 Text and Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
Entering and Importing Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
Creating a text frame . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
Adding text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
Stories and text frames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
Replacing text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
Inserting special characters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
Placing Text and Setting Text-Import Preferences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
Exporting Text and Setting Text-Export Preferences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
5
Understanding Text Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
Working with text selections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
Moving and copying text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
Text objects and iteration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
Working with Text Frames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
Linking text frames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
Unlinking text frames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
Removing a frame from a story . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
Splitting all frames in a story . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
Creating an anchored frame . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
Fitting text frames to content . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
Formatting Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
Setting text defaults . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
Working with fonts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
Applying a font . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
Changing text properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
Changing text color . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
Creating and applying styles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
Deleting a style . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
Importing paragraph and character styles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
Finding and Changing Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
About find/change preferences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
Finding and changing text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
Finding and changing text formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
Using grep . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
Using glyph search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
Working with Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
Adding Path Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
Using Autocorrect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
Adding Footnotes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
Spanning Columns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
Setting Text Preferences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
Working with Linked Stories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
Creating linked stories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
Changing linked story options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
Frequently asked questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
6 Working with Page Items . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
Creating Page Items . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
Page-item geometry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
Grouping Page Items . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
Duplicating and Moving Page Items . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
Creating compound paths . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
Using Pathfinder operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
Converting page-item shapes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
Arranging page items . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
Transforming Page Items . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
6
Using the transform method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
Working with transformation matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
Coordinate spaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
Transformation origin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
Resolving locations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
Transforming points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
Transforming again . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
Resize and Reframe . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
Working with Articles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
Retrieving an article list . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
Adding new articles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
Removing an article . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
Reordering articles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
Adding new members to an article . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
Reordering members of an article . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
Removing members from an article . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
7 User Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
Dialog Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
Your First InDesign Dialog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
Adding a User Interface to “Hello World” . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
Creating a More Complex User Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
Working with ScriptUI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
Creating a progress bar with ScriptUI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
8 Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
Understanding the Event Scripting Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
About event properties and event propagation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
Working with Event Listeners . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
Sample afterNew Event Listener . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
Sample beforePrint Event Listener . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
Sample Selection Event Listeners . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
Sample onIdle Event Listener . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
9 Menus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
Understanding the Menu Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
Localization and menu names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
Running a Menu Action from a Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
Adding Menus and Menu Items . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
Menus and Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
Working with scriptMenuActions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
A More Complex Menu-scripting Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
7
10 Working with Preflight . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
Exploring Preflight Profiles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
Listing preflight profiles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
Listing preflight rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
Listing preflight data objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
Importing a Preflight Profile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
Creating a Preflight Profile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
Adding Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
Processing a Profile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
Custom Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
Available Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
ADBE_BlankPages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
ADBE_BleedSlug . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
ADBE_BleedTrimHazard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
ADBE_Colorspace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
ADBE_CrossReferences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
ADBE_FontUsage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
ADBE_ImageColorManagement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
ADBE_ImageResolution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
ADBE_PageCount . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
ADBE_PageSizeOrientation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
ADBE_ScaledGraphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
ADBE_ScaledType . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
ADBE_SmallText . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
ADBE_SpotColorSetup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
ADBE_StrokeRequirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
ADBE_TextOverrides . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
ADBE_TransparencyBlending . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
11 Creating Dynamic Documents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
Importing Movies and Sounds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
Creating Buttons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
Creating Multistate Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
Working with Animation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
Basic animation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
TimingSettings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
Animating transformations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
Motion presets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
Design options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
Key frames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
Adding Page Transitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
12 XML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
The Best Approach to Scripting XML in InDesign . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
Scripting XML Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
8
Setting XML preferences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
Setting XML import preferences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
Importing XML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
Creating an XML tag . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
Loading XML tags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
Saving XML tags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
Creating an XML element . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
Moving an XML element . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
Deleting an XML element . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
Duplicating an XML element . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
Removing items from the XML structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
Creating an XML comment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
Creating an XML processing instruction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
Working with XML attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190
Working with XML stories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190
Exporting XML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191
Adding XML Elements to a Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191
Associating XML elements with page items and text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191
Marking up existing layouts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
Applying styles to XML elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
Working with XML tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
13 XML Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199
Why use XML rules? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
XML-rules programming model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
XML Rules Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206
Setting up a sample document . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206
Getting started with XML rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
Changing the XML structure using XML rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
Duplicating XML elements with XML rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
XML rules and XML attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
Applying multiple matching rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
Finding XML elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216
Extracting XML elements with XML rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
Applying formatting with XML rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
Creating page items with XML rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223
Creating Tables using XML Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
Scripting the XML-rules Processor Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
14 Track Changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
Tracking Changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
Navigating tracked changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
Accepting and reject tracked changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
Information about tracked changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
Preferences for Tracking Changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
9
1Introduction
This document shows how to do the following:
Work with the Adobe® InDesign® scripting environment.
Use advanced scripting features.
Perform basic document tasks like setting up master spreads, printing, and exporting.
Work with page items (rectangles, ellipses, graphic lines, polygons, text frames, and groups).
Work with text and type in an InDesign document, including finding and changing text.
Create dialog boxes and other user-interface items.
Respond to user-interface events.
Work with XML, from creating XML elements and importing XML to adding XML elements to a layout.
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 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 Scripting Tutorial.
How to Use the Scripts in this Document
For the most part, the scripts shown in this document are not complete scripts. They are only fragments of
scripts, and are intended to show only the specific part of a script relevant to the point being discussed in
the text. You can copy the script lines shown in this document and paste them into your script editor, but
you should not expect them to run without further editing. Note, in addition, that scripts copied out of this
document may contain line breaks and other characters (due to the document layout) that will prevent
them from executing properly.
A zip archive of all of the scripts shown in this document is available at the InDesign scripting home page,
expanded the archive, move the folders corresponding to the scripting language(s) of your choice into the
Scripts Panel folder inside the Scripts folder in your InDesign folder. At that point, you can run the scripts
from the Scripts panel inside InDesign.
Chapter Update Status
CS6 Unchanged
CHAPTER 1: Introduction About the Structure of the Scripts 10
About the Structure of the Scripts
The script examples are all written using a common template that includes the functions “main,
“mySetup, “mySnippet, and “myTeardown.We did this to simplify automated testing and
publication—there is no reason for you to construct your scripts this way. Most of the time, the part of the
script you will be interested in will be inside the “mySnippet” function.
For more information on InDesign scripting, you also can visit the InDesign Scripting User to User forum, at
http://www.adobeforums.com. In the forum, script writers can ask questions, post answers, and share their
newest scripts. The forum contains hundreds of sample scripts.
11
2Scripting Features
This chapter covers scripting techniques related to InDesigns scripting environment. Almost every other
object in the InDesign scripting model controls a feature that can change a document or the application
defaults. By contrast, the features in this chapter control how scripts operate.
This document discusses the following:
The ScriptPreferences object and its properties.
Getting a reference to the executing script.
Running scripts in prior versions of the scripting object model.
Using the DoScript method to run scripts.
Working with script labels.
Running scripts at InDesign start-up.
We assume that you have already read Adobe InDesign Scripting Tutorial and know how to write, install, and
run InDesign scripts in the scripting language of your choice.
Script Preferences
The ScriptPreferences object provides objects and properties related to the way InDesign runs scripts.
The following table provides more detail on each property of the ScriptPreferences object:
Chapter Update Status
CS6 Updated “Script Versioning” on page 12 and its three subsections have been updated, corrected, and clarified.
Property Description
EnableRedraw Turns screen redraw on or off while a script is running from the Scripts panel.
ScriptsFolder The path to the scripts folder.
ScriptsList A list of the available scripts. This property is an array of arrays, in the
following form:
[[fileName, filePath], ...]
Where fileName is the name of the script file and filePath is the full path to
the script. You can use this feature to check for the existence of a script in the
installed set of scripts.
CHAPTER 2: Scripting Features Getting the Current Script 12
Getting the Current Script
You can get a reference to the current script using the ActiveScript property of the application object.
You can use this property to help you locate files and folders relative to the script, as shown in the
following example (from the ActiveScript tutorial script):
Set myInDesign = CreateObject("InDesign.Application")
myActiveScript = myInDesign.ActiveScript
MsgBox ("The current script is: " & myActiveScript)
Set myFileSystemObject = CreateObject("Scripting.FileSystemObject")
myParentFolder = myFileSystemObject.GetFile(myActiveScript).ParentFolder
MsgBox ("The folder containing the active script is: " & myParentFolder)
When you debug scripts using a script editor, the ActiveScript property returns an error. Only scripts run
from the Scripts palette appear in the ActiveScript property.
Script Versioning
InDesign can run scripts using earlier versions of the InDesign scripting object model. To run an older
script in a newer version of InDesign, you must consider the following:
Targeting — Scripts must be targeted to the version of InDesign in which they are being run (i.e., the
current version). The mechanics of targeting are language specific as described in “Targeting” on
page 13.
Compilation — This involves mapping the names in the script to the underlying script IDs, which are
what InDesign understands. The mechanics of compilation are language specific as described in
“Compilation” on page 13.
Interpretation — This involves matching the IDs to the appropriate request handler within InDesign
so that InDesign correctly interprets a script written for an earlier version of the scripting object model.
To do this, either explicitly set the applications script preferences to the old object model within the
UserInteractionLevel This property controls the alerts and dialogs InDesign presents to the user.
When you set this property to
idUserInteractionLevels.idNeverInteract, InDesign does not display
any alerts or dialogs. Set it to
disable dialogs. Set it to idUserInteractionLevels.idInteractWithAll
to restore the normal display of alerts and dialogs. The ability to turn off alert
displays is very useful when you are opening documents via script; often,
InDesign displays an alert for missing fonts or linked graphics files. To avoid
this alert, set the user-interaction level to
idUserInteractionLevels.idNeverInteract before opening the
document, then restore user interaction (set the property to
idUserInteractionLevels.idInteractWithAll) before completing
script execution.
Version The version of the scripting environment in use. For more information, see
“Script Versioning” on page 12. Note this property is not the same as the
version of the application.
Property Description
CHAPTER 2: Scripting Features Script Versioning 13
script (as shown in “Interpretation” on page 13) or run the script from a folder in the Scripts panel
folder as follows:
Targeting
A script must always target the version of InDesign under which it is running (the current version), either
explicitly or implicitly. Targeting is implicit when the script is launched from the Scripts panel.
Otherwise, explicit targeting for Visual Basic applications and VBScripts is done using the CreateObject
method:
Rem Target InDesign CS6 Roman:
Set myApp = CreateObject("InDesign.Application.CS6")
Rem Target InDesign CS6 J:
Set myApp = CreateObject("InDesign.Application.CS6_J")
Rem Target the last version of InDesign that was launched:
Set myApp = CreateObject("InDesign.Application")
Compilation
Compilation of Visual Basic applications may be versioned by referencing an earlier version of the type
library. To generate an earlier version of the type library, use the PublishTerminology method, which is
exposed on the Application object. The type library is generated into a folder (named with the version of
the DOM) that is in the Scripting Support folder in your application’s preferences folder. For example, to
generate the CS5 dictionary into the C:\Documents and Settings\<username>\Application
Data\Adobe\InDesign\Version 8.0\<locale>\Scripting Support\7.0 folder:
Set myApp = CreateObject("InDesign.Application")
Rem Publish the InDesign CS5 type library (version 7.0 DOM)
myApp.PublishTerminology(7.0)
VBScripts are not precompiled. For compilation, InDesign generates and references the appropriate type
library automatically, based on the version of the DOM set for interpretation.
Interpretation
The InDesign application object contains a ScriptPreferences object, which allows a script to get/set
the version of the scripting object model to use for interpreting scripts. The version defaults to the current
version of the application and persists.
For example, to change the version of the scripting object model to CS5 (7.0):
Folder For InDesign version of scripts
Version 8.0 Scripts CS6
Version 7.0 Scripts CS5 and CS5.5
Version 6.0 Scripts CS4
Version 5.0 Scripts CS3
Version 2.0 Scripts CS2
CHAPTER 2: Scripting Features Using the DoScript Method 14
Set myInDesign = CreateObject("InDesign.Application")
Rem Set to 7.0 DOM
myInDesign.ScriptPreferences.Version = 7.0
Using the DoScript Method
The DoScript method gives a script a way to execute another script. The script can be a string of valid
scripting code or a file on disk. The script can be in the same scripting language as the current script or
another scripting language. The available languages vary by platform: on Mac OS®, you can run
AppleScript or JavaScript; on Windows®, VBScript or JavaScript.
The DoScript method has many possible uses:
Running a script in another language that provides a feature missing in your main scripting language.
For example, VBScript lacks the ability to display a file or folder browser, which JavaScript has.
AppleScript can be very slow to compute trigonometric functions (sine and cosine), but JavaScript
performs these calculations rapidly. JavaScript does not have a way to query Microsoft® Excel for the
contents of a specific spreadsheet cell, but both AppleScript and VBScript have this capability. In all
these examples, the DoScript method can execute a snippet of scripting code in another language,
to overcome a limitation of the language used for the body of the script.
Creating a script “on the fly.” Your script can create a script (as a string) during its execution, which it
can then execute using the DoScript method. This is a great way to create a custom dialog or panel
based on the contents of the selection or the attributes of objects the script creates.
Embedding scripts in objects. Scripts can use the DoScript method to run scripts that were saved as
strings in the label property of objects. Using this technique, an object can contain a script that
controls its layout properties or updates its content according to certain parameters. Scripts also can
be embedded in XML elements as an attribute of the element or as the contents of an element. See
“Running Scripts at Startup” on page 17.
Sending parameters to DoScript
To send a parameter to a script executed by DoScript, use the following form (from the
DoScriptParameters tutorial script):
Set myInDesign = CreateObject("InDesign.Application")
myJavaScript = "alert(""First argument: "" + arguments[0] + ""\rSecond argument: "" +
arguments[1]);"
myInDesign.DoScript myJavaScript, idScriptLanguage.idJavascript, Array("Hello from
DoScript", "Your message here.")
myVBScript = "msgbox arguments(1), vbOKOnly, ""First argument: "" & arguments(0)"
myInDesign.DoScript myVBScript, idScriptLanguage.idVisualBasic, Array("Hello from
DoScript", "Your message here.")
Returning values from DoScript
The following script fragment shows how to return a value from a script executed by DoScript. This
example uses a JavaScript that is executed as a string, but the same method works for script files. This
example returns a single value, but you can return multiple values by returning an array (for the complete
script, refer to the DoScriptReturnValues script).
CHAPTER 2: Scripting Features Controlling Undo with DoScript 15
Set myDocument = myInDesign.Documents.Item(1)
Set myPage = myDocument.Pages.Item(1)
Set myTextFrame = myPage.TextFrames.Item(1)
Set myDestinationPage = myDocument.Pages.Add(idLocationOptions.idAfter, myPage)
myPageIndex = myDestinationPage.Name
myID = myTextFrame.Id
myJavaScript = "var myDestinationPage = arguments[1];" & vbCr
myJavaScript = myJavaScript & "myID = arguments[0];" & vbCr
myJavaScript = myJavaScript & "var myX = arguments[2];" & vbCr
myJavaScript = myJavaScript & "var myY = arguments[3];" & vbCr
myJavaScript = myJavaScript & "var myPageItem =
app.documents.item(0).pages.item(0).pageItems.itemByID(myID);" & vbCr
myJavaScript = myJavaScript &
"myPageItem.duplicate(app.documents.item(0).pages.item(myDestinationPage));" & vbCr
Rem Create an array for the parameters we want to pass to the JavaScript.
myArguments = Array(myID, myPageIndex, 0, 0)
Set myDuplicate = myInDesign.DoScript(myJavaScript, idScriptLanguage.idJavascript,
myArguments)
Rem myDuplicate now contains a reference to the duplicated text frame.
Rem Change the text in the duplicated text frame.
myDuplicate.contents = "Duplicated text frame."
Another way to get values from another script is to use the ScriptArgs (short for “script arguments”)
object of the application. The following script fragment shows how to do this (for the complete script, see
DoScriptScriptArgs):
Set myInDesign = CreateObject("InDesign.Application")
myJavaScript = "app.scriptArgs.setValue(""ScriptArgumentA"", ""This is the first
script argument value."");" & vbCr
myJavaScript = myJavaScript & "app.scriptArgs.setValue(""ScriptArgumentB"", ""This is
the second script argument value."");" & vbCr
myInDesign.DoScript myJavaScript, idScriptLanguage.idJavascript
myScriptArgumentA = myInDesign.ScriptArgs.GetValue("ScriptArgumentA")
myScriptArgumentB = myInDesign.ScriptArgs.GetValue("ScriptArgumentB")
MsgBox "ScriptArgumentA: " & myScriptArgumentA & vbCr & "ScriptArgumentB: " &
myScriptArgumentB
myVBScript = "Set myInDesign = CreateObject(""InDesign.Application"")" & vbCr
myVBScript = myVBScript & "myInDesign.ScriptArgs.SetValue ""ScriptArgumentA"", ""This
is the first script argument value.""" & vbCr
myVBScript = myVBScript & "myInDesign.ScriptArgs.SetValue ""ScriptArgumentB"", ""This
is the second script argument value."""
myInDesign.DoScript myVBScript, idScriptLanguage.idVisualBasic
myScriptArgumentA = myInDesign.ScriptArgs.GetValue("ScriptArgumentA")
myScriptArgumentB = myInDesign.ScriptArgs.GetValue("ScriptArgumentB")
MsgBox "ScriptArgumentA: " & myScriptArgumentA & vbCr & "ScriptArgumentB: " &
myScriptArgumentB
Controlling Undo with DoScript
InDesign gives you the ability to undo almost every action, but this comes at a price: for almost every
action you make, InDesign writes to disk. For normal work you using the tools presented by the user
interface, this does not present any problem. For scripts, which can perform thousands of actions in the
time a human being can blink, the constant disk access can be a serious drag on performance.
The DoScript method offers a way around this performance bottleneck by providing two parameters that
control the way that scripts are executed relative to InDesigns Undo behavior. These parameters are
shown in the following examples:
CHAPTER 2: Scripting Features Working with Script Labels 16
Rem Given a script "myVBScript" and an array of parameters "myParameters"...
myInDesign.DoScript myVBScript, idScriptLanguage.idVisualBasic, myParameters,
idUndoModes.idFastEntireScript, "Script Action"
Rem idUndoModes can be:
Rem idUndoModes.idAutoUnto: Add no events to the Undo queue.
Rem idUndoModes.idEntireScript: Put a single event in the Undo queue.
Rem idUndoModes.idFastEntireScript: Put a single event in the Undo queue.
Rem idUndoModes.idScriptRequest: Undo each script action as a separate event.
Rem The last parameter is the text that appears in the Undo menu item.
Working with Script Labels
Many objects in InDesign scripting have a label property, including page items (rectangles, ovals, groups,
polygons, text frames, and graphic lines), table cells, documents, stories, and pages. This property can
store a very large amount of text.
The label of page items can be viewed, entered, or edited using the Script Label panel (choose Window >
Utilities > Script Label to display this panel), shown below. You also can add a label to an object using
scripting, and you can read the script label via scripting. For many objects, like stories, pages, and
paragraph styles, you cannot set or view the label using the Script Label panel.
The label property can contain any form of text data, such as tab- or comma-delimited text, HTML, or
XML. Because scripts also are text, they can be stored in the label property.
Page items can be referred to by their label, just like named items (such as paragraph styles, colors, or
layers) can be referred to by their name. The following script fragment demonstrates this special case of the
label property (for the complete script, see ScriptLabel):
Set myDocument = myInDesign.Documents.Add
Set myPage = myDocument.Pages.Item(1)
myPageWidth = myDocument.DocumentPreferences.PageWidth
myPageHeight = myDocument.DocumentPreferences.PageHeight
Rem Create 10 random page items.
For i = 1 To 10
myX1 = myGetRandom(0, myPageWidth, False)
myY1 = myGetRandom(0, myPageHeight, False)
myX2 = myGetRandom(0, myPageWidth, False)
myY2 = myGetRandom(0, myPageHeight, False)
Set myRectangle = myPage.Rectangles.Add
myRectangle.GeometricBounds = Array(myY1, myX1, myY2, myX2)
If myGetRandom(0, 1, True) > 0 Then
myRectangle.Label = "myScriptLabel"
End If
Next
Count = 0
For i = 1 To myPage.PageItems.Count
CHAPTER 2: Scripting Features Running Scripts at Startup 17
If myPage.PageItems.Item(i).Label = "myScriptLabel" Then
Count = Count + 1
End If
Next
MsgBox ("Found " & CStr(Count) & " page items with the label.")
Rem This function gets a random number in the range myStart to myEnd.
Function myGetRandom(myStart, myEnd, myInteger)
Rem Here's how to generate a random number from a given range:
Rem Int((upperbound - lowerbound + 1) * Rnd + lowerbound)
If myInteger = True Then
myGetRandom = Int(((myEnd - myStart + 1) * Rnd) + myStart)
Else
myGetRandom = ((myEnd - myStart + 1) * Rnd) + myStart
End If
End Function
In addition, all objects that support the label property also support custom labels. A script can set a
custom label using the InsertLabel method, and extract the custom label using the ExtractLabel
method, as shown in the following script fragment (from the CustomLabel tutorial script):
Set myInDesign = CreateObject("InDesign.Application")
Set myDocument = myInDesign.Documents.Add
Set myPage = myDocument.Pages.Item(1)
myDocument.ViewPreferences.HorizontalMeasurementUnits = idMeasurementUnits.idPoints
myDocument.ViewPreferences.VerticalMeasurementUnits = idMeasurementUnits.idPoints
Set myRectangle = myPage.Rectangles.Add
myRectangle.GeometricBounds = Array(72, 72, 144, 144)
Rem Insert a custom label using insertLabel. The first parameter is the
Rem name of the label, the second is the text to add to the label.
myRectangle.InsertLabel "CustomLabel", "This is some text stored in a custom label."
Rem Extract the text from the label and display it in an message box.
myString = myRectangle.ExtractLabel("CustomLabel")
MsgBox ("Custom label contained: " + myString)
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 Scripting Tutorial).
18
3Documents
The work you do in InDesign revolves around documents—creating them, saving them, printing or
exporting them, and populating them with page items, colors, styles, and text. Almost every
document-related task can be automated using InDesign scripting.
This chapter shows you how to do the following
Perform basic document-management tasks, including:
Creating a new document.
Opening a document.
Saving a document.
Closing a document.
Perform basic page-layout operations, including:
Setting the page size and document length.
Defining bleed and slug areas.
Specifying page columns and margins.
Change the appearance of the pasteboard.
Use guides and grids.
Change measurement units and ruler origin.
Define and apply document presets.
Set up master pages (master spreads)
Set text-formatting defaults.
Create a document template.
Create watermarks.
Chapter Update Status
CS6 Changes Updated list of what this chapter shows you how to do.
•Added section “Making an Adaptive Layout” on page 43.
•Added section “Collecting and Dropping Content” on page 46.
Added subsection “Exporting to grayscale PDF” on page 52.
Added subsection “Exporting as a PDF form” on page 54.
•In “Adjusting Page Sizes and Layout” on page 40, “Resizing and reframing pages” on page 41, and “Transforming pages” on
page 41, removed outdated references to features being new in CS5.
CHAPTER 3: Documents Basic Document Operations 19
Apply different sizes to different pages (multiple page sizes).
Apply flexible layout formats to the same pages for use in different devices or documents with
different sizes or orientation.
Print a document.
Export a document as Adobe PDF.
Export pages of a document as EPS.
Export a document as an ePub file.
We assume that you have already read Adobe InDesign Scripting Tutorial and know how to create, install,
and run a script.
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.)
Set myInDesign = CreateObject("InDesign.Application")
Set myDocument = myInDesign.Documents.Add
To create a document using a document preset, the Add method includes an optional parameter you can
use to specify a document preset, as shown in the following script. (For the complete script, see
MakeDocumentWithPreset.)
Rem Creates a new document using the specified document preset.
Set myInDesign = CreateObject("InDesign.Application")
Rem Replace "myDocumentPreset" in the following line with the name
Rem of the document preset you want to use.
Set myDocument = myInDesign.Documents.Add(True,
myInDesign.DocumentPresets.Item("myDocumentPreset"))
You can create a document without displaying it in a window, as shown in the following script fragment
(from the MakeDocumentWithParameters tutorial script):
Rem Creates a new document using the specified document preset.
Set myInDesign = CreateObject("InDesign.Application")
Rem Replace "myDocumentPreset" in the following line with the name
Rem of the document preset you want to use.
Set myDocument = myInDesign.Documents.Add(False)
Rem To show the window:
Set myWindow = myDocument.Windows.Add
Some script operations are much faster when the document window is hidden.
CHAPTER 3: Documents Basic Document Operations 20
Opening a document
The following script shows how to open an existing document. (For the complete script, see
OpenDocument.)
Set myInDesign = CreateObject("InDesign.Application")
Set myDocument = myInDesign.Open("c:\myTestDocument.indd")
You can choose to prevent the document from displaying (that is, hide it) by setting the showing window
parameter of the Open method to false (the default 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 fragment (from the OpenDocumentInBackground tutorial script):
Rem Opens an existing document in the background, then shows the document.
Rem Youíll have to fill in your own file path.
Set myInDesign = CreateObject("InDesign.Application")
Set myDocument = myInDesign.Open("c:\myTestDocument.indd", False)
Rem At this point, you can do things with the document without showing
Rem the document window. In some cases, scripts will run faster when
Rem the document window is not visible.
Rem When you want to show the hidden document, create a new window.
Set myLayoutWindow = myDocument.Windows.Add
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 Save method can do either operation, as
shown in the following script fragment (from the SaveDocument tutorial script):
Rem If the active document has been changed since it was last saved, save it.
Set myInDesign = CreateObject("InDesign.Application")
If myInDesign.ActiveDocument.Modified = True Then
myInDesign.ActiveDocument.Save
End If
The Save method has two optional parameters: The first (to) specifies the file to save to; the second
(stationery) can be set to true to save the document as a template, as shown in the following script
fragment (from the SaveDocumentAs tutorial script):
Rem If the active document has not been saved (ever), save it.
Set myInDesign = CreateObject("InDesign.Application")
If myDocument.Saved = False Then
Rem If you do not provide a file name,
Rem InDesign displays the Save dialog box.
myInDesign.ActiveDocument.Save "c:\myTestDocument.indd"
End If
You can save a document as a template, as shown in the following script fragment (from the
SaveAsTemplate tutorial script):
CHAPTER 3: Documents Basic Document Operations 21
Rem Save the active document as a template.
Set myInDesign = CreateObject("InDesign.Application")
If myInDesign.ActiveDocument.Saved = True Then
Rem Convert the file name to a string.
myFileName = myInDesign.ActiveDocument.FullName
Rem If the file name contains the extension ".indd",
Rem change it to ".indt".
If InStr(1, myFileName, ".indd") <> 0 Then
myFileName = Replace(myFileName, ".indd", ".indt")
End If
Else
Rem If the document has not been saved, then give it a
Rem default file name/file path.
myFileName = "c:\myTestDocument.indt"
End If
myInDesign.ActiveDocument.Save myFileName, True
Closing a document
The Close method closes a document, as shown in the following script fragment (from the
CloseDocument tutorial script):
Set myInDesign = CreateObject("InDesign.Application")
myInDesign.ActiveDocument.Close
Rem Note that you could also use:
Rem myInDesign.Documents.Item(1).Close
The Close method can take up to two optional parameters, as shown in the following script fragment
(from the CloseWithParameters tutorial script):
Rem Use idSaveOptions.idYes to save the document,idSaveOptions.idNo
Rem to close the document without saving, or idSaveOptions.idAsk to
Rem display a prompt. If you use idSaveOptions.idYes, you'll need to
Rem provide a reference to a file to save to in the second parameter Rem(SavingIn).
Set myInDesign = CreateObject("InDesign.Application")
Rem If the file has not been saved, display a prompt.
If myInDesign.ActiveDocument.Saved <> True Then
Rem Or, to save to a specific file name:
Rem myFile = "c:\myTestDocument.indd"
Rem myInDesign.ActiveDocument.Close idSaveOptions.idYes, myFile
Else
Rem If the file has already been saved, save it.
myInDesign.ActiveDocument.Close idSaveOptions.idYes
End If
You can close all open documents without saving them, as shown in the following script fragment (from
the CloseAll tutorial script):
Set myInDesign = CreateObject("InDesign.Application")
For myCounter = myInDesign.Documents.Length To 1 Step -1
myInDesign.Documents.Item(myCounter).Close idSaveOptions.idNo
Next
CHAPTER 3: Documents Basic Page Layout 22
Basic Page Layout
Each document has a default page size, assigned number of pages, bleed and slug working areas, and
columns and margins to define the area into which material is placed. Again, all these parameters are
accessible to scripting, as shown in the examples in this section.
Defining page size and document length
When you create a new document using the InDesign user interface, you can specify the default page size,
number of pages, page orientation, and whether the document uses facing pages. To create a document
using InDesign scripting, use the Documents.Add method, which does not specify these settings. After
creating a document, you can use the DocumentPreferences object to control the settings, as shown in
the following script fragment (from the DocumentPreferences tutorial script):
Set myInDesign = CreateObject("InDesign.Application")
Set myDocument = myInDesign.Documents.Add
With myDocument.DocumentPreferences
.PageHeight = "800pt"
.PageWidth = "600pt"
.PageOrientation = idPageOrientation.idLandscape
.PagesPerDocument = 16
End With
NOTE: The Application object also has a DocumentPreferences object. You can set the application
defaults for page height, page width, and other properties by changing the properties of this object. You
can also set individual page sizes; see “Adjusting Page Sizes and Layout”.
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). The two areas can be printed and exported independently; for example,
you might want to omit slug information for the final printing of a document. The following script shows
how to set up the bleed and slug for a new document. (For the complete script, see BleedAndSlug.)
Set myInDesign = CreateObject("InDesign.Application")
Set myDocument = myInDesign.Documents.Add
Rem The bleed and slug properties belong to the DocumentPreferences object.
With myDocument.DocumentPreferences
Rem Bleed
.DocumentBleedBottomOffset = "3p"
.DocumentBleedTopOffset = "3p"
.DocumentBleedInsideOrLeftOffset = "3p"
.DocumentBleedOutsideOrRightOffset = "3p"
Rem Slug
.SlugBottomOffset = "18p"
.SlugTopOffset = "3p"
.SlugInsideOrLeftOffset = "3p"
.SlugRightOrOutsideOffset = "3p"
End With
Alternately, if all the bleed distances are equal, as in the preceding example, you can use the
DocumentBleedUniformSize property, as shown in the following script fragment (from the
UniformBleed tutorial script):
CHAPTER 3: Documents Basic Page Layout 23
Rem Create a new document.
Set myInDesign = CreateObject("InDesign.Application")
Set myDocument = myInDesign.Documents.Add
Rem The bleed properties belong to the documentPreferences object.
With myDocument.DocumentPreferences
Rem Bleed
.DocumentBleedTopOffset = "3p"
.DocumentBleedUniformSize = True
End With
If all the slug distances are equal, you can use the DocumentSlugUniformSize property, as shown in the
following script fragment (from the UniformSlug tutorial script):
Rem Create a new document.
Set myInDesign = CreateObject("InDesign.Application")
Set myDocument = myInDesign.Documents.Add
Rem The slug properties belong to the documentPreferences object.
With myDocument.DocumentPreferences
Rem Slug:
.SlugTopOffset = "3p"
.DocumentSlugUniformSize = True
End With
In addition to setting the bleed and slug widths and heights, you can control the color used to draw the
guides defining the bleed and slug. This property is not in the DocumentPreferences object; instead, it is
in the PasteboardPreferences object, as shown in the following script fragment (from the
BleedSlugGuideColors tutorial script):
Set myInDesign = CreateObject("InDesign.Application")
With myInDesign.ActiveDocument.PasteboardPreferences
Rem Any of InDesign's guides can use the UIColors constants...
.BleedGuideColor = idUIColors.idCuteTeal
.SlugGuideColor = idUIColors.idCharcoal
Rem ...or you can specify an array of RGB values
Rem(with values from 0 to 255)
Rem .BleedGuideColor = Array(0, 198, 192)
Rem .SlugGuideColor = Array(192, 192, 192)
End With
Setting page margins and columns
Each page in a document can have its own margin and column settings. With InDesign scripting, these
properties are part of the MarginPreferences object for each page. This following sample script creates a
new document, then sets the margins and columns for all pages in the master spread. (For the complete
script, see PageMargins.)
Set myInDesign = CreateObject("InDesign.Application")
Set myDocument = myInDesign.Documents.Add
With myDocument.Pages.Item(1).MarginPreferences
.ColumnCount = 3
Rem columnGutter can be a number or a measurement string.
.ColumnGutter = "1p"
.Top = "4p"
.Bottom = "6p"
Rem When document.documentPreferences.facingPages = true,
Rem "left" means inside "right" means outside.
.Left = "6p"
.Right = "4p"
End With
CHAPTER 3: Documents Basic Page Layout 24
To set the page margins for an individual page, use the margin preferences for that page, as shown in the
following script fragment (from the PageMarginsForOnePage tutorial script):
Set myInDesign = CreateObject("InDesign.Application")
Set myDocument = myInDesign.Documents.Add
With myDocument.Pages.Item(1).MarginPreferences
.ColumnCount = 3
Rem columnGutter can be a number or a measurement string.
.ColumnGutter = "1p"
.Top = "4p"
.Bottom = "6p"
Rem When document.documentPreferences.facingPages = true,
Rem "left" means inside "right" means outside.
.Left = "6p"
.Right = "4p"
End With
InDesign does not allow you to create a page that is smaller than the sum of the relevant margins; that is,
the width of the page must be greater than the sum of the left and right page margins, and the height of
the page must be greater than the sum of the top and bottom margins. If you are creating very small
pages (for example, for individual newspaper advertisements) using the InDesign user interface, you can
easily set the correct margin sizes as you create the document, by entering new values in the document
default page Margin fields in the New Document dialog box.
From scripting, however, the solution is not as clear: when you create a document, it uses the application’s
default-margin preferences. These margins are applied to all pages of the document, including master
pages. Setting the document margin preferences affects only new pages and has no effect 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 existing pages, InDesign does not change the page size.
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):
Set myInDesign = CreateObject("InDesign.Application")
Set myDocument = myInDesign.Documents.Add
myDocument.ViewPreferences.HorizontalMeasurementUnits = idMeasurementUnits.idPoints
myDocument.ViewPreferences.VerticalMeasurementUnits = idMeasurementUnits.idPoints
With myDocument.MarginPreferences
.Top = 0
.Left = 0
.Bottom = 0
.Right = 0
.ColumnCount = 1
.ColumnGutter = 0
End With
Rem The following assumes that your default document contains a single page.
With myDocument.Pages.Item(1).MarginPreferences
.Top = 0
.Left = 0
.Bottom = 0
.Right = 0
.ColumnCount = 1
.ColumnGutter = 0
End With
Rem The following assumes that your default master spread contains two pages.
.Top = 0
.Left = 0
CHAPTER 3: Documents Basic Page Layout 25
.Bottom = 0
.Right = 0
.ColumnCount = 1
.ColumnGutter = 0
End With
.Top = 0
.Left = 0
.Bottom = 0
.Right = 0
.ColumnCount = 1
.ColumnGutter = 0
End With
myDocument.DocumentPreferences.PageHeight = "1p"
myDocument.DocumentPreferences.PageWidth = "6p"
Alternately, you can change the applications default-margin preferences before you create the document,
as shown in the following script fragment (from the ApplicationPageMargins tutorial script):
Set myInDesign = CreateObject("InDesign.Application")
With myInDesign.MarginPreferences
Rem Save the current application default margin preferences.
myY1 = .Top
myX1 = .Left
myY2 = .Bottom
myX2 = .Right
Rem Set the application default margin preferences.
.Top = 0
.Left = 0
.Bottom = 0
.Right = 0
End With
Rem Create a new example document to demonstrate the change.
Set myDocument = myInDesign.Documents.Add
myDocument.DocumentPreferences.PageHeight = "1p"
myDocument.DocumentPreferences.PageWidth = "6p"
Rem Reset the application default margin preferences to their former state.
With myInDesign.MarginPreferences
.Top = myY1
.Left = myX1
.Bottom = myY2
.Right = myX2
End With
Changing the appearance of the pasteboard
The pasteboard is the area that surrounds InDesign pages and spreads. You can use it for temporary
storage of page items or for job-tracking information. You can change the size of the pasteboard and its
color using scripting. The PreviewBackgroundColor property sets the color of the pasteboard in Preview
mode, as shown in the following script fragment (from the PasteboardPreferences tutorial script):
CHAPTER 3: Documents Basic Page Layout 26
Set myInDesign = CreateObject("InDesign.Application")
Set myDocument = myInDesign.Documents.Add
With myDocument.PasteboardPreferences
Rem You can use either a number or a measurement
Rem string to set the space above/below.
.MinimumSpaceAboveAndBelow = "12p"
Rem You can set the preview background color (which you'll only see
Rem in Preview mode) to any of the predefined UIColor constants...
.PreviewBackgroundColor = idUIColors.idGrassGreen
Rem ...or you can specify an array of RGB values (with values from 0 to 255)
Rem .PreviewBackgroundColor = Array(192, 192, 192)
End With
Guides and grids
Guides and grids make it easy to position objects on your document pages. These are very useful items to
add when you are creating templates for others to use.
Defining guides
Guides in InDesign give you an easy way to position objects on the pages of your document. The following
script fragment shows how to use guides. (For the complete script, see Guides.)
Set myInDesign = CreateObject("InDesign.Application")
Set myDocument = myInDesign.Documents.Add
myPageWidth = myDocument.DocumentPreferences.PageWidth
myPageHeight = myDocument.DocumentPreferences.PageHeight
With myDocument.Pages.Item(1)
Set myMarginPreferences = .MarginPreferences
Rem Place guides at the margins of the page.
.Orientation = idHorizontalOrVertical.idVertical
.Location = myMarginPreferences.Left
End With
.Orientation = idHorizontalOrVertical.idVertical
.Location = (myPageWidth - myMarginPreferences.Right)
End With
.Orientation = idHorizontalOrVertical.idHorizontal
.Location = myMarginPreferences.Top
End With
.Orientation = idHorizontalOrVertical.idHorizontal
.Location = (myPageHeight - myMarginPreferences.Bottom)
End With
Rem Place a guide at the vertical center of the page.
.Orientation = idHorizontalOrVertical.idVertical
.Location = (myPageWidth / 2)
End With
Rem Place a guide at the horizontal center of the page.
.Orientation = idHorizontalOrVertical.idHorizontal
.Location = (myPageHeight / 2)
End With
End With
CHAPTER 3: Documents Basic Page Layout 27
Horizontal guides can be limited to a given page or extend across all pages in a spread. From InDesign
scripting, you can control this using the FitToPage property. This property is ignored by vertical guides.
You can use scripting to change the layer, color, and visibility of guides, just as you can from the user
interface, as shown in the following script fragment (from the GuideOptions tutorial script):
Set myInDesign = CreateObject("InDesign.Application")
Set myDocument = myInDesign.Documents.Add
myPageWidth = myDocument.DocumentPreferences.PageWidth
myPageHeight = myDocument.DocumentPreferences.PageHeight
With myDocument.Pages.Item(1)
Set myMarginPreferences = .MarginPreferences
Rem Place guides at the margins of the page.
.Orientation = idHorizontalOrVertical.idVertical
.Location = myMarginPreferences.Left
End With
.Orientation = idHorizontalOrVertical.idVertical
.Location = (myPageWidth - myMarginPreferences.Right)
End With
.Orientation = idHorizontalOrVertical.idHorizontal
.Location = myMarginPreferences.Top
End With
.Orientation = idHorizontalOrVertical.idHorizontal
.Location = (myPageHeight - myMarginPreferences.Bottom)
End With
Rem Place a guide at the vertical center of the page.
.Orientation = idHorizontalOrVertical.idVertical
.Location = (myPageWidth / 2)
End With
Rem Place a guide at the horizontal center of the page.
.Orientation = idHorizontalOrVertical.idHorizontal
.Location = (myPageHeight / 2)
End With
End With
You also can create guides using the CreateGuides method on spreads and master spreads, as shown in
the following script fragment (from the CreateGuides tutorial script):
Set myInDesign = CreateObject("InDesign.Application")
Set myDocument = myInDesign.Documents.Add
Rem Parameters (all optional): row count, column count, row gutter,
Rem column gutter,guide color, fit margins, remove existing, layer.
Rem Note that the createGuides method does not take an RGB array
Rem for the guide color parameter.
myDocument.Spreads.Item(1).CreateGuides 4, 4, "1p", "1p", idUIColors.idGray, True,
True, myDocument.Layers.Item(0)
Setting grid preferences
To control the properties of the document and baseline grid, you set the properties of the
GridPreferences object, as shown in the following script fragment (from the DocumentAndBaselineGrid
tutorial script):
CHAPTER 3: Documents Basic Page Layout 28
Set myInDesign = CreateObject("InDesign.Application")
Set myDocument = myInDesign.Documents.Add
Rem Set the document measurement units to points.
myDocument.ViewPreferences.HorizontalMeasurementUnits = idMeasurementUnits.idPoints
myDocument.ViewPreferences.VerticalMeasurementUnits = idMeasurementUnits.idPoints
Rem Set up grid preferences.
With myDocument.GridPreferences
.BaselineStart = 56
.BaselineDivision = 14
.BaselineGridShown = True
.HorizontalGridlineDivision = 14
.HorizontalGridSubdivision = 5
.VerticalGridlineDivision = 14
.VerticalGridSubdivision = 5
.DocumentGridShown = True
End With
Snapping to guides and grids
All snap settings for a documents grids and guides are in the properties of the GuidePreferences and
GridPreferences objects. The following script fragment shows how to set guide and grid snap
properties. (For the complete script, see GuideGridPreferences.)
Set myInDesign = CreateObject("InDesign.Application")
Set myDocument = myInDesign.ActiveDocument
With myDocument.guidePreferences
.GuidesInBack = True;
.GuidesLocked = False;
.GuidesShown = True;
.GuidesSnapTo = True;
End With
With myDocument.gridPreferences {
.DocumentGridShown = False;
.DocumentGridSnapTo = True;
//Objects "snap" to the baseline grid when
//guidePreferences.guideSnapTo is set to true.
.BaselineGridShown = True;
End With
}
Changing measurement units and ruler
Thus far, the sample scripts used measurement strings, strings that force InDesign to use a specific
measurement unit (for example, “8.5i” for 8.5 inches). They do this because you might be using a different
measurement system when you run the script.
To specify the measurement system used in a script, use the document’s ViewPreferences object, as
shown in the following script fragment (from the ViewPreferences tutorial script):
CHAPTER 3: Documents Basic Page Layout 29
Set myInDesign = CreateObject("InDesign.Application")
Set myDocument = myInDesign.ActiveDocument
With myDocument.ViewPreferences
Rem Measurement unit choices are:
Rem * idMeasurementUnits.idAgates
Rem * idMeasurementUnits.idPicas
Rem * idMeasurementUnits.idPoints
Rem * idMeasurementUnits.idInches
Rem * idMeasurementUnits.idInchesDecimal
Rem * idMeasurementUnits.idMillimeters
Rem * idMeasurementUnits.idCentimeters
Rem * idMeasurementUnits.idCiceros
Rem * idMeasurementUnits.idCustom
Rem If you set the the vertical or horizontal measurement units
Rem to idMeasurementUnits.idCustom, you can also set a custom
Rem ruler increment (in points) using:
Rem .HorizontalCustomPoints = 15
Rem .VerticalCustomPoints = 15
Rem Set horizontal and vertical measurement units to points.
.HorizontalMeasurementUnits = idMeasurementUnits.idPoints
.VerticalMeasurementUnits = idMeasurementUnits.idPoints
End With
If you are writing a script that needs to use a specific measurement system, you can change the
measurement units at the beginning of the script, then restore the original measurement units at the end
of the script. This is shown in the following script fragment (from the ResetMeasurementUnits tutorial
script):
Set myInDesign = CreateObject("InDesign.Application")
Set myDocument = myInDesign.ActiveDocument
With myDocument.ViewPreferences
myOldXUnits = .HorizontalMeasurementUnits
myOldYUnits = .VerticalMeasurementUnits
.HorizontalMeasurementUnits = idMeasurementUnits.idPoints
.VerticalMeasurementUnits = idMeasurementUnits.idPoints
End With
Rem At this point, you can perform any series of script actions that
Rem depend on the measurement units you've set. At the end of the
Rem script, reset the units to their original state.
With myDocument.ViewPreferences
.HorizontalMeasurementUnits = myOldXUnits
.VerticalMeasurementUnits = myOldYUnits
End With
Defining and applying document presets
InDesign document presets enable you to store and apply common document set-up 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.
Creating a preset by copying values
To create a document preset using an existing document’s settings as an example, open a document that
has the document set-up properties you want to use in the document preset, then run the following script
(from the DocumentPresetByExample tutorial script):
CHAPTER 3: Documents Basic Page Layout 30
Set myInDesign = CreateObject("InDesign.Application")
If myInDesign.Documents.Count > 0 Then
Set myDocument = myInDesign.ActiveDocument
Rem If the document preset "myDocumentPreset" does not
Rem already exist, create it.
Rem Disable normal error handling.
Err.Clear
On Error Resume Next
Set myDocumentPreset = myInDesign.DocumentPresets.Item("myDocumentPreset")
Rem If the document preset did not exist, the above line
Rem generates an error. Handle the error.
If (Err.Number <> 0) Then
Set myDocumentPreset = myInDesign.DocumentPresets.Add
myDocumentPreset.Name = "myDocumentPreset"
Err.Clear
End If
Rem Restore normal error handling.
On Error GoTo 0
Rem Fill in the properties of the document preset with the corresponding
Rem properties of the active document.
With myDocumentPreset
Rem Note that the following gets the page margins
rem from the margin preferences of the document to get the margin
Rem preferences from the active page, replace "myDocument" with
Rem "myInDesign.activeWindow.activePage" in the following six lines
Rem (assuming the active window is a layout window).
.Left = myDocument.MarginPreferences.Left
.Right = myDocument.MarginPreferences.Right
.Top = myDocument.MarginPreferences.Top
.Bottom = myDocument.MarginPreferences.Bottom
.ColumnCount = myDocument.MarginPreferences.ColumnCount
.ColumnGutter = myDocument.MarginPreferences.ColumnGutter
.DocumentBleedBottomOffset =
myDocument.DocumentPreferences.DocumentBleedBottomOffset
.DocumentBleedTopOffset =
myDocument.DocumentPreferences.DocumentBleedTopOffset
.DocumentBleedInsideOrLeftOffset =
myDocument.DocumentPreferences.DocumentBleedInsideOrLeftOffset
.DocumentBleedOutsideOrRightOffset =
myDocument.DocumentPreferences.DocumentBleedOutsideOrRightOffset
.FacingPages = myDocument.DocumentPreferences.FacingPages
.PageHeight = myDocument.DocumentPreferences.PageHeight
.PageWidth = myDocument.DocumentPreferences.PageWidth
.PageOrientation = myDocument.DocumentPreferences.PageOrientation
.PagesPerDocument = myDocument.DocumentPreferences.PagesPerDocument
.SlugBottomOffset = myDocument.DocumentPreferences.SlugBottomOffset
.SlugTopOffset = myDocument.DocumentPreferences.SlugTopOffset
.SlugInsideOrLeftOffset =
myDocument.DocumentPreferences.SlugInsideOrLeftOffset
.SlugRightOrOutsideOffset =
myDocument.DocumentPreferences.SlugRightOrOutsideOffset
End With
End If
Creating a document preset
To create a document preset using explicit values, run the following script (from the DocumentPreset
tutorial script):
CHAPTER 3: Documents Basic Page Layout 31
On Error Resume Next
Set myDocumentPreset = myInDesign.DocumentPresets.Item("myDocumentPreset")
If Err.Number <> 0 Then
Set myDocumentPreset = myInDesign.DocumentPresets.Add
myDocumentPreset.Name = "myDocumentPreset"
Err.Clear
End If
On Error GoTo 0
Rem Fill in the properties of the document preset.
With myDocumentPreset
.PageHeight = "9i"
.PageWidth = "7i"
.Left = "4p"
.Right = "6p"
.Top = "4p"
.Bottom = "9p"
.ColumnCount = 1
.DocumentBleedBottomOffset = "3p"
.DocumentBleedTopOffset = "3p"
.DocumentBleedInsideOrLeftOffset = "3p"
.DocumentBleedOutsideOrRightOffset = "3p"
.FacingPages = True
.PageOrientation = idPageOrientation.idPortrait
.PagesPerDocument = 1
.SlugBottomOffset = "18p"
.SlugTopOffset = "3p"
.SlugInsideOrLeftOffset = "3p"
.SlugRightOrOutsideOffset = "3p"
End With
Setting up master spreads
After setting up the basic document page size, slug, and bleed, you probably will want to define the
documents master spreads. The following script shows how to do that. (For the complete script, see
Set myInDesign = CreateObject("InDesign.Application")
Rem Set up the first master spread in a new document.
Set myDocument = myInDesign.Documents.Add
Rem Set up the document.
With myDocument.DocumentPreferences
.PageHeight = "11i"
.PageWidth = "8.5i"
.FacingPages = True
.PageOrientation = idPageOrientation.idPortrait
End With
Rem Set the document's ruler origin to page origin. This is very important
Rem --if you don't do this, getting objects to the correct position on the
Rem page is much more difficult.
myDocument.ViewPreferences.RulerOrigin = idRulerOrigin.idPageOrigin
Rem Set up the left page (verso).
With .Pages.Item(1)
With .MarginPreferences
.ColumnCount = 3
.ColumnGutter = "1p"
.Bottom = "6p"
Rem "left" means inside "right" means outside.
.Left = "6p"
CHAPTER 3: Documents Basic Page Layout 32
.Right = "4p"
.Top = "4p"
End With
Rem Add a simple footer with a section number and page number.
.GeometricBounds = Array("61p", "4p", "62p", "45p")
.InsertionPoints.Item(1).Contents =
idSpecialCharacters.idSectionMarker
.InsertionPoints.Item(1).Contents = idSpecialCharacters.idEmSpace
.InsertionPoints.Item(1).Contents =
idSpecialCharacters.idAutoPageNumber
.Paragraphs.Item(1).Justification = idJustification.idLeftAlign
End With
End With
Rem Set up the right page (recto).
With .Pages.Item(2)
With .MarginPreferences
.ColumnCount = 3
.ColumnGutter = "1p"
.Bottom = "6p"
Rem "left" means inside "right" means outside.
.Left = "6p"
.Right = "4p"
.Top = "4p"
End With
Rem Add a simple footer with a section number and page number.
.GeometricBounds = Array("61p", "6p", "62p", "47p")
.InsertionPoints.Item(1).Contents =
idSpecialCharacters.idAutoPageNumber
.InsertionPoints.Item(1).Contents = idSpecialCharacters.idEmSpace
.InsertionPoints.Item(1).Contents =
idSpecialCharacters.idSectionMarker
.Paragraphs.Item(1).Justification = idJustification.idRightAlign
End With
End With
End With
To apply a master spread to a document page, use the AppliedMaster property of the document page, as
shown in the following script fragment (from the ApplyMaster tutorial script):
Set myInDesign = CreateObject("InDesign.Application")
Rem Assumes that the active document has a master page named "B-Master"
Rem and at least two pages.
myInDesign.ActiveDocument.Pages.Item(2).AppliedMaster =
Use the same property to apply a master spread to a master spread page, as shown in the following script
fragment (from the ApplyMasterToMaster tutorial script):
Rem Assumes that the default master spread name is "A-Master".
Set myInDesign = CreateObject("InDesign.Application")
Set myDocument = myInDesign.Documents.Add
Rem Create a new master spread.
myBMaster.NamePrefix = "B"
myBMaster.BaseName = "Master"
Rem Apply master spread "A" to the first page of the new master spread.
CHAPTER 3: Documents Basic Page Layout 33
Metadata is information that describes the content, origin, or other attributes of a file. In the InDesign user
interface, you enter, edit, and view metadata using the 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.
To learn more about XMP, see the XMP specification at
You also can add XMP information to a document using InDesign scripting. All XMP properties for a
document are in the documents metadataPreferences object. The example below fills in the standard
XMP data for a document.
This example also shows that XMP information is extensible. If you need to attach metadata to a document
and the data does not fall into a category provided by the metadata preferences object, you can create
your own metadata container (email, in this example). (For the complete script, see MetadataExample.)
Set myInDesign = CreateObject("InDesign.Application")
Set myDocument = myInDesign.Documents.Add
.Description = "Example of xmp metadata scripting in InDesign CS"
.DocumentTitle = "XMP Example"
.JobName = "XMP_Example_2004"
.Keywords = Array("animal", "mineral", "vegetable")
Rem The metadata preferences object also includes the read-only
Rem creator, format, creationDate, modificationDate, and serverURL properties that
are
Rem automatically entered and maintained by InDesign.
Rem Create a custom XMP container, "email"
End With
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. (For the complete script, see DocumentTemplate.)
CHAPTER 3: Documents Basic Page Layout 34
Set myInDesign = CreateObject("InDesign.Application")
Rem Set the application measurement unit defaults to points.
myInDesign.ViewPreferences.HorizontalMeasurementUnits = idMeasurementUnits.idPoints
myInDesign.ViewPreferences.VerticalMeasurementUnits = idMeasurementUnits.idPoints
Rem Set the application default margin preferences.
With myInDesign.MarginPreferences
Rem Save the current application default margin preferences.
myY1 = .Top
myX1 = .Left
myY2 = .Bottom
myX2 = .Right
Rem Set the application default margin preferences.
Rem Document baseline grid will be based on 14 points, and
Rem all margins are set in increments of 14 points.
.Top = 14 * 4
.Left = 14 * 4
.Bottom = 74
.Right = 14 * 5
End With
Rem Make a new document.
Set myDocument = myInDesign.Documents.Add
myDocument.DocumentPreferences.PageWidth = "7i"
myDocument.DocumentPreferences.PageHeight = "9i"
myDocument.DocumentPreferences.PageOrientation = idPageOrientation.idPortrait
Rem At this point, we can reset the application default margins
Rem to their original state.
With myInDesign.MarginPreferences
.Top = myY1
.Left = myX1
.Bottom = myY2
.Right = myX2
End With
Rem Set up the bleed and slug areas.
With myDocument.DocumentPreferences
Rem Bleed
.DocumentBleedBottomOffset = "3p"
.DocumentBleedTopOffset = "3p"
.DocumentBleedInsideOrLeftOffset = "3p"
.DocumentBleedOutsideOrRightOffset = "3p"
Rem Slug
.SlugBottomOffset = "18p"
.SlugTopOffset = "3p"
.SlugInsideOrLeftOffset = "3p"
.SlugRightOrOutsideOffset = "3p"
End With
Rem Create a color.
Err.Clear
On Error Resume Next
Rem If the color does not already exist, InDesign will generate an error.
Set myColor = myDocument.Colors.Item("PageNumberRed")
If Err.Number <> 0 Then
Set myColor = myDocument.Colors.Add
myColor.Name = "PageNumberRed"
myColor.colorModel = idColorModel.idProcess
myColor.ColorValue = Array(20, 100, 80, 10)
Err.Clear
End If
Rem restore normal error handling
On Error GoTo 0
Rem Next, set up some default styles.
CHAPTER 3: Documents Basic Page Layout 35
Rem Create up a character style for the page numbers.
Err.Clear
On Error Resume Next
Rem If the character style does not already exist, InDesign generates an error.
Set myCharacterStyle = myDocument.CharacterStyles.Item("page_number")
If Err.Number <> 0 Then
Set myCharacterStyle = myDocument.CharacterStyles.Add
myCharacterStyle.Name = "page_number"
Err.Clear
End If
Rem restore normal error handling
On Error GoTo 0
myDocument.CharacterStyles.Item("page_number").FillColor =
myDocument.Colors.Item("PageNumberRed")
Rem Create up a pair of paragraph styles for the page footer text.
Rem These styles have only basic formatting.
Err.Clear
On Error Resume Next
Rem If the paragraph style does not already exist, InDesign generates an error.
Set myParagraphStyle = myDocument.ParagraphStyles.Item("footer_left")
If Err.Number <> 0 Then
Set myParagraphStyle = myDocument.ParagraphStyles.Add
myParagraphStyle.Name = "footer_left"
myParagraphStyle.PointSize = 11
Err.Clear
End If
Rem restore normal error handling
On Error GoTo 0
Err.Clear
On Error Resume Next
Rem If the paragraph style does not already exist, InDesign generates an error.
Set myParagraphStyle = myDocument.ParagraphStyles.Item("footer_right")
If Err.Number <> 0 Then
Set myParagraphStyle = myDocument.ParagraphStyles.Add
myParagraphStyle.Name = "footer_right"
myParagraphStyle.BasedOn = myDocument.ParagraphStyles.Item("footer_left")
myParagraphStyle.Justification = idJustification.idRightAlign
myParagraphStyle.PointSize = 11
Err.Clear
End If
Rem restore normal error handling
On Error GoTo 0
Rem Create a layer for guides.
Err.Clear
On Error Resume Next
Set myLayer = myDocument.Layers.Item("GuideLayer")
If Err.Number <> 0 Then
Set myLayer = myDocument.Layers.Add
myLayer.Name = "GuideLayer"
Err.Clear
End If
Rem restore normal error handling
On Error GoTo 0
Rem Create a layer for the footer items.
Err.Clear
On Error Resume Next
Set myLayer = myDocument.Layers.Item("Footer")
If Err.Number <> 0 Then
CHAPTER 3: Documents Basic Page Layout 36
Set myLayer = myDocument.Layers.Add
myLayer.Name = "Footer"
Err.Clear
End If
Rem restore normal error handling
On Error GoTo 0
Rem Create a layer for the slug items.
Err.Clear
On Error Resume Next
Set myLayer = myDocument.Layers.Item("Slug")
If Err.Number <> 0 Then
Set myLayer = myDocument.Layers.Add
myLayer.Name = "Slug"
Err.Clear
End If
Rem restore normal error handling
On Error GoTo 0
Rem Create a layer for the body text.
Err.Clear
On Error Resume Next
Set myLayer = myDocument.Layers.Item("BodyText")
If Err.Number <> 0 Then
Set myLayer = myDocument.Layers.Add
myLayer.Name = "BodyText"
Err.Clear
End If
Rem restore normal error handling
On Error GoTo 0
With myDocument.ViewPreferences
.RulerOrigin = idRulerOrigin.idPageOrigin
.HorizontalMeasurementUnits = idMeasurementUnits.idPoints
.VerticalMeasurementUnits = idMeasurementUnits.idPoints
End With
Rem Document baseline grid and document grid
With myDocument.GridPreferences
.BaselineStart = 56
.BaselineDivision = 14
.BaselineGridShown = False
.HorizontalGridlineDivision = 14
.HorizontalGridSubdivision = 5
.VerticalGridlineDivision = 14
.VerticalGridSubdivision = 5
.DocumentGridShown = False
End With
Rem Document XMP information.
.Author = "Olav Martin Kvern"
.CopyrightNotice = "This document is not copyrighted."
.Description = "Example 7 x 9 book layout"
.DocumentTitle = "Example"
.JobName = "7 x 9 book layout template"
.Keywords = Array("7 x 9", "book", "template")
End With
Rem Set up the master spread.
With .Pages.Item(1)
CHAPTER 3: Documents Basic Page Layout 37
Rem Left and right are reversed for left-hand pages (becoming "inside" and
"outside"--
Rem this is also true in the InDesign user interface).
myTopMargin = .MarginPreferences.Top
myBottomMargin = myDocument.DocumentPreferences.PageHeight -
.MarginPreferences.Bottom
myRightMargin = myDocument.DocumentPreferences.PageWidth -
.MarginPreferences.Left
myLeftMargin = .MarginPreferences.Right
.ItemLayer = myDocument.Layers.Item("GuideLayer")
.Orientation = idHorizontalOrVertical.idVertical
.Location = myLeftMargin
End With
.ItemLayer = myDocument.Layers.Item("GuideLayer")
.Orientation = idHorizontalOrVertical.idVertical
.Location = myRightMargin
End With
.ItemLayer = myDocument.Layers.Item("GuideLayer")
.Orientation = idHorizontalOrVertical.idHorizontal
.Location = myTopMargin
.FitToPage = False
End With
.ItemLayer = myDocument.Layers.Item("GuideLayer")
.Orientation = idHorizontalOrVertical.idHorizontal
.Location = myBottomMargin
.FitToPage = False
End With
.ItemLayer = myDocument.Layers.Item("GuideLayer")
.Orientation = idHorizontalOrVertical.idHorizontal
.Location = myBottomMargin + 14
.FitToPage = False
End With
.ItemLayer = myDocument.Layers.Item("GuideLayer")
.Orientation = idHorizontalOrVertical.idHorizontal
.Location = myBottomMargin + 28
.FitToPage = False
End With
Set myLeftFooter = .TextFrames.Add
myLeftFooter.ItemLayer = myDocument.Layers.Item("Footer")
myLeftFooter.GeometricBounds = Array(myBottomMargin + 14,
.MarginPreferences.Right, myBottomMargin + 28, myRightMargin)
myLeftFooter.ParentStory.InsertionPoints.Item(1).Contents =
idSpecialCharacters.idSectionMarker
myLeftFooter.ParentStory.InsertionPoints.Item(1).Contents =
idSpecialCharacters.idEmSpace
myLeftFooter.ParentStory.InsertionPoints.Item(1).Contents =
idSpecialCharacters.idAutoPageNumber
myLeftFooter.ParentStory.Characters.Item(1).AppliedCharacterStyle =
myDocument.CharacterStyles.Item("page_number")
myLeftFooter.ParentStory.Paragraphs.Item(1).ApplyStyle
myDocument.ParagraphStyles.Item("footer_left"), False
Rem Slug information.
myDate = Date
CHAPTER 3: Documents Basic Page Layout 38
myString = "Author:" & vbTab & .Author & vbTab & "Description:" & vbTab &
.Description & vbCrLf & _
"Creation Date:" & vbTab & myDate & vbTab & "Email Contact" & vbTab &
End With
Set myLeftSlug = .TextFrames.Add
myLeftSlug.ItemLayer = myDocument.Layers.Item("Slug")
myLeftSlug.GeometricBounds = Array(myDocument.DocumentPreferences.PageHeight +
36, .MarginPreferences.Right, myDocument.DocumentPreferences.PageHeight + 144,
myRightMargin)
myLeftSlug.Contents = myString
myLeftSlug.ParentStory.Texts.Item(1).ConvertToTable
Rem Body text master text frame.
Set myLeftFrame = .TextFrames.Add
myLeftFrame.ItemLayer = myDocument.Layers.Item("BodyText")
myLeftFrame.GeometricBounds = Array(.MarginPreferences.Top,
.MarginPreferences.Right, myBottomMargin, myRightMargin)
End With
With .Pages.Item(2)
myTopMargin = .MarginPreferences.Top
myBottomMargin = myDocument.DocumentPreferences.PageHeight -
.MarginPreferences.Bottom
myRightMargin = myDocument.DocumentPreferences.PageWidth -
.MarginPreferences.Right
myLeftMargin = .MarginPreferences.Left
.ItemLayer = myDocument.Layers.Item("GuideLayer")
.Orientation = idHorizontalOrVertical.idVertical
.Location = myLeftMargin
End With
.ItemLayer = myDocument.Layers.Item("GuideLayer")
.Orientation = idHorizontalOrVertical.idVertical
.Location = myRightMargin
End With
Set myRightFooter = .TextFrames.Add
myRightFooter.ItemLayer = myDocument.Layers.Item("Footer")
myRightFooter.GeometricBounds = Array(myBottomMargin + 14,
.MarginPreferences.Left, myBottomMargin + 28, myRightMargin)
myRightFooter.ParentStory.InsertionPoints.Item(1).Contents =
idSpecialCharacters.idAutoPageNumber
myRightFooter.ParentStory.InsertionPoints.Item(1).Contents =
idSpecialCharacters.idEmSpace
myRightFooter.ParentStory.InsertionPoints.Item(1).Contents =
idSpecialCharacters.idSectionMarker
myRightFooter.ParentStory.Characters.Item(-1).AppliedCharacterStyle =
myDocument.CharacterStyles.Item("page_number")
myRightFooter.ParentStory.Paragraphs.Item(1).ApplyStyle
myDocument.ParagraphStyles.Item("footer_right"), False
Rem Slug information.
Set myRightSlug = .TextFrames.Add
myRightSlug.ItemLayer = myDocument.Layers.Item("Slug")
myRightSlug.GeometricBounds = Array(myDocument.DocumentPreferences.PageHeight +
36, myLeftMargin, myDocument.DocumentPreferences.PageHeight + 144, myRightMargin)
CHAPTER 3: Documents Basic Page Layout 39
myRightSlug.Contents = myString
myRightSlug.ParentStory.Texts.Item(1).ConvertToTable
Rem Body text master text frame.
Set myRightFrame = .TextFrames.Add
myRightFrame.ItemLayer = myDocument.Layers.Item("BodyText")
myRightFrame.GeometricBounds = Array(.MarginPreferences.Top,
.MarginPreferences.Left, myBottomMargin, myRightMargin)
myRightFrame.PreviousTextFrame = myLeftFrame
End With
End With
Rem Add section marker text--this text will appear in the footer.
myDocument.Sections.Item(1).Marker = "Section 1"
Rem When you link the master page text frames, one of the frames
Rem sometimes becomes selected. Deselect it.
myInDesign.Select idNothingEnum.idNothing
Creating watermarks
You can apply watermarks to documents in InDesign or InDesign Server using scripting. Currently, no user
interface component exists in InDesign for managing watermarks.
A document’s watermark preferences can be set in two ways using scripting:
Application-level watermark preferences, if any are set, are applied to the document watermark
preferences for each new document created by InDesign. This setting has no effect on existing
documents.
Document-level watermark preferences apply only to that document. Setting or changing a
document’s watermark preferences replaces any previous watermark settings for the document.
Both the document and application watermark preference settings persist after the document or
application is closed until a script changes them.
The same group of watermark preferences exist for both the document and the application objects.
Setting watermark preferences
The following script fragment shows how to set watermarks at the application level. A watermark will be
applied to all documents created after this code finishes. (For the complete script for setting application
preferences, see ApplicationWatermark.)
myInDesign.watermarkPreferences.watermarkVisibility = true
myInDesign.watermarkPreferences.watermarkDoPrint = true
myInDesign.watermarkPreferences.watermarkDrawInBack = true
myInDesign.watermarkPreferences.watermarkText = "Confidential"
myInDesign.watermarkPreferences.watermarkFontFamily = "Arial"
myInDesign.watermarkPreferences.watermarkFontStyle = "Bold"
myInDesign.watermarkPreferences.watermarkFontPointSize = 72
myInDesign.watermarkPreferences.watermarkFontColor = idUIColors.idRed
myInDesign.watermarkPreferences.watermarkOpacity = 60
myInDesign.watermarkPreferences.watermarkRotation = -45
myInDesign.watermarkPreferences.watermarkHorizontalPosition =
idWatermarkHorizontalPositionEnum.idWatermarkHCenter
myInDesign.watermarkPreferences.watermarkHorizontalOffset = 0
myInDesign.watermarkPreferences.watermarkVerticalPosition =
idWatermarkVerticalPositionEnum.idWatermarkVCenter
myInDesign.watermarkPreferences.watermarkVerticalOffset = 0
CHAPTER 3: Documents Adjusting Page Sizes and Layout 40
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.)
myInDesign.Documents.Item(1).WatermarkPreferences.watermarkVisibility = true
myInDesign.Documents.Item(1).WatermarkPreferences.watermarkDoPrint = true
myInDesign.Documents.Item(1).WatermarkPreferences.watermarkDrawInBack = true
myInDesign.Documents.Item(1).WatermarkPreferences.watermarkText = "Confidential"
myInDesign.Documents.Item(1).WatermarkPreferences.watermarkFontFamily = "Arial"
myInDesign.Documents.Item(1).WatermarkPreferences.watermarkFontStyle = "Bold"
myInDesign.Documents.Item(1).WatermarkPreferences.watermarkFontPointSize = 72
myInDesign.Documents.Item(1).WatermarkPreferences.watermarkFontColor =
idUIColors.idRed
myInDesign.Documents.Item(1).WatermarkPreferences.watermarkOpacity = 60
myInDesign.Documents.Item(1).WatermarkPreferences.watermarkRotation = -45
myInDesign.Documents.Item(1).WatermarkPreferences.watermarkHorizontalPosition =
idWatermarkHorizontalPositionEnum.idWatermarkHCenter
myInDesign.Documents.Item(1).WatermarkPreferences.watermarkHorizontalOffset = 0
myInDesign.Documents.Item(1).WatermarkPreferences.watermarkVerticalPosition =
idWatermarkVerticalPositionEnum.idWatermarkVCenter
myInDesign.Documents.Item(1).WatermarkPreferences.watermarkVerticalOffset = 0
Disabling watermarks
After turning off the application setting for watermarks, InDesign no longer turns on the watermark
settings for new documents by default. However, you can still set watermarks for individual documents.
The following script fragment shows how to turn off application-level watermarks.
Rem Given a reference to the InDesign application object "myInDesign"...
myInDesign.WatermarkVisibility = False
You can turn off watermarks in an individual document at any time, as shown in the following script
fragment.
Rem Given a reference to the InDesign application object "myInDesign"...
myInDesign.Documents.Item(1).WatermarkVisibility = False
Adjusting Page Sizes and Layout
InDesign allows different page sizes within a single InDesign document. For information on setting the
default page size, see “Defining page size and document length”.
You can also apply geometric transformations to individual pages.
Selecting pages
Before changing a page’s size or applying a transformation to the page, you must select the page. In the
InDesign user interface, you do this using the Page Tool on the Tools Panel. You can also select a page
using scripting. The following script shows how. (For the complete script, see PageSelect.)
CHAPTER 3: Documents Adjusting Page Sizes and Layout 41
Rem Given a document with four pages (1, 2, 3, 4)...
Set myDocument = myInDesign.ActiveDocument
Set myPages = myDocument.Pages
Rem Select page 2 and 3.
myPages.Item(2).Select()
Rem Select last page.
Resizing and reframing pages
You can resize or reframe page items on a page by scripting. 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. See “Setting page margins and
The following script shows how to change a page’s size using the resize method. (For the complete script,
see PageResize.)
Rem Given a document with four pages (1, 2, 3, 4)...
Set myDocument = myInDesign.ActiveDocument
Set myPages = myDocument.Pages
Rem Resize page to two times bigger
Call myPages.Item(2).Resize(idCoordinateSpaces.idInnerCoordinates, _
idAnchorPoint.idCenterAnchor, _
idResizeMethods.idMultiplyingCurrentDimensionsBy, _
Array(2, 2))
Rem Resize page to 400 points width and 600 points height.
Call myPages.item(3).Resize(idCoordinateSpaces.idInnerCoordinates, _
idAnchorPoint.idCenterAnchor, _
idResizeMethods.idReplacingCurrentDimensionsWith, _
Array(400, 600))
Reframing changes the bounding box of a page, so reframing can be used to change a page’s size by
making the bounding box larger or smaller. The following script shows how to change a pages size using
the reframe method. (For the complete script, see PageReframe.)
Rem Given a document with four pages (1, 2, 3, 4)...
Set myDocument = myInDesign.ActiveDocument
Set myPages = myDocument.Pages
Rem Make the page one inch wider and one inch higher.
Set myPage = myPages.Item(2)
myBounds = myPage.Bounds
myY1 = myBounds(0)
myX1 = myBounds(1)
myY2 = myBounds(2)+72
myX2 = myBounds(3)+72
Call myPage.Reframe(idCoordinateSpaces.idInnerCoordinates, _
Array(Array(myX1, myY1), _
Array(myX2, myY2)))
Transforming pages
Operations that change the geometry of objects are called transformations. The transform method can
rotate, scale, shear, and move (translate) page items on a page and can also be used on pages. For
technical details about transformation architecture, refer to “Transforming Page Items”.
CHAPTER 3: Documents Adjusting Page Sizes and Layout 42
To transform a page:
1. Create a transformation matrix.
2. Apply the transformation matrix to the page using the transform method.
The following script shows how to transform a page with scripting. (For the complete script, see
PageTransform.)
Rem Given a document with four pages (1, 2, 3, 4)...
Set myDocument = myInDesign.ActiveDocument
Set myPages = myDocument.Pages
Rem Rotate a page around its center point.
Set myRotateMatrix = myInDesign.TransformationMatrices.Add(, , , 27)
myTransform myPages.Item(1), myRotateMatrix
Rem Scale a page around its center point.
Set myScaleMatrix = myInDesign.TransformationMatrices.Add(0.8, 0.8)
myTransform myPages.Item(2), myScaleMatrix
Rem Shear a page around its center point.
Set myShearMatrix = myInDesign.TransformationMatrices.Add(, , 30)
myTransform myPages.Item(3), myShearMatrix
Function myTransform(myPage, myTransformationMatrix)
myPage.Transform idCoordinateSpaces.idPasteboardCoordinates, _
idAnchorPoint.idCenterAnchor, _
myTransformationMatrix
End Function
Master page overlay
Because pages can have multiple sizes, it is possible for a page and its master page to be different sizes. In
addition to tracking which master is applied, pages also maintain a matrix that determines how the master
page draws on the page. This is called the Master Page Overlay. When you select a page using the Page
Tool on the Tools Panel, you can see how the master page is positioned by checking the Show Master Page
Overlay checkbox on the control panel. You can move the overlay around with the mouse. InDesign
achieves this by applying a transform to the master overlay matrix. Although the user interface allows only
translation (moving x and y), you can do more by scripting. The following script shows how to transform a
master page overlay. (For the complete script, see MasterPageTransform.)
CHAPTER 3: Documents Making an Adaptive Layout 43
Rem Given a document with four pages (1, 2, 3, 4)...
Set myDocument = myInDesign.ActiveDocument
Set myPages = myDocument.Pages
Rem Rotate master page overlay around its top-left corner.
Set myRotateMatrix = myInDesign.TransformationMatrices.Add(, , , 27)
myPages.Item(1).MasterPageTransform = myRotateMatrix
Rem Scale master page overlay around its top-left corner.
Set myScaleMatrix = myInDesign.TransformationMatrices.Add(0.5, 0.5)
myPages.Item(2).MasterPageTransform = myScaleMatrix
Rem Shear master page overlay around its top-left corner.
Set myShearMatrix = myInDesign.TransformationMatrices.Add(, , 30)
myPages.Item(3).MasterPageTransform = myShearMatrix
Rem Translate master page overlay 1 inch right and 2 inches down.
Set myTranslateMatrix = myInDesign.TransformationMatrices.Add(, , , , 72, 144)
myPages.Item(4).MasterPageTransform = myTranslateMatrix
Making an Adaptive Layout
Using InDesign’s layout adaptation workflow, you create your primary layout the same way that you would
create it for a document that will be printed, but then you can quickly adapt that layout to another
orientation, to another dimension or aspect ratio, or to a completely different device class. This workflow
mainly involves two features: Liquid Layout makes the layout flexible, and Create Alternate Layout creates
alternative layouts for different orientations and device classes.
Making a flexible layout
Using layout rules, a designer can create one InDesign file with one set of physical pages that can display
their content suitably on different devices with different sizes and orientations. You can optionally control
the pages’ appearance for each size and orientation. The following example script shows how to do this.
(For the complete script, see LiquidLayout.)
Set doc = myInDesign.Documents.Add
Set myPage = doc.Pages.item(1)
REM Set layout policy to LayoutRuleOptions.OBJECT_BASED
myPage.LayoutRule = idLayoutRuleOptions.idOBJECTBASED
REM Create a text frame on the first page.
Set myTextFrame = myPage.TextFrames.Add
myTextFrame.GeometricBounds=myGetBounds(doc, myPage)
myTextFrame.Contents="This is object-based LayoutRule sample doc."
REM Create a rectangle
Set myItem = myPage.Rectangles.Add
myItem.GeometricBounds=Array(20,20,70,70)
myItem.VerticalLayoutConstraints = _
Array(idDimensionsConstraints.idFlexibleDimension, _
idDimensionsConstraints.idFlexibleDimension, _
idDimensionsConstraints.idFlexibleDimension)
myItem.HorizontalLayoutConstraints = _
Array(idDimensionsConstraints.idFixedDimension, _
idDimensionsConstraints.idflexibleDimension, _
idDimensionsConstraints.idFlexibleDimension)
Set doc2 = myInDesign.Documents.Add()
CHAPTER 3: Documents Making an Adaptive Layout 44
Set myPage2 = doc2.Pages.item(1)
REM Set layout rule to LayoutRuleOptions.SCALE
myPage2.LayoutRule = idLayoutRuleOptions.idSCALE
REM Create a text frame on the first page.
Set myTextFrame2 = myPage2.TextFrames.Add
myTextFrame2.GeometricBounds=myGetBounds(doc2, myPage2)
myTextFrame2.Contents="This is scale LayoutRule sample doc."
Set myItem2 = myPage2.Rectangles.Add
myItem2.GeometricBounds=Array(20,20,70,70)
Set doc3 = myInDesign.Documents.Add
Set myPage3 = doc3.Pages.item(1)
REM Set layout rule to LayoutRuleOptions.RECENTER
myPage3.LayoutRule = idLayoutRuleOptions.idRECENTER
REM Create a text frame on the first page.
Set myTextFrame3 = myPage3.TextFrames.Add
myTextFrame3.GeometricBounds=myGetBounds(doc3, myPage3)
myTextFrame3.Contents="This is recenter LayoutRule sample doc."
Set myItem3 = myPage3.Rectangles.Add
myItem3.GeometricBounds=Array(20,20,70,70)
Set doc4 = myInDesign.Documents.Add
Set myPage4 = doc4.Pages.item(1)
REM Set layout rule to LayoutRuleOptions.GUIDE_BASED
myPage4.LayoutRule = idLayoutRuleOptions.idGUIDEBASED
REM Create a text frame on the first page.
Set myTextFrame4 = myPage4.TextFrames.Add
myTextFrame4.GeometricBounds=myGetBounds(doc4, myPage4)
myTextFrame4.Contents="This is guide-based LayoutRule sample doc."
Set myItem4 = myPage4.Rectangles.Add
myItem4.GeometricBounds=Array(20,20,70,70)
with doc4
.GuideType=idGuideTypeOptions.idLIQUID
.Location=20
.Orientation=idHorizontalOrVertical.idHorizontal
End With
End With
Set doc5 = myInDesign.Documents.Add
Set myPage5 = doc5.Pages.item(1)
REM Set layout rule to LayoutRuleOptions.USE_MASTER
myPage5.LayoutRule = idLayoutRuleOptions.idUSEMASTER
REM Create a text frame on the first page.
Set myTextFrame5 = myPage5.TextFrames.Add
myTextFrame5.GeometricBounds=myGetBounds(doc5, myPage5)
myTextFrame5.Contents="This is master page LayoutRule sample doc."
Set myItem5 = myPage5.Rectangles.Add
myItem5.GeometricBounds=Array(20,20,70,70)
Adding guides for a guide-based layout
The following example script shows how to add guide slices for guide-based layout rules. (For the
complete script, see AddGuides.)
CHAPTER 3: Documents Making an Adaptive Layout 45
Set myDocument = myInDesign.Documents.Add
Rem Create a text frame on the current page.
Set myPage = myDocument.Pages.Item(1)
Rem Set layout policy
Rem Use guide slicing to resize objects on the page as it resizes.
myPage.LayoutRule = idLayoutRuleOptions.idGUIDEBASED
Set myTextFrame = myPage.TextFrames.Add
myTextFrame.GeometricBounds = myGetBounds(myDocument, myPage)
myTextFrame.Contents = "This is guide-based LayoutRule sample doc."
Set myItem = myPage.Rectangles.Add
myItem.GeometricBounds = Array(20, 20, 70, 70)
With myDocument
Set myGuide = .Guides.Add
myGuide.GuideType = idGuideTypeOptions.idLIQUID
myGuide.Location = 20
myGuide.orientation = idHorizontalOrVertical.idHorizontal
End With
Setting constraints for an object-based layout
The following example script shows how to set constraints for object-based layout rules. (For the complete
script, see SetConstraints.)
Set myDocument = myInDesign.Documents.Add
Rem Create a text frame on the current page.
Set myPage = myDocument.Pages.Item(1)
Rem Set layout rule
Rem Use guide slicing to resize objects on the page as it resizes.
myPage.LayoutRule = idLayoutRuleOptions.idOBJECTBASED
Set myTextFrame = myPage.TextFrames.Add
myTextFrame.GeometricBounds = myGetBounds(myDocument, myPage)
myTextFrame.Contents = "This is object-based layoutRule sample doc."
Set myItem = myPage.Rectangles.Add
myItem.GeometricBounds = Array(20, 20, 70, 70)
myItem.VerticalLayoutConstraints = _
Array(idDimensionsConstraints.idFlexibleDimension, _
idDimensionsConstraints.idFlexibleDimension, _
idDimensionsConstraints.idFlexibleDimension)
myItem.HorizontalLayoutConstraints = _
Array(idDimensionsConstraints.idFlexibleDimension, _
idDimensionsConstraints.idFlexibleDimension, _
idDimensionsConstraints.idFlexibleDimension)
Creating alternative layouts
Create Alternate Layout takes a range of existing pages with content and automatically creates linked
copies of the content on a set of new pages within the same document. Use this when you need to create
unique layouts for different orientations and device classes. (For the complete script, see
CreateAlternateLayout.)
CHAPTER 3: Documents Collecting and Dropping Content 46
Set myDoc = myInDesign.Documents.Add
With myDoc.DocumentPreferences
.facingPages=false
.pagesPerDocument=1
.pageWidth=1024
.pageHeight=768
End With
REM Reposition and resize objects on the page as it resizes.
myDoc.Pages.item(1).LayoutRule = idLayoutRuleOptions.idOBJECTBASED
With myDoc
Set myItem = .Pages.Item(1).Rectangles.Add
myItem.GeometricBounds=Array(50,50,100,100)
End With
REM create alternate layout
myDoc.CreateAlternateLayout myDoc.Spreads, "new layout", _
myDoc.DocumentPreferences.PageHeight, _
myDoc.DocumentPreferences.PageWidth, _
true, true, _
idLayoutRuleOptions.idPRESERVEEXISTING
Collecting and Dropping Content
With Content Dropper, you can copy the content from a file designed for printing and paste it into another
document.
The following script shows how to collect content in a document using scripting. (For the complete script,
see ContentCollectorAndPlacer.)
REM Invoke load with full parameters
contentPlacer.load myPage.Rectangles, true, true, true, true
The following script shows how to place collected content into another document. (For the complete
script, see ContentCollectorAndPlacer.)
REM Invoke Page.contentPlace with full parameters
myPage1.ContentPlace myPage.Rectangles, _
true, _
true, _
true, _
Array(0, 0, 40, 40), _
myDocument1.ActiveLayer, _
true
Printing a Document
The following script prints the active document using the current print preferences. (For the complete
script, see PrintDocument.)
Set myInDesign = CreateObject("InDesign.Application")
Rem The PrintOut method has two optional parameters:
Rem PrintDialog--if true, display the Print dialog box
Rem Using--the printer preset to use. The following line
Rem prints the document using the default settings and
Rem without displaying the Print dialog box.
myInDesign.ActiveDocument.PrintOut False
CHAPTER 3: Documents Printing a Document 47
Printing using page ranges
To specify a page range to print, set the PageRange property of the documents print preferences
object before printing, as shown in the following script fragment (from the PrintPageRange tutorial script):
Rem Prints a page range from the active document.
Rem The page range can be either idPageRange.idAllPages or a page range string.
Rem A page number entered in the page range must correspond to a page
Rem name in the document (i.e., not the page index). If the page name is
Rem not found, InDesign will display an error message.
myInDesign.ActiveDocument.PrintPreferences.PageRange = "1-3, 6, 9"
myInDesign.ActiveDocument.PrintOut False
Setting print preferences
The print preferences object contains properties corresponding to the options in the panels of the Print
dialog. The following script shows how to set print preferences using scripting. (For the complete script,
see PrintPreferences.)
Rem PrintPreferences.vbs
Rem An InDesign CS6 VBScript
Rem Sets the print preferences of the active document.
Set myInDesign = CreateObject("InDesign.Application")
With myInDesign.ActiveDocument.PrintPreferences
Rem Properties corresponding to the controls in the General panel
Rem of the Print dialog box.
Rem ActivePrinterPreset is ignored in this example--we'll set our own
Rem print preferences.
Rem printer can be either a string (the name of the printer) or
Rem idPrinter.idPostscriptFile.
.Printer = idPrinter.idPostscriptFile
Rem If the printer property is the name of a printer, then the ppd property
Rem is locked (and will return an error if you try to set it).
On Error Resume Next
Rem ppd = "AGFA-SelectSet5000SF"
If Err.Number <> 0 Then
Err.Clear
End If
Rem If the printer property is set to Printer.postscript file, the copies
Rem property is unavailable. Attempting to set it will generate an error.
Rem.Copies = 1
Rem If the printer property is set to Printer.postscript file, or if the
Rem selected printer does not support collation, then the collating
Rem property is unavailable. Attempting to set it will generate an error.
Rem collating = false
.ReverseOrder = False
Rem pageRange can be either PageRange.allPages or a page range string.
.PageRange = idPageRange.idAllPages
.PrintMasterPages = False
Rem If the printer property is set to Printer.postScript file, then
Rem the printFile property contains the file path to the output file.
Rem printFile = "/c/test.ps"
.Sequence = idSequences.idAll
Rem If trapping is set to either idTrapping.idApplicationBuiltIn
Rem then setting the following properties will produce an error.
If (.ColorOutput = idColorOutputModes.idInRIPSeparations) Or _
CHAPTER 3: Documents Printing a Document 48
(.ColorOutput = idColorOutputModes.idSeparations) Then
If .Trapping = idTrapping.idOff Then
.PrintBlankPages = False
.PrintGuidesGrids = False
.PrintNonprinting = False
End If
End If
Rem-----------------------------------------------------------------------
Rem Properties corresponding to the controls in the Setup panel
Rem of the Print dialog box.
Rem-----------------------------------------------------------------------
.PaperSize = idPaperSizes.idCustom
Rem Page width and height are ignored if paperSize is not PaperSizes.custom.
Rem .PaperHeight = 1200
Rem .PaperWidth = 1200
.PrintPageOrientation = idPrintPageOrientation.idPortrait
.PagePosition = idPagePositions.idCentered
.PaperGap = 0
.PaperOffset = 0
.PaperTransverse = False
.ScaleHeight = 100
.ScaleWidth = 100
.ScaleMode = idScaleModes.idScaleWidthHeight
.ScaleProportional = True
Rem If trapping is set to either idTrapping.idApplicationBuiltIn or
Rem idTrapping.idAdobeInRIP,then setting the following properties will
Rem produce an error.
If (.ColorOutput = idColorOutputModes.idInRIPSeparations) Or _
(.ColorOutput = idColorOutputModes.idSeparations) Then
If .Trapping = idTrapping.idOff Then
.TextAsBlack = False
.Thumbnails = False
Rem The following properties is not needed because thumbnails
Rem is set to false.
Rem thumbnailsPerPage = 4
.Tile = False
Rem The following properties are not needed
Rem because tile is set to false.
Rem .TilingOverlap = 12
Rem .TilingType = TilingTypes.auto
End If
End If
Rem-----------------------------------------------------------------------
Rem Properties corresponding to the controls in the Marks and Bleed
Rem panel of the Print dialog box.
Rem-----------------------------------------------------------------------
Rem Set the following property to true to print all printer's marks.
Rem allPrinterMarks = true
.UseDocumentBleedToPrint = False
Rem If useDocumentBleedToPrint = false then setting any of
Rem the bleed properties will result in an error.
Rem Get the bleed amounts from the document's bleed and add a bit.
.BleedBottom = myInDesign.ActiveDocument.DocumentPreferences.
DocumentBleedBottomOffset + 3
.BleedTop = myInDesign.ActiveDocument.
DocumentPreferences.DocumentBleedTopOffset + 3
.BleedInside = myInDesign.ActiveDocument.DocumentPreferences.
DocumentBleedInsideOrLeftOffset + 3
.BleedOutside = myInDesign.ActiveDocument.DocumentPreferences.
DocumentBleedOutsideOrRightOffset + 3
CHAPTER 3: Documents Printing a Document 49
Rem If any bleed area is greater than zero, then print the bleed marks.
If ((.BleedBottom = 0) And (.BleedTop = 0) And (.BleedInside = 0) _
And (.BleedOutside = 0)) Then
.BleedMarks = True
Else
.BleedMarks = False
End If
.ColorBars = True
.CropMarks = True
.IncludeSlugToPrint = False
.MarkLineWeight = idMarkLineWeight.idP125pt
.MarkOffset = 6
Rem .MarkType = MarkTypes.default
.PageInformationMarks = True
.RegistrationMarks = True
Rem-----------------------------------------------------------------------
Rem Properties corresponding to the controls in the
Rem Output panel of the Print dialog box.
Rem-----------------------------------------------------------------------
.Negative = True
.ColorOutput = idColorOutputModes.idSeparations
Rem Note the lowercase "i" in "Builtin"
.Trapping = idTrapping.idApplicationBuiltin
.Screening = "175 lpi/2400 dpi"
.Flip = idFlip.idNone
Rem The following options are only applicable if trapping is set to
If .Trapping = idTrapping.idAdobeInRIP Then
.PrintBlack = True
.PrintCyan = True
.PrintMagenta = True
.PrintYellow = True
End If
Rem Only change the ink angle and frequency when you want to override the
Rem screening set by the screening specified by the screening property.
Rem .BlackAngle = 45
Rem .BlackFrequency = 175
Rem .CyanAngle = 15
Rem .CyanFrequency = 175
Rem .MagentaAngle = 75
Rem .MagentaFreqency = 175
Rem .YellowAngle = 0
Rem .YellowFrequency = 175
Rem The following properties are not needed (because colorOutput
Rem is set to separations).
Rem .CompositeAngle = 45
Rem .CompositeFrequency = 175
Rem .SimulateOverprint = false
Rem-----------------------------------------------------------------------
Rem Properties corresponding to the controls in the Graphics
Rem panel of the Print dialog box.
Rem-----------------------------------------------------------------------
.SendImageData = idImageDataTypes.idAllImageData
Err.Clear
On Error Resume Next
.DataFormat = idDataFormat.idBinary
.PostScriptLevel = idPostScriptLevels.idLevel3
If Err.Number <> 0 Then
CHAPTER 3: Documents Exporting a Document as PDF 50
Err.Clear
End If
On Error GoTo 0
Rem-----------------------------------------------------------------------
Rem Properties corresponding to the controls in the Color
Rem Management panel of the Print dialog box.
Rem-----------------------------------------------------------------------
Rem If the UseColorManagement property of myInDesign.ColorSettings is false,
Rem attempting to set the following properties will return an error.
Err.Clear
On Error Resume Next
.SourceSpace = SourceSpaces.useDocument
.Intent = RenderingIntent.useColorSettings
.CRD = ColorRenderingDictionary.useDocument
.Profile = Profile.postscriptCMS
If Err.Number <> 0 Then
Err.Clear
End If
On Error GoTo 0
Rem-----------------------------------------------------------------------
Rem Properties corresponding to the controls in the
Rem Advanced panel of the Print dialog box.
Rem-----------------------------------------------------------------------
.OPIImageReplacement = False
.OmitBitmaps = False
.OmitEPS = False
.OmitPDF = False
Rem The following line assumes that you have a flattener
Rem preset named "high quality flattener".
Err.Clear
On Error Resume Next
.FlattenerPresetName = "high quality flattener"
If Err.Number <> 0 Then
Err.Clear
End If
On Error GoTo 0
End With
Printing with printer presets
To print a document using a printer preset, include the printer preset in the print command.
Exporting a Document as PDF
InDesign scripting offers full control over the creation of PDF files from your page-layout documents.
Exporting to PDF
The following script exports the current document as PDF, using the current PDF export options. (For the
complete script, see ExportPDF.)
Set myInDesign = CreateObject("InDesign.Application")
myInDesign.ActiveDocument.Export idExportFormat.idPDFType, "c:\myTestDocument.pdf",
False
CHAPTER 3: Documents Exporting a Document as PDF 51
The following script fragment shows how to export to PDF using a PDF export preset. (For the complete
script, see ExportPDFWithPreset.)
Set myInDesign = CreateObject("InDesign.Application")
myInDesign.ActiveDocument.Export idExportFormat.idPDFType, "c:\myTestDocument.pdf",
False, myInDesign.PDFExportPresets.Item("[Press]")
Setting PDF export options
The following script sets the PDF export options before exporting. (For the complete script, see
ExportPDFWithOptions.)
Set myInDesign = CreateObject("InDesign.Application")
With myInDesign.PDFExportPreferences
Rem Basic PDF output options.
.PageRange = idPageRange.idAllPages
.AcrobatCompatibility = idAcrobatCompatibility.idAcrobat6
.ExportGuidesAndGrids = False
.ExportLayers = False
.ExportNonprintingObjects = False
.GenerateThumbnails = False
On Error Resume Next
.IncludeICCProfiles = True
On Error GoTo 0
.IncludeBookmarks = True
.IncludeSlugWithPDF = False
.IncludeStructure = False
.InteractiveElementsOption = idInteractiveElementsOptions.idDoNotInclude
Rem Setting subsetFontsBelow to zero disallows font subsetting
Rem set subsetFontsBelow to some other value to use font subsetting.
.SubsetFontsBelow = 0
Rem Bitmap compression/sampling/quality options
Rem (note the additional "s" in "compression").
.ColorBitmapCompression = idBitmapCompression.idZip
.ColorBitmapQuality = idCompressionQuality.idEightBit
.ColorBitmapSampling = idSampling.idNone
Rem ThresholdToCompressColor is not needed in this example.
Rem ColorBitmapSamplingDPI is not needed when
Rem ColorBitmapSampling is set to none.
.GrayscaleBitmapCompression = idBitmapCompression.idZip
.GrayscaleBitmapQuality = idCompressionQuality.idEightBit
.GrayscaleBitmapSampling = idSampling.idNone
Rem ThresholdToCompressGray is not needed in this
Rem example.
Rem GrayscaleBitmapSamplingDPI is not needed when
Rem GrayscaleBitmapSampling is set to none.
.MonochromeBitmapCompression = idBitmapCompression.idZip
.MonochromeBitmapSampling = idSampling.idNone
Rem ThresholdToCompressMonochrome is not needed in this example.
Rem MonochromeBitmapSamplingDPI is not needed when
Rem MonochromeBitmapSampling is set to none.
Rem Other compression options.
.CompressionType = idPDFCompressionType.idCompressNone
.CompressTextAndLineArt = True
.CropImagesToFrames = True
.OptimizePDF = True
CHAPTER 3: Documents Exporting a Document as PDF 52
Rem Printers marks and prepress options.
Rem Get the bleed amounts from the document's bleed.
.BleedBottom = myInDesign.ActiveDocument.DocumentPreferences.
DocumentBleedBottomOffset
.BleedTop = myInDesign.ActiveDocument.DocumentPreferences.
DocumentBleedTopOffset
.BleedInside = myInDesign.ActiveDocument.DocumentPreferences.
DocumentBleedInsideOrLeftOffset
.BleedOutside = myInDesign.ActiveDocument.DocumentPreferences.
DocumentBleedOutsideOrRightOffset
Rem If any bleed area is greater than zero, then export the bleed marks.
If ((.BleedBottom = 0) And (.BleedTop = 0) And (.BleedInside = 0) And
(.BleedOutside = 0)) Then
.BleedMarks = True
Else
.BleedMarks = False
End If
.ColorBars = True
Rem ColorTileSize and GrayTileSize are only used when
Rem the export format is set to JPEG2000.
Rem .ColorTileSize = 256
Rem .GrayTileSize = 256
.CropMarks = True
.OmitBitmaps = False
.OmitEPS = False
.OmitPDF = False
.PageInformationMarks = True
.PageMarksOffset = 12
.PDFColorSpace = idPDFColorSpace.idUnchangedColorSpace
.PDFMarkType = idMarkTypes.idDefault
.PrinterMarkWeight = idPDFMarkWeight.idP125pt
.RegistrationMarks = True
On Error Resume Next
.SimulateOverprint = False
On Error GoTo 0
.UseDocumentBleedWithPDF = True
Rem Set viewPDF to true to open the PDF in Acrobat or Adobe Reader.
.ViewPDF = False
End With
Rem Now export the document. You'll have to fill in your own file path.
myInDesign.ActiveDocument.Export idExportFormat.idPDFType, "c:\myTestDocument.pdf",
False
Exporting to grayscale PDF
An InDesign document that contains colors can be exported to a color PDF or to a grayscale PDF. You can
modify the script in the preceding “Setting PDF export options” on page 51 section to export in grayscale
by changing the idPDFColorSpace option from idUnchangedColorSpace to gray. For example:
With app.pdfExportPreferences
.PDFColorSpace = idPDFColorSpace.idGRAY
End With
(For a different script that creates a small document containing color and exports it to PDF in grayscale, see
GreyscalePDFforIDS.)
CHAPTER 3: Documents Exporting a Document as PDF 53
Exporting a range of pages to PDF
The following script shows how to export a specified page range as PDF. (For the complete script, see
ExportPageRangeAsPDF.)
Set myInDesign = CreateObject("InDesign.Application")
Rem Enter the names of the pages you want to export in the following line.
Rem Note that the page name is not necessarily the index of the page in the
Rem document (e.g., the first page of a document whose page numbering starts
Rem with page 21 will be "21", not 1).
myInDesign.PDFExportPreferences.PageRange = "1-3, 6, 9"
Rem Fill in your own file path.
myFile = "c:\myTestFile.pdf"
myInDesign.ActiveDocument.Export idExportFormat.idPDFType, myFile, False
Exporting individual pages to PDF
The following script exports each page from a document as an individual PDF file. (For the complete script,
see ExportEachPageAsPDF.)
Set myInDesign = CreateObject("InDesign.Application")
Set myFileSystemObject = CreateObject("Scripting.FileSystemObject")
If myInDesign.Documents.Count <> 0 Then
Set myDocument = myInDesign.ActiveDocument
Rem VBScript doesn't have a native "get folder" statement, so we'll use
Rem InDesign's JavaScript to display a folder browser.
myJavaScript = "myFolder = Folder.selectDialog(""Choose a Folder"");
myFolderName = myFolder.fsName;"
Rem Run the string "myJavaScript" as a JavaScript
myFolderName = myInDesign.DoScript(myJavaScript,
idScriptLanguage.idJavascript)
If myFileSystemObject.FolderExists(myFolderName) Then
myExportPages myInDesign, myDocument, myFolderName
End If
End If
Function myExportPages(myInDesign, myDocument, myFolderName)
myDocumentName = myDocument.Name
Set myDialog = myInDesign.Dialogs.Add
With myDialog
.Name = "ExportPages"
.StaticLabel = "Base Name:"
End With
Set myBaseNameField = .TextEditboxes.Add
myBaseNameField.EditContents = myDocumentName
myBaseNameField.MinWidth = 160
End With
End With
End With
myResult = myDialog.Show
If myResult = True Then
myBaseName = myBaseNameField.EditContents
Rem Remove the dialog box from memory.
myDialog.Destroy
For myCounter = 1 To myDocument.Pages.Count
CHAPTER 3: Documents Exporting a Document as PDF 54
myPageName = myDocument.Pages.Item(myCounter).Name
myInDesign.PDFExportPreferences.PageRange = myPageName
Rem Generate a file path from the folder name,
Rem the base document name, and the page name.
Rem Replace the colons in the page name (e.g., "Sec1:1") wtih
Rem underscores.
myPageName = Replace(myPageName, ":", "_")
myFilePath = myFolderName & "\" & myBaseName & "_" &
myPageName & ".pdf"
myDocument.Export idExportFormat.idPDFType, myFilePath, False
Next
Else
myDialog.Destroy
End If
End Function
Exporting PDF with interactive features
The following script exports a document with interactive features as a PDF. (For the complete script, see
ExportInteractivePDF.)
Rem Given a document "myDocument," add page transitions...
For myCounter = 1 To myDocument.Spreads.Count
idPageTransitionTypeOptions.idWipeTransition
idPageTransitionDirectionOptions.idDown
idPageTransitionDurationOptions.idMedium
Next
myInDesign.InteractivePDFExportPreferences.FlipPages = True
myInDesign.InteractivePDFExportPreferences.FlipPagesSpeed = 5
myInDesign.InteractivePDFExportPreferences.OpenInFullScreen = True
myInDesign.InteractivePDFExportPreferences.InteractivePDFInteractiveElementsOption =
idInteractivePDFInteractiveElementsOptions.idIncludeAllMedia
Rem Export the document to PDF.
Rem You'll have to fill in your own file path.
myDocument.Export idExportFormat.idInteractivePDF, "C:\InteractivePDF.pdf", False
Exporting as a PDF form
To create a PDF that contains form fields, you can either save the InDesign document as PDF, then open it
in Acrobat and apply form fields, or apply text fields, radio buttons, signature fields, and so on directly in
InDesign and export the document to PDF as a form with no additional Acrobat editing required.
The following script applies form elements to an InDesign document and exports the document as a PDF
form. (For the complete script, see ExportInteractivePDFForm.)
CHAPTER 3: Documents Exporting a Document as PDF 55
Set myPage = myDocument.Pages.Item(1)
REM Create a textframe as firstname label
Set myTextFrame = myPage.TextFrames.Add
myTextFrame.GeometricBounds = Array(15, 15, 20, 35)
myTextFrame.Contents = "FirstName: "
REM Create a textbox as firstname input box
Set myTextBox = myPage.TextBoxes.Add
myTextBox.GeometricBounds = Array(15, 40, 20, 75)
REM Create another textframe as lastname label
Set myTextFrame1 = myPage.TextFrames.Add
myTextFrame1.GeometricBounds = Array(30, 15, 25, 35)
myTextFrame1.Contents = "LastName: "
REM Create another textbox as lastname input box
Set myTextBox = myPage.TextBoxes.Add
myTextBox.GeometricBounds = Array(30, 40, 25, 75)
REM Create a TextFrame to introduce the following checkbox
Set myTextFrame2 = myPage.TextFrames.Add
myTextFrame2.GeometricBounds = Array(15, 80, 20, 95)
myTextFrame2.Contents = "Hobby: "
REM Create some CheckBoxes
Set myCheckBox = myPage.CheckBoxes.Add
myCheckBox.GeometricBounds = Array(15, 100, 20, 105)
myCheckBox.Name = "Football "
Set myTextFrame3 = myPage.TextFrames.Add
myTextFrame3.GeometricBounds = Array(15, 107, 20, 125)
myTextFrame3.Contents = "Football "
Set myCheckBox1 = myPage.CheckBoxes.Add
myCheckBox1.GeometricBounds = Array(15, 130, 20, 135)
myCheckBox1.Name = "Basketball "
Set myTextFrame4 = myPage.TextFrames.Add
myTextFrame4.GeometricBounds = Array(15, 137, 20, 160)
myTextFrame4.Contents = "Basketball "
Set myCheckBox2 = myPage.CheckBoxes.Add
myCheckBox2.GeometricBounds = Array(15, 165, 20, 170)
myCheckBox2.Name = "Pingpong "
Set myTextFrame5 = myPage.TextFrames.Add
myTextFrame5.GeometricBounds = Array(15, 172, 20, 193)
myTextFrame5.Contents = "Pingpong "
REM Create a button for submit
Set submitButton = myPage.Buttons.Add
submitButton.GeometricBounds = Array(45, 15, 35, 35)
submitButton.Name = "Submit"
REM Fill contents to the button
Set myRightArrow1 = submitButton.States.Item(1).Polygons.Add
myRightArrow1.fillColor = myDocument.Colors.Item("Green")
myRightArrow1.Paths.Item(1).EntirePath = Array(Array(15, 35),Array(35,40),Array(15,
45))
REM Add the Rollover state.
Set myRolloverState1 = submitButton.States.Add
REM Add a shadow to the polygon in the Rollover state.
Set myRolloverArrow1 = myRolloverState1.Polygons.Add
myRolloverArrow1.fillColor = myDocument.Colors.Item("Green")
myRolloverArrow1.Paths.Item(1).EntirePath = Array(Array(15, 35),Array(35,40),Array(15,
45))
Set myFillTransparencySettings1 = myRolloverArrow1.FillTransparencySettings
CHAPTER 3: Documents Exporting Pages as EPS 56
REM Add a shadow to the polygon in the Click state.
Set myClickState1 = submitButton.States.Add
Set myClickArrow1 = myClickState1.Polygons.Add
myClickArrow1.FillColor = myDocument.Colors.Item("Blue")
myClickArrow1.Paths.Item(1).EntirePath = Array(Array(15,
35),Array(35,40),Array(15,45))
REM Set the behavior for the button.
Set SubmitForm = submitButton.SubmitFormBehaviors.Add
SubmitForm.BehaviorEvent = idBehaviorEvents.idMouseUp
REM Create a button for print
Set printButton = myPage.Buttons.Add
printButton.GeometricBounds = Array(45, 40, 35, 60)
REM Fill contents to the button
Set myRightArrow2 = printButton.States.Item(1).Polygons.Add
myRightArrow2.fillColor = myDocument.Colors.Item("Red")
myRightArrow2.Paths.Item(1).EntirePath = Array(Array(40, 35),Array(60,40),Array(40,
45))
REM Add the Rollover state.
Set myRolloverState2 = printButton.States.Add
REM Add a shadow to the polygon in the Rollover state.
Set myRolloverArrow2 = myRolloverState2.Polygons.Add
myRolloverArrow2.FillColor = myDocument.Colors.Item("Red")
myRolloverArrow2.Paths.Item(1).EntirePath = Array(Array(40, 35),Array(60,40),Array(40,
45))
Set myFillTransparencySettings2 = myRolloverArrow2.FillTransparencySettings
REM Add a shadow to the polygon in the Click state.
Set myClickState2 = printButton.States.Add
Set myClickArrow2 = myClickState2.Polygons.Add
myClickArrow2.FillColor = myDocument.Colors.Item("Blue")
myClickArrow2.Paths.Item(1).EntirePath = Array(Array(40,
35),Array(60,40),Array(40,45))
REM Set the behavior for the button.
Set PrintForm = printButton.PrintFormBehaviors.Add
PrintForm.BehaviorEvent = idBehaviorEvents.idMouseUp
REM Export the document to PDF.
myDocument.Export idExportFormat.idInteractivePDF, "C:\SubmitForm.pdf", False
Exporting Pages as EPS
When you export a document as EPS, InDesign saves each page of the file as a separate EPS graphic (an
EPS, by definition, can contain only a single page). If you export more than a single page, InDesign
appends the index of the page to the filename. The index of the page in the document is not necessarily
the name of the page (as defined by the section options for the section containing the page).
Exporting all pages to EPS
The following script exports the pages of the active document to one or more EPS files. (For the complete
script, see ExportAsEPS.)
Set myInDesign = CreateObject("InDesign.Application")
myFile = "c:\myTestFile.eps"
myInDesign.ActiveDocument.Export idExportFormat.idEPSType, myFile, False
CHAPTER 3: Documents Exporting Pages as EPS 57
Exporting a range of pages to EPS
To control which pages are exported as EPS, set the page range property of the EPS export preferences to
a page-range string containing the page or pages you want to export, before exporting. (For the complete
script, see ExportPageRangeAsEPS.)
Set myInDesign = CreateObject("InDesign.Application")
Rem Enter the name of the page you want to export in the following line.
Rem Note that the page name is not necessarily the index of the page in the
Rem document (e.g., the first page of a document whose page numbering starts
Rem with page 21 will be "21", not 1).
myInDesign.EPSExportPreferences.PageRange = "1-3, 6, 9"
Rem Fill in your own file path.
myFile = "c:\myTestFile.eps"
myInDesign.ActiveDocument.Export idExportFormat.idEPSType, myFile, False
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.)
Set myInDesign = CreateObject("InDesign.Application")
Set myFileSystemObject = CreateObject("Scripting.FileSystemObject")
If myInDesign.Documents.Count <> 0 Then
Set myDocument = myInDesign.ActiveDocument
Rem VBScript doesn't have a native "get folder" statement, so we'll use
Rem InDesign's JavaScript to display a folder browser.
myJavaScript = "myFolder = Folder.selectDialog(""Choose a Folder"");
myFolderName = myFolder.fsName;"
Rem Run the string "myJavaScript" as a JavaScript
myFolderName = myInDesign.DoScript(myJavaScript,
idScriptLanguage.idJavascript)
If myFileSystemObject.FolderExists(myFolderName) Then
myExportEPSPages myInDesign, myDocument, myFolderName
End If
End If
Function myExportEPSPages(myInDesign, myDocument, myFolderName)
myDocumentName = myDocument.Name
Set myDialog = myInDesign.Dialogs.Add
With myDialog
.Name = "ExportPages"
.StaticLabel = "Base Name:"
End With
Set myBaseNameField = .TextEditboxes.Add
myBaseNameField.EditContents = myDocumentName
myBaseNameField.MinWidth = 160
End With
End With
End With
myResult = myDialog.Show
If myResult = True Then
myBaseName = myBaseNameField.EditContents
Rem Remove the dialog box from memory.
myDialog.Destroy
For myCounter = 1 To myDocument.Pages.Count
CHAPTER 3: Documents Exporting to EPub 58
myPageName = myDocument.Pages.Item(myCounter).Name
myInDesign.EPSExportPreferences.PageRange = myPageName
Rem Generate a file path from the folder name, the base document
Rem name, and the page name.
Rem Replace the colons in the page name (e.g., "Sec1:1") with
Rem underscores.
myPageName = Replace(myPageName, ":", "_")
myFilePath = myFolderName & "\" & myBaseName & "_" & _
myPageName & ".eps"
myDocument.Export idExportFormat.idEPSType, myFilePath, False
Next
Else
myDialog.Destroy
End If
End Function
Exporting to EPub
InDesign scripting offers full control over the creation of EPub files from your page-layout documents.
Exporting the current document
The following script exports the current document as EPub, using default options. (For the complete script,
see ExportEPub.)
Set myDocument = myInDesign.Documents.Item(1)
myDocument.Export idExportFormat.idEPUB, "C:\test\ExportEPub.epub", False
To give the user more control over the the creation of EPub files, specify true for the third parameter. This
opens the EPub export options dialog.
Setting EPub export options
The following script sets the EPub export options before exporting. (For the complete script, see
ExportEPubWithOptions.)
Rem Sets EPub export options, then exports the active document as EPub.
With myDocument.EPubExportPreferences
Rem Apply image alignment to anchored object settings.
.ApplyImageAlignmentToAnchoredObjectSettings = False
Rem The unit of space.
.SpaceUnit = idSpaceUnitType.idCssEm
Rem The unit of margin.
.MarginUnit = idSpaceUnitType.idCssEm
Rem Bottom margin of the epub.
.BottomMargin = 5
Rem Left margin of the epub.
.LeftMargin = 5
Rem Right margin of the epub.
.RightMargin = 5
Rem Top margin of the epub.
.TopMargin = 5
Rem If true, break InDesign document into smaller pieces when generating epub.
CHAPTER 3: Documents Exporting to EPub 59
.BreakDocument = False
Rem The bullet export option.
.BulletExportOption = idBulletListExportOption.idAsText
.CSSExportOption = idStyleSheetExportOption.idEmbeddedCSS
.CustomImageSizeOption = idImageSizeOption.idSizeRelativeToPageWidth
.EmbedFont = True
.EpubCover = idEpubCover.idFirstPage
Rem This will take effect only when EpubCover is set to idExternalImage.
Rem .CoverImageFile = "C:\conver.jpg"
.EpubPublisher = "Adobe Devtech"
Rem The export order.
.ExportOrder = idExportOrder.idLayoutOrder
Rem If true, output foornoteimmediately after its paragraph.
.FootnoteFollowParagraph = False
Rem If true, export epub in XHTML format. Otherwise, in DTBook format.
.Format = True
.GIFOptionsInterlaced = True
.GIFOptionsPalette = idGIFOptionsPalette.idWindowsPalette
Rem The epub unique identifier, like ISBN.
.Id = "123"
Rem Ignore object level image conversion settings.
.IgnoreObjectConversionSettings = True
Rem Alignment applied to images.
.ImageAlignment = idImageAlignmentType.idAlignCenter
Rem The file format to use for converted images.
Rem Valid only when copy optimized images and/or copy formatted images is true.
.ImageConversion = idImageConversion.idAutomatic
.ImageExportResolution = idImageResolution.idPpi150
Rem Image page break settings to be used with objects.
.ImagePageBreak = idImagePageBreakType.idPageBreakAfter
Rem Space After applied to images.
.ImageSpaceAfter = 2
Rem Space Before applied to images.
.ImageSpaceBefore = 2
Rem If true, include CSS definition.
.IncludeCSSDefinition = True
Rem If true, output document metadata into epub.
.JPEGOptionsFormat = idJPEGOptionsFormat.idBaselineEncoding
.JPEGOptionsQuality = idJPEGOptionsQuality.idHigh
Rem The PNG compression level.
.Level = 5
.NumberedListExportOption = idNumberedListExportOption.idAsText
Rem If true, format image based on layout appearence.
CHAPTER 3: Documents Exporting to EPub 60
.PreserveLayoutAppearence = True
Rem If true, output local style override.
.PreserveLocalOverride = True
.StripSoftReturn = True
Rem If true, image page break settings will be used in objects.
.UseImagePageBreak = True
Rem Use InDesign TOC style to generate epub TOC.
.UseTocStyle = True
.ViewDocumentAfterExport = False
End With
myDocument.Export idExportFormat.idEPUB, "C:\test\ExportEPubWithOptions.epub", False
61
4Working with Layers
InDesigns 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.
A document can contain one or more layers, and each document includes at least one layer. Layers are
document wide, not bound to specific pages or spreads.
This chapter covers scripting techniques related to layers in an InDesign layout and discusses common
operations involving layers.
Understanding the Layer Object Model
The following figure shows the layer object model. Note the following about the diagram:
It focuses on the location of a layer and its contents in the context of the object hierarchy of a
document; it does not attempt to show all the other ways a script might work with the content of a
layer (e.g., you can get a reference to a text-frame object from a story, text object, page, or spread, in
addition to finding it inside a layer object).
It uses the JavaScript form of the object names; however, the object hierarchy is the same in all
scripting languages.
The basic properties of a layer are shown in the column at the left of the figure; the objects that may
be contained by the layer object, at the right.
It is important to note the distinction between the page-items collection and the AllPageItems
collection. The former is a collection containing only the top-level page items in a layer. If a page item is
inside a group, for example, it will not appear in the PageItems collection. In contrast, the AllPageItems
collection is a flattened collection of all page items assigned to the layer, regardless of their location in the
object hierarchy. A page item inside a group on the layer would appear in the AllPageItems collection.
Similarly, the AllGraphics property contains all graphics stored in page items assigned to the layer,
regardless of their location in the object hierarchy.
Chapter Update Status
CS6 Unchanged
CHAPTER 4: Working with Layers Scripting Layers 62
Scripting Layers
In InDesigns 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. (For more on assigning objects to a layer, see the InDesign online help.)
This section shows how to accomplish these tasks using InDesign scripting.
Creating layers
The following script fragment shows how to create a new layer. (For the complete script, see AddLayer.)
Rem Given a document "myDocument"...
Set myLayer = myDocument.Layers.Add()
When you create a new layer, the layer appears above all other layers in the document.
Referring to layers
InDesign scripting offers several ways to refer to a layer object. This section describes the most common
ways to refer to layers.
CHAPTER 4: Working with Layers Scripting Layers 63
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.)
Rem Given a document "myDocument"...
Set myDocument = myInDesign.Documents.Item(1)
Set myLayer = myDocument.ActiveLayer
Referring to layers by layer index
You can get a reference to a layer using the index of the layer in the layers collection of a document. The
script fragment below uses the layer index to iterate through layers. (For the complete script, see
HideOtherLayers.)
Rem Given a document "myDocument"...
Set myTargetLayer = myDocument.ActiveLayer
For myCounter = 1 to myDocument.Layers.Count
Rem If the layer is not the target layer, hide it.
If myDocument.Layers.Item(myCounter).Name <> myTargetLayer.Name Then
myDocument.Layers.Item(myCounter).Visible = False
End If
Next
Note that you can use negative numbers to refer to the layers in the layers collection of a document. Layer
-1 refers to the last (bottom) layer in the collection.
Referring to layers by layer name
You also can get a reference to a layer using the name of the layer, as shown in the following script
fragment. (For the complete script, see LayerName.)
Rem Given a reference to the InDesign Application object "myInDesign"...
Set myLayer = myInDesign.Documents.Item(1).Layers.Item("Text Layer")
Using relative references
Given a layer, you can refer to the layer above using the PreviousItem method, or refer to the layer below
using the NextItem method, as shown in the following script fragment. (For the complete script, see
RelativeLayerReferences.) Both methods take a reference layer as a parameter.
Rem Given a document "myDocument"...
Set myLayer = myDocument.Layers.Item(5)
myDocument.activeLayer = myLayer
Set myNextLayer = myDocument.Layers.NextItem(myLayer)
Set myPreviousLayer = myDocument.Layers.PreviousItem(myLayer)
myString = "The layer below the target layer is " & myNextLayer.name & VBCr
myString = myString & "The layer above the target layer is " & myPreviousLayer.name
MsgBox(myString)
The PreviousItem and NextItem methods return an invalid layer reference if the specified (next or
previous) layer does not exist, rather than generating an error.
CHAPTER 4: Working with Layers Scripting Layers 64
Referring to ranges of layers
To refer to a series of layers, you can use the ItemByRange method. The following script fragment shows
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.)
Rem Given a document "myDocument"...
Set myLayer = myDocument.Layers.Item(5)
myDocument.ActiveLayer = myLayer
Rem Now hide all of the layers above the current layer.
Set myLayers = myDocument.Layers.ItemByRange(1, myTargetLayer.Index - 1)
Rem Iterate through the range of layers.
For myCounter = 1 To myLayers.Count
myLayers.Item(myCounter).Visible = False
Next
Deleting layers
Use the Delete method to delete a layer from a specific document, as shown in the following script
fragment. (For the complete script, see DeleteLayer.) You cannot delete the last remaining layer in a
document.
Rem Given a document "myDocument" containing a layer named "Delete This Layer"...
Set myLayer = myDocument.Layers.Item("Delete This Layer")
myLayer.Delete()
Moving layers
Use the move method to change the stacking order of layers in a document, as shown in the following
script fragment. (For the complete script, see MoveLayer.)
Rem Given a document "myDocument" containing at least two layers...
Set myLayerA = myDocument.Layers.Item(1)
Set myLayerB = myDocument.Layers.ITem(2)
myLayerA.Move idLocationOptions.idAfter,myLayerB
Duplicating layers
Use the duplicate method to create a copy of a layer, as shown in the following script fragment. (For the
complete script, see DuplicateLayer.)
Rem Given a layer "myLayer"...
Set myNewLayer = myLayer.Duplicate()
Merging layers
The following script fragment shows how to merge two or more layers, including the page items assigned
to them, into a single layer. (For the complete script, see MergeLayers.)
Rem Given the layers "myLayer1" and "myLayer2"...
myLayer1.Merge(myLayer2)
CHAPTER 4: Working with Layers Scripting Layers 65
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
add method of all page items can take a layer as a parameter) or setting the ItemLayer property of an
existing page item. The following script fragment shows how to assign a page item to a layer using both
techniques. (For the complete script, see AssignPageItemsToLayers.)
Rem Given a reference to a page "myPage," and a document "myDocument,"
Rem create a text frame on a layer named "TextFrames"
Set myTextFrame = myPage.TextFrames.Add(myDocument.Layers.Item("TextFrames"))
myTextFrame.geometricBounds = Array(72, 72, 144, 144)
Rem Create a rectangle on the current target layer.
Set myRectangle = myPage.Rectangles.Add
myRectangle.geometricBounds = Array(72, 144, 144, 216)
Rem Move the rectangle to a specific layer.
myRectangle.ItemLayer = myDocument.Layers.Item("Rectangles")
Rem Create a series of ovals.
For myCounter = 72 To 172 Step 10
Set myOval = myPage.Ovals.Add
myOval.geometricBounds = Array(216, myCounter, 226, myCounter + 10)
Next
Rem Move all of the ovals on the page to a specific layer.
For myCounter = 1 To myPage.Ovals.Count
myPage.Ovals.Item(myCounter).ItemLayer = myDocument.Layers.Item("Ovals")
Next
Setting layer properties
Layer properties control the layer name, color, visibility, and other attributes of a layer. This section shows
how to work with layer properties.
Setting basic layer properties
Basic layer properties include the name of the layer, the highlight color of the layer, the visibility of the
layer, and whether text objects on the layer ignore text-wrap settings. The following script fragment shows
how to set these basic properties of a layer. (For the complete script, see BasicLayerProperties.)
Rem Given a document "myDocument"...
Set myLayer = myDocument.Layers.Add
myLayer.Name = "myLayer"
myLayer.LayerColor = idUIColors.idCHARCOAL
myLayer.IgnoreWrap = False
myLayer.Visible = True
CHAPTER 4: Working with Layers Scripting Layers 66
Working with layer guides
Guides can be assigned to a specific layer, just like page items. You can choose to show or hide the guides
for a layer, and you can lock or unlock the guides on a layer. The following script fragment shows how to
work with the guides on a layer. (For the complete script, see LayerGuides.)
Rem Given a document "myDocument" and a page "myPage" containing at least one guide...
Rem Create a new layer.
Set myLayer = myDocument.Layers.Add
Rem Move all of the guides on the page to the new layer.
For myCounter = 1 to myPaqe.Guides.Count
myPage.Guides.Item(myCounter).ItemLayer = myLayer
Next
myLayer.LockGuides = True
myLayer.ShowGuides = True
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.)
Rem Given a document "myDocument" containing layers named "Background,"
Rem "Language A,", "Language B," and "Language C," export the "Background"
Rem layer and each "Language" layer to PDF as separate PDF files...
Set myFileSystemObject = New FileSystemObject
Set myFolder = myFileSystemObject.GetSpecialFolder(TemporaryFolder)
myPath = myFolder.ParentFolder.ParentFolder.Path & "\Desktop\"
For myCounter = 1 To 3
Select Case myCounter
Case 1:
myVersion = "Language A"
Case 2:
myVersion = "Language B"
Case 3:
myVersion = "Language C"
End Select
For myLanguageCounter = 1 To myDocument.Layers.Count
If myDocument.Layers.Item(myLanguageCounter).name = myVersion Or
myDocument.Layers.Item(myLanguageCounter).name = "Background" Then
myDocument.Layers.Item(myLanguageCounter).Visible = True
myDocument.Layers.Item(myLanguageCounter).Printable = True
Else
myDocument.Layers.Item(myLanguageCounter).Visible = False
myDocument.Layers.Item(myLanguageCounter).Printable = False
End If
Next
myFilePath = myPath & myVersion & ".pdf"
myDocument.Export idExportFormat.idPDFType, myFilePath
Next
CHAPTER 4: Working with Layers Scripting Layers 67
Locking layers
Layers can be locked, which means the page items on the layers cannot be edited. The following script
fragment shows how to lock and unlock layers. (For the complete script, see LockLayersBelow.)
Rem Given a document "myDocument"...
Set myTargetLayer = myDocument.ActiveLayer
Set myLayers = myDocument.Layers.ItemByRange(myDocument.Layers.Count,
myTargetLayer.Index + 1)
For myCounter = 1 To myLayers.Count
myLayers.Item(myCounter).Locked = True
Next
68
5Text and Type
Entering, editing, and formatting text are the tasks that make up the bulk of the time spent working on
most InDesign documents. Because of this, automating text and type operations can result in large
productivity gains.
This chapter shows how to script the most common operations involving text and type. The sample scripts
in this chapter are presented in order of complexity, starting with very simple scripts and building toward
more complex operations.
We assume that you have already read Adobe InDesign 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.
Entering and Importing Text
This section covers the process of getting text into your InDesign documents. Just as you can type text into
text frames and place text files using the InDesign user interface, you can create text frames, insert text
into a story, or place text files on pages using scripting.
Creating a text frame
The following script creates a text frame, sets the bounds (size) of the frame, then enters text in the frame
(for the complete script, see the MakeTextFrame tutorial script):
Set myDocument = myInDesign.Documents.Item(1)
Set myPage = myDocument.Pages.Item(1)
Set myTextFrame = myPage.TextFrames.Add
Rem Set the bounds of the text frame.
myTextFrame.GeometricBounds = Array(72, 72, 288, 288)
Rem Enter text in the text frame.
myTextFrame.Contents = "This is some example text."
The following script shows how to create a text frame that is the size of the area defined by the page
margins. myGetBounds is a useful function that you can add to your own scripts, and it appears in many
other examples in this chapter. (For the complete script, see MakeTextFrameWithinMargins.)
Set myDocument = myInDesign.Documents.Item(1)
Set myPage = myDocument.Pages.Item(1)
Rem Create a text frame on the current page.
Set myTextFrame = myPage.TextFrames.Add
Rem Set the bounds of the text frame.
myTextFrame.GeometricBounds = myGetBounds(myDocument, myDocument.Pages.Item(1))
Rem Enter text in the text frame.
myTextFrame.Contents = "This is some example text."
The following script fragment shows the myGetBounds function.
Chapter Update Status
CS6 Updated Added section “Fitting text frames to content” on page 87.
CHAPTER 5: Text and Type Entering and Importing Text 69
Function myGetBounds(myDocument, myPage)
myPageWidth = myDocument.DocumentPreferences.PageWidth
myPageHeight = myDocument.DocumentPreferences.PageHeight
If myPage.Side = idPageSideOptions.idLeftHand Then
myX2 = myPage.MarginPreferences.Left
myX1 = myPage.MarginPreferences.Right
Else
myX1 = myPage.MarginPreferences.Left
myX2 = myPage.MarginPreferences.Right
End If
myY1 = myPage.marginPreferences.Top
myX2 = myPageWidth - myX2
myY2 = myPageHeight - myPage.MarginPreferences.Bottom
myGetBounds = Array(myY1, myX1, myY2, myX2)
End Function
To add text to a story, use the contents property of the insertion point at the location where you want to
insert the text. The following sample script uses this technique to add text at the end of a story (for the
complete script, see AddText):
set myDocument = myInDesign.Documents.Item(1)
Set myTextFrame = myDocument.TextFrames.Item(1)
Rem Add text at the end of the text in the text frame.
Rem To do this, we'll use the last insertion point in the story.
Rem (vbCr is a return character, "&" concatenates two strings.)
myNewText = "This is a new paragraph of example text."
myTextFrame.ParentStory.InsertionPoints.Item(-1).Contents = vbCr & myNewText
Stories and text frames
All text in an InDesign layout is part of a story, and every story can contain one or more text frames.
Creating a text frame creates a story, and stories can contain multiple text frames.
In the preceding script, we added text at the end of the parent story rather than at the end of the text
frame. This is because the end of the text frame might not be the end of the story; that depends on the
length and formatting of the text. By adding the text to the end of the parent story, we can guarantee that
the text is added, regardless of the composition of the text in the text frame.
You always can get a reference to the story using the ParentTextFrame property of a text frame. It can be
useful to work with the text of a story instead of the text of a text frame; the following script demonstrates
the difference. The alerts shows that the text frame does not contain the overset text, but the story does
(for the complete script, see StoryAndTextFrame).
Set myDocument = myInDesign.Documents.Item(1)
Set myPage = myDocument.Pages.Item(1)
Set myTextFrame = myPage.TextFrames.Item(1)
Rem Now add text beyond the end of the text frame.
myTextFrame.InsertionPoints.Item(-1).Contents = vbCr & "This is some overset text"
myString = myTextFrame.Contents
MsgBox ("The last paragraph in this alert should be ""This is some overset text"". Is
it?" & vbCr & myString)
myString = myTextFrame.ParentStory.Contents
MsgBox ("The last paragraph in this alert should be ""This is some overset text"". Is
it?" & vbCr & myString)
CHAPTER 5: Text and Type Entering and Importing Text 70
For more on understanding the relationships between text objects in an InDesign document, see
“Understanding Text Objects” on page 78.
Replacing text
The following script replaces a word with a phrase by changing the contents of the appropriate object (for
the complete script, see ReplaceWord):
Set myDocument = myInDesign.Documents.Item(1)
Set myPage = myDocument.Pages.Item(1)
Set myTextFrame = myPage.TextFrames.Item(1)
Rem Replace the third word with the phrase
Rem "a little bit of".
myTextFrame.ParentStory.Words.Item(3).contents = "a little bit of"
The following script replaces the text in a paragraph (for the complete script, see ReplaceText):
Rem Replace the text in the second paragraph without replacing
Rem the return character at the end of the paragraph. To do this,
Rem we'll use the ItemByRange method.
Set myDocument = myInDesign.Documents.Item(1)
Set myPage = myDocument.Pages.Item(1)
Set myTextFrame = myPage.TextFrames.Item(1)
Set myStartCharacter = myTextFrame.ParentStory.Paragraphs.Item(2).Characters.Item(1)
Set myEndCharacter = myTextFrame.ParentStory.Paragraphs.Item(2).Characters.Item(-2)
myTextFrame.Texts.ItemByRange(myStartCharacter, myEndCharacter).Item(1).Contents =
"This text replaces the text in paragraph 2."
In the preceding script, we used the ItemByRange method to get a reference to the text of the paragraph
(excluding the return character at the end of the paragraph), as a single text object. We excluded the
return character because deleting the return might change the paragraph style applied to the paragraph.
To use the ItemByRange method, we used the texts collection of the story, but we supplied two
characters—the starting and ending characters of the paragraph—as parameters. If we used
myTextFrame.ParentStory.Characters.ItemByRange, InDesign would return a collection of
Character objects. We wanted one Text object, so we could replace the contents in one action.
Inserting special characters
Because most VBScript editors support Unicode, you can simply enter Unicode characters in text strings
that you send to InDesign. The following script shows several ways to enter special characters. (We
omitted the myGetBounds function from this listing; you can find it in “Creating a text frame” on page 68
or in the SpecialCharacters tutorial script.)
CHAPTER 5: Text and Type Placing Text and Setting Text-Import Preferences 71
Set myDocument = myInDesign.Documents.Item(1)
Set myPage = myDocument.Pages.Item(1)
Set myTextFrame = myPage.TextFrames.Item(1)
Rem Entering special characters directly.
myTextFrame.contents = "Registered trademark: Æ" & vbCr & "Copyright: ©" & vbCr &
"Trademark: ?" & vbCr & ""
Rem Entering special characters by their Unicode glyph ID
Rem value ("&H" indicates a hexadecimal number):
myTextFrame.ParentStory.InsertionPoints.Item(-1).contents = "Not equal to: " &
ChrW(&H2260) & vbCr & "Square root: " & ChrW(&H221A) & vbCr & "Paragraph: " & ChrW(&HB6)
& vbCr
Rem Entering InDesign special characters by their enumerations:
myTextFrame.ParentStory.InsertionPoints.Item(-1).contents = "Page number marker:"
myTextFrame.ParentStory.InsertionPoints.Item(-1).contents =
idSpecialCharacters.idAutoPageNumber
myTextFrame.ParentStory.InsertionPoints.Item(-1).contents = vbCr
myTextFrame.ParentStory.InsertionPoints.Item(-1).contents = "Section symbol:"
myTextFrame.ParentStory.InsertionPoints.Item(-1).contents =
idSpecialCharacters.idSectionSymbol
myTextFrame.ParentStory.InsertionPoints.Item(-1).contents = vbCr
myTextFrame.ParentStory.InsertionPoints.Item(-1).contents = "En dash:"
myTextFrame.ParentStory.InsertionPoints.Item(-1).contents =
idSpecialCharacters.idEnDash
myTextFrame.ParentStory.InsertionPoints.Item(-1).contents = vbCr
The easiest way to find the Unicode ID for a character is to use InDesigns Glyphs palette: move the cursor
over a character in the palette, and InDesign displays its Unicode value. To learn more about Unicode, visit
http://www.unicode.org.
Placing Text and Setting Text-Import Preferences
In addition to entering text strings, you can place text files created using word processors and text editors.
The following script shows how to place a text file on a document page (for the complete script, see
PlaceTextFile):
Set myDocument = myInDesign.Documents.Item(1)
Set myPage = myDocument.Pages.Item(1)
myX = myPage.MarginPreferences.Left
myY = myPage.MarginPreferences.Top
Rem Autoflow a text file on the current page.
Rem Parameters for Page.place():
Rem File as File object,
Rem [PlacePoint as Array [x, y]]
Rem [DestinationLayer as Layer object]
Rem [ShowingOptions as Boolean = False]
Rem [Autoflowing as Boolean = False]
Rem You'll have to fill in your own file path.
Set myTextFrame = myPage.Place("c:\test.txt", Array(myX, myY), , False, True)
Rem Note that if the PlacePoint parameter is inside a file, only the vertical (y)
Rem coordinate will be honored--the text frame will expand horizontally
Rem to fit the column.
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” on page 68,” or see the
PlaceTextFileInFrame tutorial script.)
CHAPTER 5: Text and Type Placing Text and Setting Text-Import Preferences 72
Set myDocument = myInDesign.Documents.Item(1)
Set myPage = myDocument.Pages.Item(1)
Set myTextFrame = myPage.TextFrames.Item(1)
Rem Place a text file in the text frame.
Rem Parameters for TextFrame.place():
Rem File as string,
Rem [ShowingOptions as Boolean = False]
Rem You'll have to fill in your own file path.
myTextFrame.Place "c:\test.txt"
The following script shows how to insert a text file at a specific location in text. (We omitted the
myGetBounds function from this listing; you can find it in “Creating a text frame” on page 68,” o r s e e th e
InsertTextFile tutorial script.)
Set myDocument = myInDesign.Documents.Item(1)
Set myPage = myDocument.Pages.Item(1)
Rem Create a text frame.
Set myTextFrame = myPage.TextFrames.Add
myTextFrame.geometricBounds = myGetBounds(myDocument, myPage)
myTextFrame.Contents = "Inserted text file follows:" & vbCr
Rem Place a text file at the end of the text.
Rem Parameters for InsertionPoint.place():
Rem File as string (file path),
Rem [ShowingOptions as Boolean = False]
Rem You'll have to fill in your own file path.
myTextFrame.ParentStory.InsertionPoints.Item(-1).Place "c:\test.txt"
To specify the import options for the specific type of text file you are placing, use the corresponding
import-preferences object. The following script shows how to set text-import preferences (for the
complete script, see TextImportPreferences). The comments in the script show the possible values for each
property.
With myInDesign.TextImportPreferences
Rem Options for characterSet: idTextImportCharacterSet
.CharacterSet = idTextImportCharacterSet.idUTF8
.ConvertSpacesIntoTabs = True
.SpacesIntoTabsCount = 3
Rem Dictionary can take many values, such as French, Italian.
.Dictionary = "English: USA"
Rem platform options: idImportPlatform
.Platform = idImportPlatform.idPC
.StripReturnsBetweenLines = True
.StripReturnsBetweenParagraphs = True
.UseTypographersQuotes = True
End With
The following script shows how to set tagged text import preferences (for the complete script, see
TaggedTextImportPreferences):
With myInDesign.TaggedTextImportPreferences
.RemoveTextFormatting = False
Rem .styleConflict property can be:
Rem idStyleConflict.idPublicationDefinition
Rem idStyleConflict.idTagFileDefinition
.StyleConflict = idStyleConflict.idPublicationDefinition
.UseTypographersQuotes = True
End With
The following script shows how to set Word and RTF import preferences (for the complete script, see
WordRTFImportPreferences):
CHAPTER 5: Text and Type Exporting Text and Setting Text-Export Preferences 73
With myInDesign.WordRTFImportPreferences
Rem convertPageBreaks property can be:
Rem idConvertPageBreaks.idColumnBreak
Rem idConvertPageBreaks.idNone
Rem idConvertPageBreaks.idPageBreak
.ConvertPageBreaks = idConvertPageBreaks.idNone
Rem convertTablesTo property can be:
Rem idConvertTablesOptions.idUnformattedTabbedText
Rem idConvertTablesOptions.idUnformattedTable
.ConvertTablesTo = idConvertTablesOptions.idUnformattedTable
.ImportEndnotes = True
.ImportFootnotes = True
.ImportIndex = True
.ImportTOC = True
.ImportUnusedStyles = False
.PreserveGraphics = False
.PreserveLocalOverrides = False
.PreserveTrackChanges = False
.RemoveFormatting = False
Rem resolveCharacterStyleClash and resolveParagraphStyleClash properties can be:
Rem idResolveStyleClash.idResolveClashAutoRename
Rem idResolveStyleClash.iduseExisting
Rem idResolveStyleClash.iduseNew
.ResolveCharacterStyleClash = idResolveStyleClash.idResolveClashUseExisting
.ResolveParagraphStyleClash = idResolveStyleClash.idResolveClashUseExisting
.UseTypographersQuotes = True
End With
The following script shows how to set Excel import preferences (for the complete script, see
ExcelImportPreferences):
With myInDesign.ExcelImportPreferences
Rem alignmentStyle property can be:
Rem AlignmentStyleOptions.centerAlign
Rem AlignmentStyleOptions.leftAlign
Rem AlignmentStyleOptions.rightAlign
.DecimalPlaces = 4
.PreserveGraphics = False
Rem Enter the range you want to import as "start cell:end cell".
.RangeName = "A1:B16"
.SheetIndex = 1
.SheetName = "pathpoints"
.ShowHiddenCells = False
Rem tableFormatting property can be:
Rem idTableFormattingOptions.idExcelFormattedTable
Rem idTableFormattingOptions.idExcelUnformattedTabbedText
Rem idTableFormattingOptions.idExcelUnformattedTable
.TableFormatting = idTableFormattingOptions.idExcelFormattedTable
.UseTypographersQuotes = True
.ViewName = ""
End With
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.
CHAPTER 5: Text and Type Exporting Text and Setting Text-Export Preferences 74
(We omitted the myGetBounds function from this listing; you can find it in “Creating a text frame” on
page 68,” or see the ExportTextFile tutorial script.)
Set myDocument = myInDesign.Documents.Item(1)
Set myPage = myDocument.Pages.Item(1)
Set myTextFrame = myPage.TextFrames.Item(1)
Rem Text export method parameters:
Rem Format as idExportFormat
Rem To As File
Rem [ShowingOptions As Boolean = False]
Rem
Rem Format parameter can be:
Rem idExportFormat.idInCopy
Rem idExportFormat.idInCopyCS2Story
Rem idExportFormat.idRTF
Rem idExportFormat.idTaggedText
Rem idExportFormat.idTextType
Rem
Rem Export the story as text. You'll have to fill in a valid file path on your system.
myTextFrame.ParentStory.Export idExportFormat.idTextType, "C:\test.txt"
The following example shows how to export a specific range of text. (We omitted the myGetBounds
function from this listing; you can find it in “Creating a text frame” on page 68,” or see the ExportTextRange
tutorial script.)
Set myDocument = myInDesign.Documents.Item(1)
Set myPage = myDocument.Pages.Item(1)
Set myTextFrame = myPage.TextFrames.Item(1)
Set myStory = myTextFrame.ParentStory
Set myStartCharacter = myStory.Paragraphs.Item(1).Characters.Item(1)
Set myEndCharacter = myStory.Paragraphs.Item(1).Characters.Item(-1)
Set myText = myTextFrame.ParentStory.Texts.ItemByRange(myStartCharacter,
myEndCharacter).Item(1)
Rem Text export method parameters:
Rem Format as idExportFormat
Rem To As File
Rem [ShowingOptions As Boolean = False]
Rem
Rem Format parameter can be:
Rem idExportFormat.idInCopy
Rem idExportFormat.idInCopyCS2Story
Rem idExportFormat.idRTF
Rem idExportFormat.idTaggedText
Rem idExportFormat.idTextType
Rem
Rem Export the text range. You'll have to fill in a valid file path on your system.
myText.Export idExportFormat.idTextType, "C:\test.txt"
To specify the export options for the specific type of text file youre exporting, use the corresponding
export preferences object. The following script sets text-export preferences (for the complete script, see
TextExportPreferences):
With myInDesign.TextExportPreferences
Rem Options for characterSet: idTextExportCharacterSet
.CharacterSet = idTextExportCharacterSet.idUTF8
Rem platform options: idImportPlatform
.Platform = idImportPlatform.idPC
End With
CHAPTER 5: Text and Type Exporting Text and Setting Text-Export Preferences 75
The following script sets tagged text export preferences (for the complete script, see
TaggedTextExportPreferences):
Set myInDesign = CreateObject("InDesign.Application")
With myInDesign.TaggedTextExportPreferences
Rem Options for characterSet:
Rem idTagTextExportCharacterSet.idAnsi
Rem idTagTextExportCharacterSet.idASCII
Rem idTagTextExportCharacterSet.idGB18030
Rem idTagTextExportCharacterSet.idKSC5601
Rem idTagTextExportCharacterSet.idShiftJIS
Rem idTagTextExportCharacterSet.idUnicode
.CharacterSet = idTagTextExportCharacterSet.idUnicode
Rem tagForm options:
Rem idTagTextForm.idAbbreviated
Rem idTagTextForm.idVerbose
.TagForm = idTagTextForm.idVerbose
End With
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. The following script demonstrates the former approach. (We omitted the myGetBounds
function from this listing; you can find it in “Creating a text frame” on page 68,” or see the ExportAllText
tutorial script.) For any format other than text only, the latter method can become quite complex.
If myInDesign.Documents.Count <> 0 Then
If myInDesign.Documents.Item(1).Stories.Count <> 0 Then
myExportAllText myInDesign, myInDesign.Documents.Item(1).Name
End If
End If
Here is the ExportAllText function referred to in the preceding fragment:
CHAPTER 5: Text and Type Exporting Text and Setting Text-Export Preferences 76
Function myExportAllText(myInDesign, myDocumentName)
mySeparatorString = "----------------------------------------" & vbCr
Rem If you want to add a separator line between stories,
Rem set myAddSeparator to true.
Set myNewDocument = myInDesign.Documents.Add
Set myDocument = myInDesign.Documents.Item(myDocumentName)
Set myTextFrame = myNewDocument.Pages.Item(1).TextFrames.Add
myTextFrame.geometricBounds = myGetBounds(myNewDocument,
myNewDocument.Pages.Item(1))
Set myNewStory = myTextFrame.ParentStory
For myCounter = 1 To myDocument.Stories.Count
Set myStory = myDocument.Stories.Item(myCounter)
myStory.texts.item(1).duplicate idLocationOptions.idAfter,
myNewStory.InsertionPoints.Item(1)
Rem If the text did not end with a return, enter a return
Rem to keep the stories from running together.
If myCounter <> myDocument.Stories.Count Then
If myNewStory.Characters.Item(-1).Contents <> vbCr Then
myNewStory.InsertionPoints.Item(-1).Contents = vbCr
End If
If myAddSeparator = True Then
myNewStory.InsertionPoints.Item(-1).Contents = mySeparatorString
End If
End If
Next
myNewStory.Export idExportFormat.idTaggedText, "c:\test.txt"
myNewDocument.Close idSaveOptions.idNo
End Function
Do not assume that you are limited to exporting text using existing export filters. Because VBScript can
write text files to disk, you can have your script traverse the text in a document and export it in any order
you like, using whatever text mark-up scheme you prefer. Here is a very simple example that shows how to
export InDesign text as HTML. (We omitted the myGetBounds function from this listing; you can find it in
“Creating a text frame” on page 68,” or see the ExportHTML tutorial script.)
Set myDocument = myInDesign.Documents.Item(1)
Rem Use the myStyleToTagMapping dictionary to set
Rem up your paragraph style to tag mapping.
Set myStyleToTagMapping = CreateObject("Scripting.Dictionary")
Rem For each style to tag mapping, add a new item to the dictionary.
Rem End of style to tag mapping.
If myDocument.Stories.Count <> 0 Then
Rem Open a new text file.
Set myDialog = CreateObject("UserAccounts.CommonDialog")
myDialog.Filter = "HTML Files|*.html|All Files|*.*"
myDialog.FilterIndex = 1
myDialog.InitialDir = "C:\"
myResult = myDialog.ShowOpen
Rem If the user clicked the Cancel button, the result is null.
If myResult = True Then
myTextFileName = myDialog.FileName
Set myFileSystemObject = CreateObject("Scripting.FileSystemObject")
Set myTextFile = myFileSystemObject.CreateTextFile(myTextFileName)
For myCounter = 1 To myInDesign.Documents.Item(1).Stories.Count
Set myStory = myDocument.Stories.Item(myCounter)
CHAPTER 5: Text and Type Exporting Text and Setting Text-Export Preferences 77
For myParagraphCounter = 1 To myStory.Paragraphs.Count
Set myParagraph = myStory.Paragraphs.Item(myParagraphCounter)
If myParagraph.Tables.Count = 0 Then
If myParagraph.TextStyleRanges.Count = 1 Then
Rem If the paragraph is a simple paragraph--no tables,
Rem no local formatting--then simply export the text
Rem of the pararaph with the appropriate tag.
myTag = myStyleToTagMapping.Item(myParagraph.
AppliedParagraphStyle.Name)
Rem If the tag comes back empty, map it to the basic paragraph tag.
If myTag = "" Then
myTag = "p"
End If
myStartTag = "<" & myTag & ">"
myEndTag = "</" & myTag & ">"
Rem If the paragraph is not the last paragraph in the story,
Rem omit the return character.
If myParagraph.Characters.Item(-1).Contents = vbCr Then
myString = myParagraph.Texts.ItemByRange(myParagraph.
Characters.Item(1), myParagraph.Characters.Item(-2)).
Item(1).Contents
Else
myString = myParagraph.Contents
End If
Rem Write the paragraphs' text to the text file.
myTextFile.WriteLine myStartTag & myString & myEndTag
Else
Rem Handle text style range export by iterating
Rem through the text style ranges in the paragraph..
For myRangeCounter = 1 To myParagraph.TextStyleRanges.Length
myTextStyleRange = myParagraph.TextStyleRanges.Item
(myRangeCounter)
If myTextStyleRange.Characters.Item(-1) = vbCr Then
myString = myTextStyleRange.Texts.ItemByRange
(myTextStyleRange.Characters.Item(1),
myTextStyleRange.Characters.Item(-2)).Item(1).Contents
Else
myString = myTextStyleRange.Contents
End If
Select Case myTextStyleRange.FontStyle
Case "Bold":
myString = "<b>" & myString & "</b>"
Case "Italic":
myString = "<i>" & myString & "</i>"
End Select
myTextFile.write myString
Next
myTextFile.write vbCr
End If
Else
Rem Handle table export (assumes that there is
Rem only one table per paragraph,
Rem and that the table is in the paragraph by itself).
Set myTable = myParagraph.Tables.Item(1)
myTextFile.write "<table border = 1>"
For myRowCounter = 1 To myTable.Rows.Count
myTextFile.write "<tr>"
For myColumnCounter = 1 To myTable.Columns.Count
If myRowCounter = 1 Then
myString = "<th>" & myTable.Rows.Item(myRowCounter).
CHAPTER 5: Text and Type Understanding Text Objects 78
Cells.Item(myColumnCounter).Texts.Item(1).Contents &
"</th>"
Else
myString = "<td>" & myTable.Rows.Item(myRowCounter).
Cells.Item(myColumnCounter).Texts.Item(1).Contents &
"</td>"
End If
myTextFile.write myString
Next
myTextFile.WriteLine "</tr>"
Next
myTextFile.WriteLine "</table>"
End If
Next
Rem Close the text file.
myTextFile.Close
Next
End If
End If
Here is the myFindTag function referred to in the above script:
function myFindTag (myStyleName, myStyleToTagMapping){
var myTag = "";
var myDone = false;
var myCounter = 0;
do{
if(myStyleToTagMapping[myCounter][0] == myStyleName){
myTag = myStyleToTagMapping[myCounter][1];
break;
}
myCounter ++;
} while((myDone == false)||(myCounter < myStyleToTagMapping.length))
return myTag;
}
Understanding Text Objects
The following diagram shows a view of InDesigns text object model. As you can see, there are two main
types of text object: layout objects (text frames) and text-stream objects (for example, stories, insertion
points, characters, and words):
CHAPTER 5: Text and Type Understanding Text Objects 79
There are many ways to get a reference to a given text object. The following diagram shows a few ways to
refer to the first character in the first text frame of the first page of a new document:
For any text stream object, the parent of the object is the story containing the object. To get a reference to
the text frame (or text frames) containing the text object, use the ParentTextFrames property.
story
insertion points
characters
words
lines
paragraphs
text columns
text style ranges
texts
text frame
insertion points
characters
words
lines
paragraphs
text columns
text style ranges
texts
text containers
document
notes
notes
document
pages.item(0)
textFrames.item(0)
characters.item(0)
stories.item(0)
characters.item(0)
textFrames.item(0)
paragraphs.item(0)
characters.item(0)
stories.item(0)
paragraphs.item(0)
characters.item(0)
CHAPTER 5: Text and Type Understanding Text Objects 80
For a text frame, the parent of the text frame usually is the page or spread containing the text frame. If the
text frame is inside a group or was pasted inside another page item, the parent of the text frame is the
containing page item. If the text frame was converted to an anchored frame, the parent of the text frame
is the character containing the anchored frame.
Working with text selections
Text-related scripts often act on a text selection. The following script demonstrates a way to determine
whether the current selection is a text selection. Unlike many of the other sample scripts, this script does
not actually do anything; it simply presents a selection-filtering routine that you can use in your own
scripts (for the complete script, see TextSelection).
Set myInDesign = CreateObject("InDesign.Application")
If myInDesign.Documents.Count <> 0 Then
Rem If the selection contains more than one item, the selection
Rem is not text selected with the Type tool.
If myInDesign.Selection.Count = 1 Then
Select Case TypeName(myInDesign.Selection.Item(1))
Case "InsertionPoint", "Character", "Word", "TextStyleRange",
"Line", "Paragraph", "TextColumn", "Text"
MsgBox "The selection is a text object."
Rem A real script would now act on the text object
Rem or pass it on to a function.
Case "TextFrame"
Rem In addition to checking for the above text objects, we can
Rem also continue if the selection is a text frame selected with
Rem the Selection tool or the Direct Selection tool.
Rem If the selection is a text frame, you get a reference to the
Rem text in the text frame and then pass it along to a function.
Rem Set myText = myInDesign.Selection.Item(1).Texts.Item(1)
MsgBox "The selected object is a text frame."
Case Else
MsgBox "The selected object is not a text object.
Select some text and try again."
End Select
Else
MsgBox "Please select some text and try again."
End If
Else
MsgBox "No documents are open. Please open a document,
select some text, and try again."
End If
Moving and copying text
You can move a text object to another location in text using the move method. To copy the text, use the
duplicate method (whose arguments are identical to the move method). The following script fragment
shows how it works (for the complete script, see MoveText):
CHAPTER 5: Text and Type Understanding Text Objects 81
Set myDocument = myInDesign.Documents.Item(1)
Set myPage = myDocument.Pages.Item(1)
Rem Set the bounds live area of the page.
myBounds = myGetBounds(myDocument, myDocument.Pages.Item(1))
myX1 = myBounds(1)
myY1 = myBounds(0)
myX2 = myBounds(3)
myY2 = myBounds(2)
myWidth = myX2 - myX1
myHeight = myY2 - myY1
Rem Create a series of text frames.
Set myTextFrameA = myPage.TextFrames.Add
myTextFrameA.geometricBounds = Array(myY1, myX1, myY1 + (myHeight / 2), myX1 + (myWidth
/ 2))
myTextFrameA.Contents = "Before." & vbCr
Set myTextFrameB = myPage.TextFrames.Add
myTextFrameB.geometricBounds = Array(myY1, myX1 + (myWidth / 2), myY1 + (myHeight / 2),
myX2)
myTextFrameB.Contents = "After." & vbCr
Set myTextFrameC = myPage.TextFrames.Add
myTextFrameC.geometricBounds = Array(myY1 + (myHeight / 2), myX1, myY2, myX1 + (myWidth
/ 2))
myTextFrameC.Contents = "Between words." & vbCr
Set myTextFrameD = myPage.TextFrames.Add
myTextFrameD.geometricBounds = Array(myY1 + (myHeight / 2), myX1 + (myWidth / 2), myY2,
myX2)
myTextFrameD.Contents = "Text to move:" & vbCr & "WordA" & vbCr & "WordB" & vbCr &
"WordC" & vbCr
Rem Move WordC between the words in TextFrameC.
myTextFrameD.ParentStory.Paragraphs.Item(-1).Words.Item(1).Move
idLocationOptions.idBefore, myTextFrameC.ParentStory.Paragraphs.Item(1).Words.Item(2)
Rem Move WordB after the word in TextFrameB.
myTextFrameD.ParentStory.Paragraphs.Item(-2).Words.Item(1).Move
idLocationOptions.idAfter, myTextFrameB.ParentStory.Paragraphs.Item(1).Words.Item(1)
Rem Move WordA to before the word in TextFrameA.
myTextFrameD.ParentStory.Paragraphs.Item(-3).Words.Item(1).Move
idLocationOptions.idBefore, myTextFrameA.ParentStory.Paragraphs.Item(1).Words.Item(1)
Rem Note that moving text removes it from its original location.
When you want to transfer formatted text from one document to another, you also can use the move
method. Using the move or duplicate method is better than using copy and paste; to use copy and paste,
you must make the document visible and select the text you want to copy. Using move or duplicate is
much faster and more robust. The following script shows how to move text from one document to another
using move and duplicate. (We omitted the myGetBounds function from this listing; you can find it in
“Creating a text frame” on page 68,” or see the MoveTextBetweenDocuments tutorial script.)
CHAPTER 5: Text and Type Understanding Text Objects 82
Rem Create the source document
Set mySourceDocument = myInDesign.Documents.Add
Set mySourcePage = mySourceDocument.Pages.Item(1)
Set mySourceTextFrame = mySourcePage.TextFrames.Add
mySourceTextFrame.geometricBounds = myGetBounds(mySourceDocument, mySourcePage)
mySourceTextFrame.Contents = "This is the source text." & vbCr & "This text is not the
source text."
Set mySourceParagraph = mySourceTextFrame.ParentStory.Paragraphs.Item(1)
mySourceParagraph.PointSize = 24
Rem Create the target document.
Set myTargetDocument = myInDesign.Documents.Add
Set myTargetPage = myTargetDocument.Pages.Item(1)
Set myTargetTextFrame = myTargetPage.TextFrames.Add
myTargetTextFrame.GeometricBounds = myGetBounds(myTargetDocument, myTargetPage)
myTargetTextFrame.Contents = "This is the target text. Insert the source text before
this paragraph." & vbCr
Rem Move the text from the source document to the target document.
Rem This deletes the text from the source document.
mySourceParagraph.Move idLocationOptions.idBefore,
myTargetTextFrame.InsertionPoints.Item(1)
Rem To duplicate (rather than move) the text, use the following:
Rem mySourceParagraph.Duplicate idLocationOptions.idBefore,
myTargetTextFrame.InsertionPoints.Item(1)
When you need to copy and paste text, you can use the copy method of the application. You will need to
select the text before you copy. Again, you should use copy and paste only as a last resort; other
approaches are faster, less fragile, and do not depend on the document being visible. (We omitted the
myGetBounds function from this listing; you can find it in “Creating a text frame” on page 68,” o r s e e th e
CopyPasteText tutorial script.)
Set myDocumentA = myInDesign.Documents.Add
Set myPageA = myDocumentA.Pages.Item(1)
Set myTextFrameA = myPageA.TextFrames.Add
myTextFrameA.GeometricBounds = myGetBounds(myDocumentA, myPageA)
myTextFrameA.Contents = "Example text." & vbCr
Set myDocumentB = myInDesign.Documents.Add
Set myPageB = myDocumentB.Pages.Item(1)
Set myTextFrameB = myPageB.TextFrames.Add
myTextFrameB.GeometricBounds = myGetBounds(myDocumentB, myPageB)
Rem Make document A the active document.
myInDesign.ActiveDocument = myDocumentA
Rem Select the text.
myInDesign.Select myTextFrameA.ParentStory.Texts.Item(1)
myInDesign.Copy
Rem Make document B the active document.
myInDesign.ActiveDocument = myDocumentB
Rem Select the insertion point at which you want to paste the text.
myInDesign.Select myTextFrameB.ParentStory.InsertionPoints.Item(1)
myInDesign.Paste
One way to copy unformatted text from one text object to another is to get the contents property of a
text object, then use that string to set the contents property of another text object. The following script
shows how to do this (for the complete script, see CopyUnformattedText):
CHAPTER 5: Text and Type Understanding Text Objects 83
Set myDocument = myInDesign.Documents.Item(1)
Set myPage = myDocument.Pages.Item(1)
Set myTextFrameA = myPage.TextFrames.Add
myTextFrameA.geometricBounds = Array(72, 72, 144, 288)
myTextFrameA.Contents = "This is a formatted string."
myTextFrameA.ParentStory.Texts.Item(1).FontStyle = "Bold"
Set myTextFrameB = myPage.TextFrames.Add
myTextFrameB.geometricBounds = Array(228, 72, 300, 288)
myTextFrameB.Contents = "This is the destination text frame. Text pasted here will
retain its formatting."
myTextFrameB.ParentStory.Texts.Item(1).FontStyle = "Italic"
Rem Copy from one frame to another using a simple copy.
myInDesign.Select myTextFrameA.Texts.Item(1)
myInDesign.Copy
myInDesign.Select myTextFrameB.ParentStory.InsertionPoints.Item(-1)
myInDesign.Paste
Rem Create another text frame on the active page.
Set myTextFrameC = myPage.TextFrames.Add
myTextFrameC.geometricBounds = Array(312, 72, 444, 288)
myTextFrameC.Contents = "Text copied here will take on the formatting of the existing
text."
myTextFrameC.ParentStory.Texts.Item(1).FontStyle = "Italic"
Rem Copy the unformatted string from text frame A to the end of text frame C (note
Rem that this doesn't really copy the text it replicates the text string from one
Rem text frame in another text frame):
myTextFrameC.ParentStory.InsertionPoints.Item(-1).Contents =
myTextFrameA.ParentStory.Texts.Item(1).Contents
Text objects and iteration
When your script moves, deletes, or adds text while iterating through a series of text objects, you can
easily end up with invalid text references. The following script demonstrates this problem. (We omitted the
myGetBounds function from this listing; you can find it in “Creating a text frame” on page 68,” o r s e e th e
TextIterationWrong tutorial script.)
Set myDocument = myInDesign.Documents.Item(1)
Set myStory = myDocument.Stories.Item(1)
Rem The following for loop cause an error.
For myParagraphCounter = 1 to myStory.Paragraphs.Count
If myStory.Paragraphs.Item(myParagraphCounter).Words.Item(1).contents = "Delete"
Then
myStory.Paragraphs.Item(myParagraphCounter).Delete
Else
myStory.Paragraphs.Item(myParagraphCounter).PointSize = 24
End If
Next
In the preceding example, some of the paragraphs are left unformatted. How does this happen? The loop
in the script iterates through the paragraphs from the first paragraph in the story to the last. As it does so,
it deletes paragraphs that begin with the word “Delete.When the script deletes the second paragraph,
the third paragraph moves up to take its place. When the loop counter reaches 3, the script processes the
paragraph that had been the fourth paragraph in the story; the original third paragraph is now the second
paragraph and is skipped.
To avoid this problem, iterate backward through the text objects, as shown in the following script. (We
omitted the myGetBounds function from this listing; you can find it in “Creating a text frame” on page 68,”
or see the TextIterationRight tutorial script.)
CHAPTER 5: Text and Type Working with Text Frames 84
Set myDocument = myInDesign.Documents.Item(1)
Set myStory = myDocument.Stories.Item(1)
Rem The following for loop will format all of the paragraphs by iterating
Rem backwards through the paragraphs in the story.
For myCounter = myStory.Paragraphs.Count To 1 Step -1
If myStory.Paragraphs.Item(myCounter).Words.Item(1).contents = "Delete" Then
myStory.Paragraphs.Item(myCounter).Delete
Else
myStory.Paragraphs.Item(myCounter).PointSize = 24
End If
Next
Working with Text Frames
In the previous sections of this chapter, we concentrated on working with text stream objects; in this
section, we focus on text frames, the page-layout items that contain text in an InDesign document.
The nextTextFrame and previousTextFrame properties of a text frame are the keys to linking (or
“threading”) text frames in InDesign scripting. These properties correspond to the in port and out port on
InDesign text frames, as shown in the following script fragment (for the complete script, see
Set myDocument = myInDesign.Documents.Item(1)
Set myPage = myDocument.Pages.Item(1)
Set myTextFrameA = myPage.TextFrames.Add
myTextFrameA.geometricBounds = Array(72, 72, 144, 144)
Set myTextFrameB = myPage.TextFrames.Add
myTextFrameB.geometricBounds = Array(228, 72, 300, 144)
Rem Add a page.
Set myNewPage = myDocument.Pages.Add
Rem Create another text frame on the new page.
Set myTextFrameC = myNewPage.TextFrames.Add
myTextFrameC.geometricBounds = Array(72, 72, 144, 144)
Rem Link TextFrameA to TextFrameB using the nextTextFrame property.
myTextFrameA.NextTextFrame = myTextFrameB
Rem Link TextFrameC to TextFrameB using the previousTextFrame property.
myTextFrameC.PreviousTextFrame = myTextFrameB
Rem Fill the text frames with placeholder text.
myTextFrameA.Contents = idTextFrameContents.idPlaceholderText
The following example script shows how to unlink text frames (for the complete script, see
Rem Given two linked text frames on page 1...
Set myDocument = myInDesign.Documents.Item(1)
Set myPage = myDocument.Pages.Item(1)
Set myTextFrameA = myPage.TextFrames.Item(-1)
Rem Unlink text frame A.
myTextFrameA.NextTextFrame = Nothing
CHAPTER 5: Text and Type Working with Text Frames 85
Removing a frame from a story
In InDesign, deleting a frame from a story does not delete the text in the frame, unless the frame is the only
frame in the story. The following script fragment shows how to delete a frame and the text it contains from
a story without disturbing the other frames in the story (for the complete script, see BreakFrame):
ReDim myObjectList(0)
Rem Script does nothing if no documents are open or if no objects are selected.
If myInDesign.Documents.Count <> 0 Then
If myInDesign.Selection.Count <> 0 Then
Rem Process the objects in the selection to create a list of
Rem qualifying objects (text frames).
For myCounter = 1 To myInDesign.Selection.Count
Select Case TypeName(myInDesign.Selection.Item(myCounter))
Case "TextFrame":
If Not (IsEmpty(myObjectList(0))) Then
ReDim Preserve myObjectList(UBound(myObjectList) + 1)
End If
Set myObjectList(UBound(myObjectList)) =
myInDesign.Selection.Item(myCounter)
Case "InsertionPoint", "Character", "Word", "TextStyleRange", "Line",
"Paragraph", "TextColumn", "Text":
If Not (IsEmpty(myObjectList(0))) Then
ReDim Preserve myObjectList(UBound(myObjectList) + 1)
End If
Set myObjectList(UBound(myObjectList)) =
myInDesign.Selection.Item(myCounter).ParentTextFrames.Item(1)
End Select
Next
Rem If the object list is not empty, pass it on to the function
Rem that does the real work.
If Not (IsEmpty(myObjectList(0))) Then
myBreakFrames myObjectList
End If
End If
End If
Here is the myBreakFrames function referred to in the preceding script.
CHAPTER 5: Text and Type Working with Text Frames 86
Function myBreakFrames(myObjectList)
For myCounter = UBound(myObjectList) To 0 Step -1
myBreakOutFrame myObjectList(myCounter)
Next
End Function
Function myBreakFrame(myTextFrame)
myProcessFrame = vbYes
If (TypeName(myTextFrame.NextTextFrame) <> "Nothing") Or
(TypeName(myTextFrame.PreviousTextFrame) <> "Nothing") Then
If myTextFrame.ParentStory.Tables.Count <> 0 Then
myProcessFrame = MsgBox("This story contains tables. If the text frame you
are trying to remove from the story contains a table, the results might not be
what you expect. Do you want to continue?", vbYesNo)
End If
If myProcessFrame = vbYes Then
Set myNewFrame = myTextFrame.Duplicate
If myTextFrame.Contents <> "" Then
myTextFrame.Texts.Item(1).Delete
End If
myTextFrame.Delete
End If
End If
End Function
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):
Rem Get the first item in the selection.
Set myDocument = myInDesign.Documents.Item(1)
Set myPage = myDocument.Pages.Item(1)
Set myTextFrame = myPage.TextFrames.Item(1)
Set myStory = myTextFrame.ParentStory
Rem If the text frame is the only text frame in the story, do nothing.
If myStory.TextContainers.Count > 1 Then
Rem Splitting the story is a two-step process: first, duplicate
Rem the text frames, second, delete the original text frames.
mySplitStory myStory
myRemoveFrames myStory
End If
Here is the mySplitStory function referred to in the preceding script:
Function mySplitStory(myStory)
Rem Duplicate each text frame in the story.
For myCounter = myStory.TextContainers.Count To 1 Step -1
Set myTextFrame = myStory.TextContainers.Item(myCounter)
myTextFrame.Duplicate
Next
End Function
Function myRemoveFrames(myStory)
Rem Remove each text frame in the story.
RemIterate backwards to avoid invalid references.
For myCounter = myStory.TextContainers.Count To 1 Step -1
myStory.TextContainers.Item(myCounter).Delete
Next
End Function
CHAPTER 5: Text and Type Working with Text Frames 87
Creating an anchored frame
To create an anchored frame (also known as an inline frame), you can create a text frame (or rectangle,
oval, polygon, or graphic line) at a specific location in text (usually an insertion point). The following script
fragment shows an example (for the complete script, see AnchoredFrame):
Set myDocument = myInDesign.Documents.Item(1)
Set myPage = myDocument.Pages.Item(1)
set myTextFrame = myPage.TextFrames.Item(1)
Set myInsertionPoint = myTextFrame.Paragraphs.Item(1).InsertionPoints.Item(1)
Set myInlineFrame = myInsertionPoint.TextFrames.Add
Rem Recompose the text to make sure that getting the
Rem geometric bounds of the inline graphic will work.
myTextFrame.Texts.Item(1).Recompose
Rem Get the geometric bounds of the inline frame.
myBounds = myInlineFrame.GeometricBounds
Rem Set the width and height of the inline frame. In this example, we'll
Rem make the frame 24 points tall by 72 points wide.
myArray = Array(myBounds(0), myBounds(1), myBounds(0) + 24, myBounds(1) + 72)
myInlineFrame.GeometricBounds = myArray
myInlineFrame.Contents = "This is an inline frame."
Set myInsertionPoint = myTextFrame.Paragraphs.Item(2).InsertionPoints.Item(1)
Set myAnchoredFrame = myInsertionPoint.TextFrames.Add
Rem Recompose the text to make sure that getting the
Rem geometric bounds of the inline graphic will work.
myTextFrame.Texts.Item(1).Recompose
Rem Get the geometric bounds of the inline frame.
myBounds = myAnchoredFrame.GeometricBounds
Rem Set the width and height of the inline frame. In this example, we'll
Rem make the frame 24 points tall by 72 points wide.
myArray = Array(myBounds(0), myBounds(1), myBounds(0) + 24, myBounds(1) + 72)
myAnchoredFrame.GeometricBounds = myArray
myAnchoredFrame.Contents = "This is an anchored frame."
With myAnchoredFrame.AnchoredObjectSettings
.AnchoredPosition = idAnchorPosition.idAnchored
.AnchorPoint = idAnchorPoint.idTopLeftAnchor
.HorizontalReferencePoint = idAnchoredRelativeTo.idAnchorLocation
.HorizontalAlignment = idHorizontalAlignment.idLeftAlign
.AnchorXoffset = 72
.VerticalReferencePoint = idVerticallyRelativeTo.idLineBaseline
.AnchorYoffset = 24
.AnchorSpaceAbove = 24
End With
Fitting text frames to content
The following example script shows how to set rules on a text frame to determine how it grows when the
user inputs text (for the complete script, see PersistedTextFrameFill):
CHAPTER 5: Text and Type Formatting Text 88
Set myDocument = myInDesign.Documents.item(1)
Set myTextFrame = myDocument.Pages.item(1).TextFrames.item(4)
REM Now add text at the end of the text frame.
myTextFrame.InsertionPoints.item(-1).Contents = vbCr&"This is some overset text"
MsgBox("The last paragraph in this alert should be ""This is some overset text"". Is
it?" & _
vbCr&myTextFrame.Contents)
MsgBox("The last paragraph in this alert should be ""This is some overset text"". Is
it?" & _
vbCr&myTextFrame.ParentStory.Contents)
Set myTextFrame2 = myDocument.Pages.item(1).TextFrames.item(3)
REM Set auto size dimension of the text frame
with myTextFrame2.TextFramePreferences
.AutoSizingDimension=idAutoSizingDimension.idHEIGHTANDWIDTHPROPORTIONALLY
End With
REM Now add text at the end of the text frame.
myTextFrame2.InsertionPoints.item(-1).Contents = vbCr&"This is some overset text"
Set myTextFrame3 = myDocument.Pages.item(1).TextFrames.item(2)
REM Set auto size dimension of the text frame
REM useMinimumHeightForAutoSizing and useNoLineBreaksForAutoSizing
with myTextFrame3.TextFramePreferences
.AutoSizingDimension=idAutoSizingDimension.idHEIGHTONLY
.UseMinimumHeightForAutoSizing=true
.UseNoLineBreaksForAutoSizing=true
End With
REM Now add text at the end of the text frame.
myTextFrame3.InsertionPoints.item(-1).Contents = vbCr&"This is some overset text"
Set myTextFrame4 = myDocument.Pages.item(1).TextFrames.item(1)
REM Set auto size dimension of the text frame and autoSizingReferencePoint
with myTextFrame4.TextFramePreferences
.AutoSizingDimension=idAutoSizingDimension.idWIDTHONLY
.AutoSizingReferencePoint=idAutoSizingReferencePoint.idTOPLEFTPOSITION
End With
REM Now add text at the end of the text frame.
myTextFrame4.InsertionPoints.item(-1).Contents = vbCr&"This is some overset text"
Formatting Text
In the previous sections of this chapter, we added text to a document, linked text frames, and worked with
stories and text objects. In this section, we apply formatting to text. All the typesetting capabilities of
InDesign are available to scripting.
Setting text defaults
You can set text defaults for both the application and each document. Text defaults for the application
determine the text defaults in all new documents; text defaults for a document set the formatting of all
new text objects in that document. (For the complete script, see TextDefaults.)
CHAPTER 5: Text and Type Formatting Text 89
With myInDesign.TextDefaults
.AlignToBaseline = True
Rem Because the font might not be available, it's usually best
Rem to trap errors using "On Error Resume Next" error handling.
Rem Fill in the name of a font on your system.
Err.Clear
On Error Resume Next
.AppliedFont = myInDesign.Fonts.Item("Minion Pro")
If Err.Number <> 0 Then
Err.Clear
End If
On Error GoTo 0
Rem Because the font style might not be available, it's usually best
Rem to trap errors using "On Error Resume Next" error handling.
Err.Clear
On Error Resume Next
.FontStyle = "Regular"
If Err.Number <> 0 Then
Err.Clear
End If
On Error GoTo 0
Rem Because the language might not be available, it's usually best
Rem to trap errors using "On Error Resume Next" error handling.
Err.Clear
On Error Resume Next
.AppliedLanguage = "English: USA"
If Err.Number <> 0 Then
Err.Clear
End If
On Error GoTo 0
.BalanceRaggedLines = False
.BaselineShift = 0
.Capitalization = idCapitalization.idNormal
.Composer = "Adobe Paragraph Composer"
.DesiredGlyphScaling = 100
.DesiredLetterSpacing = 0
.DesiredWordSpacing = 100
.DropCapCharacters = 0
If .DropCapCharacters <> 0 Then
.DropCapLines = 3
On Error Resume Next
.DropCapStyle = myInDesign.CharacterStyles.Item("myDropCap")
If Err.Number <> 0 Then
Err.Clear
End If
On Error GoTo 0
End If
On Error Resume Next
.FillColor = myInDesign.Colors.Item("Black")
If Err.Number <> 0 Then
Err.Clear
End If
On Error GoTo 0
.FillTint = 100
.FirstLineIndent = 14
.GridAlignFirstLineOnly = False
.HorizontalScale = 100
.HyphenateAfterFirst = 3
.HyphenateBeforeLast = 4
CHAPTER 5: Text and Type Formatting Text 90
.HyphenateCapitalizedWords = False
.HyphenateWordsLongerThan = 5
.Hyphenation = True
.HyphenationZone = 36
.HyphenWeight = 9
.Justification = idJustification.idLeftAlign
.KeepAllLinesTogether = False
.KeepLinesTogether = True
.KeepFirstLines = 2
.KeepLastLines = 2
.KeepWithNext = 0
.KerningMethod = "Optical"
.LeftIndent = 0
.Ligatures = True
.MaximumGlyphScaling = 100
.MaximumLetterSpacing = 0
.MaximumWordSpacing = 160
.MinimumGlyphScaling = 100
.MinimumLetterSpacing = 0
.MinimumWordSpacing = 80
.NoBreak = False
.OTFContextualAlternate = True
.OTFDiscretionaryLigature = True
.OTFFigureStyle = idOTFFigureStyle.idProportionalOldstyle
.OTFFraction = True
.OTFHistorical = True
.OTFOrdinal = False
.OTFSlashedZero = True
.OTFSwash = False
.OTFTitling = False
.OverprintFill = False
.OverprintStroke = False
.PointSize = 11
.Position = idPosition.idNormal
.RightIndent = 0
.RuleAbove = False
If .RuleAbove = True Then
On Error Resume Next
.RuleAboveColor = myInDesign.Colors.Item("Black")
If Err.Number <> 0 Then
Err.Clear
End If
On Error GoTo 0
On Error Resume Next
.RuleAboveGapColor = myInDesign.Swatches.Item("None")
If Err.Number <> 0 Then
Err.Clear
End If
On Error GoTo 0
.RuleAboveGapOverprint = False
.RuleAboveGapTint = 100
.RuleAboveLeftIndent = 0
.RuleAboveLineWeight = 0.25
.RuleAboveOffset = 14
.RuleAboveOverprint = False
.RuleAboveRightIndent = 0
.RuleAboveTint = 100
On Error Resume Next
CHAPTER 5: Text and Type Formatting Text 91
.RuleAboveType = myInDesign.StrokeStyles.Item("Solid")
If Err.Number <> 0 Then
Err.Clear
End If
On Error GoTo 0
.RuleAboveWidth = idRuleWidth.idColumnWidth
End If
.RuleBelow = False
If .RuleBelow = True Then
On Error Resume Next
.RuleBelowColor = myInDesign.Colors.Item("Black")
If Err.Number <> 0 Then
Err.Clear
End If
On Error GoTo 0
On Error Resume Next
.RuleBelowGapColor = myInDesign.Swatches.Item("None")
If Err.Number <> 0 Then
Err.Clear
End If
On Error GoTo 0
.RuleBelowGapOverPrint = False
.RuleBelowGapTint = 100
.RuleBelowLeftIndent = 0
.RuleBelowLineWeight = 0.25
.RuleBelowOffset = 0
.RuleBelowOverPrint = False
.RuleBelowRightIndent = 0
.RuleBelowTint = 100
On Error Resume Next
.RuleBelowType = myInDesign.StrokeStyles.Item("Solid")
If Err.Number <> 0 Then
Err.Clear
End If
On Error GoTo 0
.RuleBelowWidth = idRuleWidth.idColumnWidth
End If
.SingleWordJustification = idSingleWordJustification.idLeftAlign
.Skew = 0
.SpaceAfter = 0
.SpaceBefore = 0
.StartParagraph = idStartParagraph.idAnywhere
.StrikeThru = False
If .StrikeThru = True Then
On Error Resume Next
.StrikeThroughColor = myInDesign.Colors.Item("Black")
If Err.Number <> 0 Then
Err.Clear
End If
On Error GoTo 0
On Error Resume Next
.StrikeThroughGapColor = myInDesign.Swatches.Item("None")
If Err.Number <> 0 Then
Err.Clear
End If
On Error GoTo 0
.StrikeThroughGapOverprint = False
.StrikeThroughGapTint = 100
.StrikeThroughOffset = 3
.StrikeThroughOverprint = False
CHAPTER 5: Text and Type Formatting Text 92
.StrikeThroughTint = 100
On Error Resume Next
.StrikeThroughType = myInDesign.StrokeStyles.Item("Solid")
If Err.Number <> 0 Then
Err.Clear
End If
On Error GoTo 0
.StrikeThroughWeight = 0.25
End If
On Error Resume Next
.StrokeColor = myInDesign.Swatches.Item("None")
If Err.Number <> 0 Then
Err.Clear
End If
On Error GoTo 0
.StrokeTint = 100
.StrokeWeight = 0
.Tracking = 0
.Underline = False
If .Underline = True Then
On Error Resume Next
.UnderlineColor = myInDesign.Colors.Item("Black")
If Err.Number <> 0 Then
Err.Clear
End If
On Error GoTo 0
On Error Resume Next
.UnderlineGapColor = myInDesign.Swatches.Item("None")
If Err.Number <> 0 Then
Err.Clear
End If
On Error GoTo 0
.UnderlineGapOverprint = False
.UnderlineGapTint = 100
.UnderlineOffset = 3
.UnderlineOverprint = False
.UnderlineTint = 100
On Error Resume Next
.UnderlineType = myInDesign.StrokeStyles.Item("Solid")
If Err.Number <> 0 Then
Err.Clear
End If
On Error GoTo 0
.UnderlineWeight = 0.25
End If
.VerticalScale = 100
End With
Working with fonts
The fonts collection of the InDesign application object contains all fonts accessible to InDesign. The fonts
collection of a document, by contrast, contains only those fonts used in the document. The fonts
collection of a document also contains any missing fonts—fonts used in the document that are not
accessible to InDesign. The following script shows the difference between application fonts and document
fonts. (We omitted the myGetBounds function here; for the complete script, see FontCollections.)
CHAPTER 5: Text and Type Formatting Text 93
Set myDocument = myInDesign.Documents.Item(1)
Set myPage = myDocument.Pages.Item(1)
Set myApplicationFonts = myInDesign.Fonts
myString = "Document Fonts:" & vbCr
For myCounter = 1 To myDocument.Fonts.Count
myString = myString & myDocument.Fonts.Item(myCounter).Name & vbCr
Next
myString = myString & vbCr & "Application Fonts:" & vbCr
For myCounter = 1 To myInDesign.Fonts.Count
myString = myString & myInDesign.Fonts.Item(myCounter) & vbCr
Next
Set myTextFrame = myPage.TextFrames.Item(1)
Set myStory = myTextFrame.ParentStory
myStory.Contents = myString
NOTE: Font names typically are of the form familyName<tab>fontStyle, where familyName is the name
of the font family, <tab> is a tab character, and fontStyle is the name of the font style. For example:
"Adobe Caslon Pro<tab>Semibold Italic"
Applying a font
To apply a local font change to a range of text, use the appliedFont property, as shown in the following
script fragment (from the ApplyFont tutorial script):
Rem Given a font name "myFontName" and a text object "myText"...
myText.AppliedFont = myInDesign.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 = myInDesign.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.
Even one insertion point features properties that affect the formatting of text—up to and including
properties of the paragraph containing the insertion point. The SetTextProperties tutorial script shows
how to set every property of a text object. A fragment of the script is shown below:
Set myDocument = myInDesign.Documents.Item(1)
Set myPage = myDocument.Pages.Item(1)
Set myStory = myDocument.Stories.Item(1)
Set myTextObject = myStory.Characters.Item(1)
myFontName = "Minion Pro" & vbTab & "Regular"
With myTextObject
.AlignToBaseline = False
.AppliedCharacterStyle = myDocument.CharacterStyles.Item("[None]")
On Error Resume Next
.AppliedFont = myInDesign.Fonts.Item(myFontName)
.FontStyle = "Regular"
If Err.Number <> 0 Then
Err.Clear
End If
On Error Goto 0
.AppliedLanguage = myInDesign.LanguagesWithVendors.Item("English: USA")
.AppliedNumberingList = myDocument.NumberingLists.Item("[Default]")
CHAPTER 5: Text and Type Formatting Text 94
.AppliedParagraphStyle = myDocument.ParagraphStyles.Item("[No Paragraph Style]")
.BalanceRaggedLines = idBalanceLinesStyle.idNoBalancing
.BaselineShift = 0
.BulletsAlignment = idListAlignment.idLeftAlign
.BulletsAndNumberingListType = idListType.idNoList
.BulletsCharacterStyle = myDocument.CharacterStyles.Item("[None]")
.BulletsTextAfter = "^t"
.Capitalization = idCapitalization.idNormal
.Composer = "Adobe Paragraph Composer"
.DesiredGlyphScaling = 100
.DesiredLetterSpacing = 0
.DesiredWordSpacing = 100
.DropCapCharacters = 0
.DropCapLines = 0
.DropCapStyle = myDocument.CharacterStyles.Item("[None]")
.DropcapDetail = 0
.FillColor = myDocument.Colors.Item("Black")
.FillTint = -1
.FirstLineIndent = 0
.GradientFillStart = Array(0, 0)
.GradientStrokeStart = Array(0, 0)
.GridAlignFirstLineOnly = False
.HorizontalScale = 100
.HyphenWeight = 5
.HyphenateAcrossColumns = True
.HyphenateAfterFirst = 2
.HyphenateBeforeLast = 2
.HyphenateCapitalizedWords = True
.HyphenateLastWord = True
.HyphenateWordsLongerThan = 5
.Hyphenation = True
.HyphenationZone = 3
.IgnoreEdgeAlignment = False
.Justification = idJustification.idLeftAlign
.KeepAllLinesTogether = False
.KeepFirstLines = 2
.KeepLastLines = 2
.KeepLinesTogether = False
.KeepRuleAboveInFrame = False
.KeepWithNext = 0
.KerningMethod = "Optical"
.LastLineIndent = 0
.LeftIndent = 0
.Ligatures = True
.MaximumGlyphScaling = 100
.MaximumLetterSpacing = 0
.MaximumWordSpacing = 133
.MinimumGlyphScaling = 100
.MinimumLetterSpacing = 0
.MinimumWordSpacing = 80
.NoBreak = False
.NumberingAlignment = idListAlignment.idLeftAlign
.NumberingApplyRestartPolicy = True
CHAPTER 5: Text and Type Formatting Text 95
.NumberingCharacterStyle = myDocument.CharacterStyles.Item("[None]")
.NumberingContinue = True
.NumberingExpression = "^#.^t"
.NumberingFormat = "1, 2, 3, 4..."
.NumberingLevel = 1
.NumberingStartAt = 1
.OTFContextualAlternate = True
.OTFDiscretionaryLigature = False
.OTFFigureStyle = idOTFFigureStyle.idProportionalLining
.OTFFraction = False
.OTFHistorical = False
.OTFLocale = True
.OTFMark = True
.OTFOrdinal = False
.OTFSlashedZero = False
.OTFStylisticSets = 0
.OTFSwash = False
.OTFTitling = False
.OverprintFill = False
.OverprintStroke = False
.PointSize = 12
.Position = idPosition.idNormal
.PositionalForm = idPositionalForms.idNone
.RightIndent = 0
.RuleAbove = False
.RuleAboveColor = "Text Color"
.RuleAboveGapColor = myDocument.Swatches.Item("None")
.RuleAboveGapOverprint = False
.RuleAboveGapTint = -1
.RuleAboveLeftIndent = 0
.RuleAboveLineWeight = 1
.RuleAboveOffset = 0
.RuleAboveOverprint = False
.RuleAboveRightIndent = 0
.RuleAboveTint = -1
.RuleAboveType = myDocument.StrokeStyles.Item("Solid")
.RuleAboveWidth = idRuleWidth.idColumnWidth
.RuleBelow = False
.RuleBelowColor = "Text Color"
.RuleBelowGapColor = myDocument.Swatches.Item("None")
.RuleBelowGapOverprint = False
.RuleBelowGapTint = -1
.RuleBelowLeftIndent = 0
.RuleBelowLineWeight = 1
.RuleBelowOffset = 0
.RuleBelowOverprint = False
.RuleBelowRightIndent = 0
.RuleBelowTint = -1
.RuleBelowType = myDocument.StrokeStyles.Item("Solid")
.RuleBelowWidth = idRuleWidth.idColumnWidth
.SingleWordJustification = idSingleWordJustification.idLeftAlign
.Skew = 0
.SpaceAfter = 0
.SpaceBefore = 0
.StartParagraph = idStartParagraph.idAnywhere
.StrikeThroughColor = "Text Color"
.StrikeThroughGapColor = myDocument.Swatches.Item("None")
.StrikeThroughGapOverprint = False
.StrikeThroughGapTint = -1
.StrikeThroughOffset = -9999
CHAPTER 5: Text and Type Formatting Text 96
.StrikeThroughOverprint = False
.StrikeThroughTint = -1
.StrikeThroughType = myDocument.StrokeStyles.Item("Solid")
.StrikeThroughWeight = -9999
.StrikeThru = False
.StrokeColor = myDocument.Swatches.Item("None")
.StrokeTint = -1
.StrokeWeight = 1
.Tracking = 0
.Underline = False
.UnderlineColor = "Text Color"
.UnderlineGapColor = myDocument.Swatches.Item("None")
.UnderlineGapOverprint = False
.UnderlineGapTint = -1
.UnderlineOffset = -9999
.UnderlineOverprint = False
.UnderlineTint = -1
.UnderlineType = myDocument.StrokeStyles.Item("Solid")
.UnderlineWeight = -9999
.VerticalScale = 100
End With
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):
Set myDocument = myInDesign.Documents.Item(1)
Set myStory = myDocument.Stories.Item(1)
Rem Apply a color to the fill of the text.
Set myText = myStory.Paragraphs.Item(1)
myText.FillColor = myDocument.Colors.Item("DGC1_446a")
Rem Use the itemByRange method to apply the color to the stroke of the text.
myText.StrokeColor = myDocument.Swatches.Item("DGC1_446b")
Set myText = myStory.Paragraphs.Item(2)
myText.FillColor = myDocument.Swatches.Item("DGC1_446b")
myText.StrokeColor = myDocument.Swatches.Item("DGC1_446a")
myText.StrokeWeight = 3
Creating and applying styles
While you can use scripting to apply local formatting—as in some of the examples earlier in this
chapter—you probably will want to use character and paragraph styles to format your text. Using styles
creates a link between the formatted text and the style, which makes it easier to redefine the style, collect
the text formatted with a given style, or find and/or change the text. Paragraph and character styles are
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):
CHAPTER 5: Text and Type Formatting Text 97
Set myDocument = myInDesign.Documents.Item(1)
Set myPage = myDocument.Pages.Item(1)
Set myTextFrame = myPage.TextFrames.Item(1)
Rem Create a color for use by one of the paragraph styles we'll create.
Set myColor = myAddColor(myDocument, "Red", idColorModel.idProcess,
Array(0, 100, 100, 0))
Rem Create a character style named "myCharacterStyle" if
Rem no style by that name already exists.
Set myCharacterStyle = myAddStyle(myDocument, "myCharacterStyle", 1)
Rem At this point, the variable myCharacterStyle contains a reference to a character
Rem style object, which you can now use to specify formatting.
myCharacterStyle.FillColor = myColor
Rem Create a paragraph style named "myParagraphStyle" if
Rem no style by that name already exists.
Set myParagraphStyle = myAddStyle(myDocument, "myParagraphStyle", 2)
Rem At this point, the variable myParagraphStyle contains a reference to a paragraph
Rem style object, which you can now use to specify formatting.
myTextFrame.ParentStory.Texts.Item(1).ApplyParagraphStyle myParagraphStyle, True
Set myStartCharacter = myTextFrame.ParentStory.Characters.Item(14)
Set myEndCharacter = myTextFrame.ParentStory.Characters.Item(55)
Set myText = myTextFrame.ParentStory.Texts.ItemByRange(myStartCharacter,
myEndCharacter)
myText.Item(1).ApplyCharacterStyle myCharacterStyle, True
Why use the applyParagraphStyle method instead of setting the appliedParagraphStyle property of
the text object? The applyParagraphStyle method gives the ability to override existing formatting;
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. If it does, trying to create a new style with the same name results in an
error.
Nested styles apply character-style formatting to a paragraph according to a pattern. The following script
fragment shows how to create a paragraph style containing nested styles (for the complete script, see
NestedStyles):
Set myDocument = myInDesign.Documents.Item(1)
Set myPage = myDocument.Pages.Item(1)
Set myParagraphStyle = myDocument.ParagraphStyles.Item("myParagraphStyle")
Rem At this point, the variable myParagraphStyle contains a reference to a paragraph
Rem style object, which you can now use to specify formatting.
Set myNestedStyle = myParagraphStyle.NestedStyles.Add
myNestedStyle.AppliedCharacterStyle =
myDocument.CharacterStyles.Item("myCharacterStyle")
myNestedStyle.Delimiter = "."
myNestedStyle.Inclusive = True
myNestedStyle.Repetition = 1
Rem Note that the story object does not have the ApplyParagraphStyle method.)
Set myText = myPage.TextFrames.Item(1).ParentStory.Texts.Item(1)
myText.ApplyParagraphStyle myParagraphStyle, True
Deleting a style
When you delete a style using the user interface, you can choose the way you want to format any text
tagged with that style. InDesign scripting works the same way, as shown in the following script fragment
(from the RemoveStyle tutorial script):
CHAPTER 5: Text and Type Finding and Changing Text 98
Set myDocument = myInDesign.Documents.Item(1)
Set myParagraphStyleA = myDocument.ParagraphStyles.Item("myParagraphStyleA")
Rem Delete the paragraph style myParagraphStyleA and replace with myParagraphStyleB.
myParagraphStyleA.Delete myDocument.ParagraphStyles.Item("myParagraphStyleB")
Importing paragraph and character styles
You can import character and paragraph styles from other InDesign documents, as shown in the following
script fragment (from the ImportTextStyles tutorial script):
Set myDocument = myInDesign.Documents.Item(1)
Set myPage = myDocument.Pages.Item(1)
Set myNewDocument = myInDesign.Documents.Add
Rem Import the styles from the saved document.
Rem ImportStyles parameters:
Rem Format as idImportFormat enumeration. Options for text styles are:
Rem idImportFormat.idParagraphStylesFormat
Rem idImportFormat.idCharacterStylesFormat
Rem idImportFormat.idTextStylesFormat
Rem From as string (file path)
Rem GlobalStrategy as idGlobalClashResolutionStrategy enumeration. Options are:
myNewDocument.ImportStyles idImportFormat.idTextStylesFormat, "c:\styles.indd",
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. InDesign has three ways of searching for text:
You can find text and/or text formatting and change it to other text and/or text formatting. This type
of find/change operation uses the findTextPreferences and changeTextPreferences objects to
specify parameters for the findText and changeText methods.
You can find text using regular expressions, or “grep.” This type of find/change operation uses the
findGrepPreferences and changeGrepPreferences objects to specify parameters for the findGrep
and changeGrep methods.
You can find specific glyphs (and their formatting) and replace them with other glyphs and formatting.
This type of find/change operation uses the findGlyphPreferences and changeGlyphPreferences
objects to specify parameters for the findGlyph and changeGlyph methods.
All the find/change methods take one optional parameter, ReverseOrder, which specifies the order in
which the results of the search are returned. If you are processing the results of a find or change operation
in a way that adds or removes text from a story, you might face the problem of invalid text references, as
discussed earlier in this chapter. In this case, you can either construct your loops to iterate backward
through the collection of returned text objects, or you can have the search operation return the results in
reverse order and then iterate through the collection normally.
CHAPTER 5: Text and Type Finding and Changing Text 99
Before you search for text, you probably will want to clear find and change preferences, to make sure the
settings from previous searches have no effect on your search. You also need to set some find/change
preferences to specify the text, formatting, regular expression, or glyph you want to find and/or change. A
typical find/change operation involves the following steps:
1. Clear the find/change preferences. Depending on the type of find/change operation, this can take one
of the following three forms:
Rem Find/Change text preferences
Set myInDesign = CreateObject("InDesign.Application")
myInDesign.FindTextPreferences = idNothingEnum.idNothing
myInDesign.ChangeTextPreferences = idNothingEnum.idNothing
Rem Find/Change grep preferences
Set myInDesign = CreateObject("InDesign.Application")
myInDesign.FindGrepPreferences = idNothingEnum.idNothing
myInDesign.ChangeGrepPreferences = idNothingEnum.idNothing
Rem Find/Change glyph preferences
Set myInDesign = CreateObject("InDesign.Application")
myInDesign.FindGlyphPreferences = idNothingEnum.idNothing
myInDesign.ChangeGlyphPreferences = idNothingEnum.idNothing
2. Set up search parameters.
3. Execute the find/change operation.
4. Clear find/change preferences again.
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. The findText method and its parameters are the same for all text objects. (For
the complete script, see FindText.)
Set myDocument = myInDesign.Documents.Item(1)
Rem Clear the find/change text preferences.
myInDesign.FindTextPreferences = idNothingEnum.idNothing
myInDesign.ChangeTextPreferences = idNothingEnum.idNothing
Rem Search the document for the string "text".
myInDesign.FindTextPreferences.FindWhat = "text"
Rem Set the find options.
myInDesign.FindChangeTextOptions.CaseSensitive = False
myInDesign.FindChangeTextOptions.IncludeFootnotes = False
myInDesign.FindChangeTextOptions.IncludeHiddenLayers = False
myInDesign.FindChangeTextOptions.IncludeLockedLayersForFind = False
myInDesign.FindChangeTextOptions.IncludeLockedStoriesForFind = False
myInDesign.FindChangeTextOptions.IncludeMasterPages = False
myInDesign.FindChangeTextOptions.WholeWord = False
Set myFoundItems = myInDesign.Documents.Item(1).FindText
MsgBox ("Found " & CStr(myFoundItems.Count) & " instances of the search string.")
Rem Clear the find/change text preferences after the search.
myInDesign.FindTextPreferences = idNothingEnum.idNothing
myInDesign.ChangeTextPreferences = idNothingEnum.idNothing
CHAPTER 5: Text and Type Finding and Changing Text 100
The following script fragment shows how to find a specified string of text and replace it with a different
string (for the complete script, see ChangeText):
Set myDocument = myInDesign.Documents.Item(1)
Rem Clear the find/change text preferences.
myInDesign.FindTextPreferences = idNothingEnum.idNothing
myInDesign.ChangeTextPreferences = idNothingEnum.idNothing
Rem Search the document for the string "copy" and replace with "text".
myInDesign.FindTextPreferences.FindWhat = "copy"
myInDesign.ChangeTextPreferences.ChangeTo = "text"
Rem Set the find options.
myInDesign.FindChangeTextOptions.CaseSensitive = False
myInDesign.FindChangeTextOptions.IncludeFootnotes = False
myInDesign.FindChangeTextOptions.IncludeHiddenLayers = False
myInDesign.FindChangeTextOptions.IncludeLockedLayersForFind = False
myInDesign.FindChangeTextOptions.IncludeLockedStoriesForFind = False
myInDesign.FindChangeTextOptions.IncludeMasterPages = False
myInDesign.FindChangeTextOptions.WholeWord = False
Set myFoundItems = myInDesign.Documents.Item(1).ChangeText
MsgBox ("Changed " & CStr(myFoundItems.Count) & " instances of the search string.")
Rem Clear the find/change text preferences.
myInDesign.FindTextPreferences = idNothingEnum.idNothing
myInDesign.ChangeTextPreferences = idNothingEnum.idNothing
Finding and changing text formatting
To find and change text formatting, you set other properties of the findTextPreferences and
changeTextPreferences objects, as shown in the script fragment below (from the
FindChangeFormatting tutorial script):
Rem Clear the find/change preferences.
myInDesign.FindTextPreferences = idNothingEnum.idNothing
myInDesign.ChangeTextPreferences = idNothingEnum.idNothing
Rem Set the find options.
myInDesign.FindChangeTextOptions.CaseSensitive = false
myInDesign.FindChangeTextOptions.IncludeFootnotes = false
myInDesign.FindChangeTextOptions.IncludeHiddenLayers = false
myInDesign.FindChangeTextOptions.IncludeLockedLayersForFind = false
myInDesign.FindChangeTextOptions.IncludeLockedStoriesForFind = false
myInDesign.FindChangeTextOptions.IncludeMasterPages = false
myInDesign.FindChangeTextOptions.WholeWord = false
Rem Search the document for the 24 point text and change it to 10 point text.
myInDesign.findTextPreferences.pointSize = 24
myInDesign.changeTextPreferences.pointSize = 10
myInDesign.documents.item(1).changeText
Rem Clear the find/change preferences after the search.
myInDesign.FindTextPreferences = idNothingEnum.idNothing
myInDesign.ChangeTextPreferences = idNothingEnum.idNothing
Using grep
InDesign supports regular expression find/change through the findGrep and changeGrep methods.
Regular-expression find/change also can find text with a specified format or replace the formatting of the
text with formatting specified in the properties of the changeGrepPreferences object. The following
script fragment shows how to use these methods and the related preferences objects (for the complete
script, see FindGrep):
CHAPTER 5: Text and Type Finding and Changing Text 101
Set myDocument = myInDesign.Documents.Item(1)
Rem Clear the find/change grep preferences.
myInDesign.FindGrepPreferences = idNothingEnum.idNothing
myInDesign.ChangeGrepPreferences = idNothingEnum.idNothing
Rem Set the find options.
myInDesign.FindChangeGrepOptions.IncludeFootnotes = False
myInDesign.FindChangeGrepOptions.IncludeHiddenLayers = False
myInDesign.FindChangeGrepOptions.IncludeLockedLayersForFind = False
myInDesign.FindChangeGrepOptions.IncludeLockedStoriesForFind = False
myInDesign.FindChangeGrepOptions.IncludeMasterPages = False
Rem Regular expression for finding an email address.
myInDesign.FindGrepPreferences.FindWhat = "(?i)[A-Z]*?@[A-Z]*?[.]..."
Rem Apply the change to 24-point text only.
myInDesign.FindGrepPreferences.PointSize = 24
myInDesign.ChangeGrepPreferences.Underline = True
myDocument.ChangeGrep
Rem Clear the find/change grep preferences after the search.
myInDesign.FindGrepPreferences = idNothingEnum.idNothing
myInDesign.ChangeGrepPreferences = idNothingEnum.idNothing
NOTE: The findChangeGrepOptions object lacks two properties of the findChangeTextOptions object:
wholeWord and caseSensitive. This is because you can set these options using the regular expression
string itself. Use (?i) to turn case sensitivity on and (?-i) to turn case sensitivity off. Use \> to match the
beginning of a word and \< to match the end of a word, or use \b to match a word boundary.
One handy use for grep find/change is to convert text mark-up (i.e., some form of tagging plain text with
formatting instructions) into InDesign formatted text. PageMaker paragraph tags (which are not the same
as PageMaker tagged-text format files) are an example of a simplified text mark-up scheme. In a text file
marked up using this scheme, paragraph style names appear at the start of a paragraph, as shown below:
<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
Set myInDesign = CreateObject("InDesign.Application")
Rem Access the active document.
Set myDocument = myInDesign.Documents.Item(1)
Set myStory = myDocument.Stories.Item(1)
Here is the myReadPMTags function referred to in the above script.
Set myDocument = myStory.Parent
Rem Reset the findGrepPreferences to ensure that previous settings
Rem do not affect the search.
myInDesign.FindGrepPreferences = idNothingEnum.idNothing
myInDesign.ChangeGrepPreferences = idNothingEnum.idNothing
Rem Find the tags.
myInDesign.FindGrepPreferences.findWhat = "(?i)^<\s*\w+\s*>"
Set myFoundItems = myStory.findGrep
If myFoundItems.Count <> 0 Then
Set myFoundTags = CreateObject("Scripting.Dictionary")
For myCounter = 1 To myFoundItems.Count
If Not (myFoundTags.Exists(myFoundItems.Item(myCounter).Contents)) Then
myFoundItems.Item(myCounter).Contents
CHAPTER 5: Text and Type Finding and Changing Text 102
End If
Next
Rem At this point, we have a list of tags to search for.
For Each myFoundTag In myFoundTags
myString = myFoundTag
Rem Find the tag using findWhat.
myInDesign.FindTextPreferences.findWhat = myString
Rem Extract the style name from the tag.
myStyleName = Mid(myString, 2, Len(myString) - 2)
Rem Create the style if it does not already exist.
Set myStyle = myAddStyle(myDocument, myStyleName)
Rem Apply the style to each instance of the tag.
myInDesign.ChangeTextPreferences.AppliedParagraphStyle = myStyle
myStory.ChangeText
Rem Reset the changeTextPreferences.
myInDesign.ChangeTextPreferences = idNothingEnum.idNothing
Rem Set the changeTo to an empty string.
myInDesign.ChangeTextPreferences.ChangeTo = ""
Rem Search to remove the tags.
myStory.ChangeText
Rem Reset the find/change preferences again.
myInDesign.ChangeTextPreferences = idNothingEnum.idNothing
Next
End If
myInDesign.FindGrepPreferences = idNothingEnum.idNothing
myInDesign.ChangeGrepPreferences = idNothingEnum.idNothing
End Function
Using glyph search
You can find and change individual characters in a specific font using the findGlyph and changeGlyph
methods and the associated findGlyphPreferences and changeGlyphPreferences objects. The
following scripts fragment shows how to find and change a glyph in an example document (for the
complete script, see FindChangeGlyph):
CHAPTER 5: Text and Type Working with Tables 103
Rem Clear the find/change glyph preferences.
myInDesign.FindGlyphPreferences = idNothingEnum.idNothing
myInDesign.ChangeGlyphPreferences = idNothingEnum.idNothing
Rem Set the find options.
myInDesign.FindChangeGrepOptions.IncludeFootnotes = False
myInDesign.FindChangeGrepOptions.IncludeHiddenLayers = False
myInDesign.FindChangeGrepOptions.IncludeLockedLayersForFind = False
myInDesign.FindChangeGrepOptions.IncludeLockedStoriesForFind = False
myInDesign.FindChangeGrepOptions.IncludeMasterPages = False
Rem You must provide a font that is used in the document for the
Rem AppliedFont property of the FindGlyphPreferences object.
myInDesign.FindGlyphPreferences.AppliedFont = myInDesign.Fonts.Item("Minion Pro" &
vbTab & "Regular")
Rem Provide the glyph ID, not the glyph Unicode value.
myInDesign.FindGlyphPreferences.GlyphID = 374
Rem The appliedFont of the changeGlyphPreferences object can be
Rem any font available to the application.
myInDesign.changeGlyphPreferences.AppliedFont = myInDesign.Fonts.Item("Times New
Roman" & vbTab & "Bold")
myInDesign.changeGlyphPreferences.GlyphID = 85
myInDesign.Documents.Item(1).ChangeGlyph
Rem Clear the find/change glyph preferences after the search.
myInDesign.FindGlyphPreferences = idNothingEnum.idNothing
myInDesign.ChangeGlyphPreferences = idNothingEnum.idNothing
Working with Tables
Tables can be created from existing text using the convertTextToTable method, or an empty table can
be created at any insertion point in a story. The following script fragment shows three different ways to
create a table (for the complete script, see MakeTable):
Set myDocument = myInDesign.Documents.Item(1)
Set myPage = myDocument.Pages.Item(1)
Set myTextFrame = myPage.TextFrames.Add
Rem Set the bounds of the text frame.
myTextFrame.GeometricBounds = myGetBounds(myDocument, myPage)
Rem Fill the text frame with placeholder text.
myString = "Table 1" & vbCr
myString = myString & "Column 1" & vbTab & "Column 2" & vbTab & "Column 3" & vbCr & "1a"
& vbTab & "1b" & vbTab & "1c" & vbCr & "2a" & vbTab & "2b" & vbTab & "2c" & vbCr & "3a" &
vbTab & "3b" & vbTab & "3c" & vbCr
myString = myString & "Table 2" & vbCr
myString = myString & "Column 1,Column 2,Column 3;1a,1b,1c;2a,2b,2c;3a,3b,3c" & vbCr
myString = myString & "Table 3" & vbCr
myTextFrame.Contents = myString
Set myStory = myTextFrame.ParentStory
Set myStartCharacter = myStory.Paragraphs.Item(7).Characters.Item(1)
Set myEndCharacter = myStory.Paragraphs.Item(7).Characters.Item(-2)
Set myText = myStory.Texts.ItemByRange(myStartCharacter, myEndCharacter).Item(1)
Rem The convertToTable method takes three parameters:
Rem [ColumnSeparator as string]
Rem [RowSeparator as string]
Rem [NumberOfColumns as integer] (only used if the ColumnSeparator
Rem and RowSeparator values are the same)
CHAPTER 5: Text and Type Working with Tables 104
Rem In the last paragraph in the story, columns are separated by commas
Rem and rows are separated by semicolons, so we provide those characters
Rem to the method as parameters.
Set myTable = myText.ConvertToTable(",", ";")
Set myStartCharacter = myStory.Paragraphs.Item(2).Characters.Item(1)
Set myEndCharacter = myStory.Paragraphs.Item(5).Characters.Item(-2)
Set myText = myStory.Texts.ItemByRange(myStartCharacter, myEndCharacter).Item(1)
Rem In the second through the fifth paragraphs, colums are separated by
Rem tabs and rows are separated by returns. These are the default delimiter
Rem parameters, so we don't need to provide them to the method.
Set myTable = myText.ConvertToTable
Rem You can also explicitly add a table--you don't have to convert text to a table.
Set myTable = myStory.InsertionPoints.Item(-1).Tables.Add
myTable.ColumnCount = 3
myTable.BodyRowCount = 3
The following script fragment shows how to merge table cells. (For the complete script, see
MergeTableCells.)
Set myDocument = myInDesign.Documents.Item(1)
Set myStory = myDocument.Stories.Item(1)
Set myTable = myStory.Tables.Item(1)
Rem Merge all of the cells in the first column.
myTable.Cells.Item(1).Merge myTable.Columns.Item(1).Cells.Item(-1)
Rem Convert column 2 into 2 cells (rather than 4).
myTable.Columns.Item(2).Cells.Item(-1).Merge myTable.Columns.Item(2).Cells.Item(-2)
myTable.Columns.Item(2).Cells.Item(1).Merge myTable.Columns.Item(2).Cells.Item(2)
Rem Merge the last two cells in row 1.
myTable.Rows.Item(1).Cells.Item(-1).Merge myTable.Rows.Item(1).Cells.Item(-1)
Rem Merge the last two cells in row 3.
myTable.Rows.Item(3).Cells.Item(-2).Merge myTable.Rows.Item(3).Cells.Item(-1)
The following script fragment shows how to split table cells. (For the complete script, see SplitTableCells.)
Set myDocument = myInDesign.Documents.Item(1)
Set myStory = myDocument.Stories.Item(1)
Set myTable = myStory.InsertionPoints.Item(-1).Tables.Add
myTable.ColumnCount = 1
myTable.BodyRowCount = 1
myArray = myGetBounds(myDocument, myDocument.Pages.Item(1))
myWidth = myArray(3) - myArray(1)
myTable.Columns.Item(1).Width = myWidth
myTable.Cells.Item(1).Split idHorizontalOrVertical.idHorizontal
myTable.Columns.Item(1).Split idHorizontalOrVertical.idVertical
myTable.Cells.Item(1).Split idHorizontalOrVertical.idVertical
myTable.Rows.Item(-1).Split idHorizontalOrVertical.idHorizontal
myTable.Cells.Item(-1).Split idHorizontalOrVertical.idVertical
For myRowCounter = 1 To myTable.Rows.Count
Set myRow = myTable.Rows.Item(myRowCounter)
For myCellCounter = 1 To myRow.Cells.Count
myString = "Row: " & myRowCounter & " Cell: " & myCellCounter
myRow.Cells.Item(myCellCounter).contents = myString
Next
Next
The following script fragment shows how to create header and footer rows in a table (for the complete
CHAPTER 5: Text and Type Working with Tables 105
Set myDocument = myInDesign.Documents.Item(1)
Set myPage = myDocument.Pages.Item(1)
Rem Create a text frame on page 1.
Set myTable = myDocument.Stories.Item(1).Tables.Item(1)
Rem Convert the first row to a header row.
Rem Convert the last row to a footer row.
myTable.Rows.Item(-1).RowType = idRowTypes.idFooterRow
The following script fragment shows how to apply formatting to a table (for the complete script, see
TableFormatting):
Set myDocument = myInDesign.Documents.Item(1)
Set myStory = myDocument.Stories.Item(1)
Set myTable = myStory.Tables.Item(1)
Rem Convert the first row to a header row.
Rem Use a reference to a swatch, rather than to a color.
myTable.Rows.Item(1).FillColor = myDocument.Swatches.Item("DGC1_446b")
myTable.Rows.Item(1).FillTint = 40
myTable.Rows.Item(2).FillColor = myDocument.Swatches.Item("DGC1_446a")
myTable.Rows.Item(2).FillTint = 40
myTable.Rows.Item(3).FillColor = myDocument.Swatches.Item("DGC1_446a")
myTable.Rows.Item(3).FillTint = 20
myTable.Rows.Item(4).FillColor = myDocument.Swatches.Item("DGC1_446a")
myTable.Rows.Item(4).FillTint = 40
Rem Iterate through the cells to apply the cell stroke formatting.
For myCounter = 1 To myTable.Cells.Count
myTable.Cells.Item(myCounter).TopEdgeStrokeColor =
myDocument.Swatches.Item("DGC1_446b")
myTable.Cells.Item(myCounter).TopEdgeStrokeWeight = 1
myTable.Cells.Item(myCounter).BottomEdgeStrokeColor =
myDocument.Swatches.Item("DGC1_446b")
myTable.Cells.Item(myCounter).BottomEdgeStrokeWeight = 1
Rem When you set a cell stroke to a swatch, make certain that
Remyou also set the stroke weight.
myTable.Cells.Item(myCounter).LeftEdgeStrokeColor =
myDocument.Swatches.Item("None")
myTable.Cells.Item(myCounter).LeftEdgeStrokeWeight = 0
myTable.Cells.Item(myCounter).RightEdgeStrokeColor =
myDocument.Swatches.Item("None")
myTable.Cells.Item(myCounter).RightEdgeStrokeWeight = 0
Next
The following script fragment shows how to add alternating row formatting to a table (for the complete
script, see AlternatingRows):
Set myDocument = myInDesign.Documents.Item(1)
Set myTable = myDocument.stories.Item(1).tables.Item(1)
Rem Apply alternating fills to the table.
myTable.alternatingFills = idAlternatingFillsTypes.idAlternatingRows
myTable.startRowFillColor = myDocument.swatches.Item("DGC1_446a")
myTable.startRowFillTint = 60
myTable.endRowFillColor = myDocument.swatches.Item("DGC1_446b")
myTable.endRowFillTint = 50
The following script fragment shows how to process the selection when text or table cells are selected. In
this example, the script displays an alert for each selection condition, but a real production script would
then do something with the selected item(s). (For the complete script, see TableSelection.)
CHAPTER 5: Text and Type Adding Path Text 106
Set myInDesign = CreateObject("InDesign.Application")
If myInDesign.Documents.Count <> 0 Then
If myInDesign.Selection.Count <> 0 Then
Select Case TypeName(myInDesign.Selection.Item(1))
Rem When a row, a column, or a range of cells is selected,
Rem the type returned is "Cell"
Case "Cell"
MsgBox ("A cell is selected.")
Case "Table"
MsgBox ("A table is selected.")
Case "InsertionPoint", "Character", "Word", "TextStyleRange",
"Line", "Paragraph", "TextColumn", "Text"
If TypeName(myInDesign.Selection.Item(1).Parent) = "Cell" Then
MsgBox ("The selection is inside a table cell.")
End If
Case "Rectangle", "Oval", "Polygon", "GraphicLine"
If TypeName(myInDesign.Selection.Item(1).Parent.Parent) = "Cell" Then
MsgBox ("The selection is inside a table cell.")
End If
Case "Image", "PDF", "EPS"
If TypeName(myInDesign.Selection.Item(1).Parent.Parent.Parent) =
"Cell" Then
MsgBox ("The selection is inside a table cell.")
End If
Case Else
MsgBox ("The selection is not inside a table.")
End Select
End If
End If
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):
Set myDocument = myInDesign.Documents.Item(1)
Set myPage = myDocument.Pages.Item(1)
Rem Create a rectangle on the first page.
Set myTextFrame = myPage.TextFrames.Add
myTextFrame.geometricBounds = Array(72, 72, 288, 288)
Set myTextPath = myTextFrame.TextPaths.Add
myTextPath.Contents = "This is path text."
To link text paths to another text path or text frame, use the nextTextFrame and previousTextFrame
properties, just as you would for a text frame (see “Working with Text Frames” on page 84).
Using Autocorrect
The autocorrect feature can correct text as you type. The following script shows how to use it (for the
complete script, see Autocorrect):
CHAPTER 5: Text and Type Adding Footnotes 107
ReDim myNewWordPairList(0)
Rem Add a word pair to the autocorrect list. Each
Rem AutoCorrectTable is linked to a specific language.
Set myAutoCorrectTable = myInDesign.AutoCorrectTables.Item("English: USA")
Rem To safely add a word pair to the auto correct table, get the current
Rem word pair list, then add the new word pair to that array, and then
Rem set the autocorrect word pair list to the array.
myWordPairList = myAutoCorrectTable.AutoCorrectWordPairList
ReDim myNewWordPairList(UBound(myWordPairList)+1)
For myCounter = 0 To UBound(myWordPairList)
myNewWordPairList(myCounter) = myWordPairList(myCounter)
Next
Rem Add a new word pair to the array.
myNewWordPairList(UBound(myNewWordPairList)) = (Array("paragarph", "paragraph"))
Rem Update the word pair list.
myAutoCorrectTable.AutoCorrectWordPairList = myNewWordPairList
Rem To clear all autocorrect word pairs in the current dictionary:
Rem myAutoCorrectTable.autoCorrectWordPairList = array(())
Rem Turn autocorrect on if it's not on already.
If myInDesign.AutoCorrectPreferences.AutoCorrect = False Then
myInDesign.AutoCorrectPreferences.AutoCorrect = True
End If
myInDesign.AutoCorrectPreferences.AutoCorrectCapitalizationErrors = True
The following script fragment shows how to add footnotes to a story (for the complete script, including
the myGetRandom function, see Footnotes):
Set myDocument = myInDesign.Documents.Item(1)
Set myPage = myDocument.Pages.Item(1)
With myDocument.FootnoteOptions
.SeparatorText = vbTab
.MarkerPositioning = idFootnoteMarkerPositioning.idSuperscriptMarker
End With
Set myTextFrame = myDocument.Pages.Item(1).TextFrames.Item(1)
Rem Add four footnotes at random locations in the story.
For myCounter = 1 To 4
myRandomNumber = CLng(myGetRandom(1, myTextFrame.ParentStory.Words.Count))
Set myWord = myTextFrame.ParentStory.Words.Item(myRandomNumber)
Set myFootnote = myWord.InsertionPoints.Item(-1).Footnotes.Add
Rem Note: when you create a footnote, it contains text--the footnote marker
Rem and the separator text (if any). If you try to set the text of the footnote
Rem by setting the footnote contents, you will delete the marker. Instead, append
Rem the footnote text, as shown below.
myFootnote.InsertionPoints.Item(-1).Contents = "This is a footnote."
Next
Spanning 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):
CHAPTER 5: Text and Type Setting Text Preferences 108
Set myInDesign = CreateObject("InDesign.Application")
Set myDocument = myInDesign.ActiveDocument
Set myPage = myDocument.Pages.Item(1)
Set myTextFrame = myPage.TextFrames.Item(1)
myTextFrame.TextFramePreferences.TextColumnCount = 3
Set myStory = myTextFrame.ParentStory
Rem Split Column
With myStory.Paragraphs.Item(1)
.SpanColumnType = idSpanColumnTypeOptions.idSplitColumns
.SpanSplitColumnCount = 2
.SplitColumnOutsideGutter = 0
.SplitColumnInsideGutter = 1
End With
Rem Span Columns
mySpanIndex = myStory.Paragraphs.Count \ 2 + 1
With myStory.Paragraphs.Item(mySpanIndex)
.SpanColumnType = idSpanColumnTypeOptions.idSpanColumns
.SpanSplitColumnCount = idSpanColumnCountOptions.idAll
End With
Setting Text Preferences
The following script shows how to set general text preferences (for the complete script, see
TextPreferences):
With myInDesign.TextPreferences
.AbutTextToTextWrap = True
Rem baseline shift key increment can range from .001 to 200 points.
.BaselineShiftKeyIncrement = 1
.DeleteEmptyPages = False
.EnableStylePreviewMode = False
.HighlightCustomSpacing = False
.HighlightHjViolations = True
.HighlightKeeps = True
.HighlightSubstitutedFonts = True
.HighlightSubstitutedGlyphs = True
.JustifyTextWraps = True
Rem kerning key increment value is 1/1000 of an em.
.KerningKeyIncrement = 10
Rem leading key increment value can range from .001 to 200 points.
.LimitToMasterTextFrames = False
.ShowInvisibles = True
.SmallCap = 60
.SmartTextReflow = False
.SubscriptPosition = 30
.SubscriptSize = 60
CHAPTER 5: Text and Type Working with Linked Stories 109
.SuperscriptPosition = 30
.SuperscriptSize = 60
.TypographersQuotes = False
.UseOpticalSize = False
.ZOrderTextWrap = False
End With
Rem Text editing preferences are application-wide.
With myInDesign.TextEditingPreferences
.AllowDragAndDropTextInStory = True
.DragAndDropTextInLayout = True
.SingleClickConvertsFramesToTextFrames = True
.SmartCutAndPaste = True
.TripleClickSelectsLine = False
End With
Working with Linked Stories
Linked stories make it easier to manager multiple versions of the same story or text content in the same
document; it makes it easier to support emerging digital publishing workflows, where, for example, you
need to design for vertical and horizontal layouts. Linked stories behave similarly to traditional links. You
can designate a story as a parent, and then place the same story at other places in the document as child
stories. Whenever the parent story is updated, the child stories are flagged in the Links panel and can be
updated to synchronize with the parent story.
There are several ways to create a linked story. It can be created by linking existing text frames with the
parent story, or by telling the Page, Spread, Master or Document object to create the text frame at the
specified location and link it with the parent story.
To link an existing text frame with the parent story, use the following script (for the complete script, see
If you specify true for the second parameter, which is optional, the linked story options dialog opens;
otherwise, the default options are used.
To tell the Page object to create a linked story for the parent story, the PlaceAndLink method includes two
additional parameters that you can use to specify the layer and point at which to place the linked story, as
shown in the following script fragment (for the complete script, see CreateLinkedStories).
Set newPage = myDocument.Pages.Add
newPage.PlaceAndLink myTextFrame.ParentStory, Array(originY, originX),
myDocument.ActiveLayer, False
To tell the Spread object to create linked story for the parent story, the PlaceAndLink method takes the
same parameters as the PlaceAndLink method for Page object, as shown in the following script fragment
(for the complete script, see CreateLinkedStories).
myDocument.ActiveLayer, False
CHAPTER 5: Text and Type Working with Linked Stories 110
You can also call the PlaceAndLink method for the Document object. The method takes the parent story as
the only parameter. This method does not create the linked story; instead, it loads the place gun and lets
the user decide where to place the linked story.
Changing linked story options
To change the linked story options, use the following script fragment (for the complete script, see
.RemoveForcedLineBreaks = True
.UpdateWhileSaving = True
.WarnOnUpdateOfEditedStory = True
End With
How can I tell whether a given link is a link for a linked story?
Use Link.FilePath. If it is empty, then it is a link for a linked story.
Given a link for linked story, how can I get its link source?
Use this to select the link source:
Then use this to find the active selection, which is the link source:
Application.Selection
111
6Working 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.
Duplicating and moving page items.
Transforming page items.
Working with articles.
Creating Page Items
Page items in an InDesign layout are arranged in a hierarchy, and appear within a container object of some
sort. Spreads, pages, other page items, groups, and text characters are all examples of objects that can
contain page items. This hierarchy of containers in the InDesign scripting object model is the same as in
the InDesign user interface--when you create a rectangle by dragging the Rectangle tool on a page, you
are specifying that the page is the container, or parent, of the rectangle. When you paste an ellipse into a
polygon, you are specifying that the polygon is the parent of the ellipse, which, in turn, is a child object of
its parent, a page.
In general, creating a new page item is as simple as telling the object you want to contain the page item to
create the page item, as shown in the MakeRectangle script.
Rem Given a page "myPage", create a new rectangle at the default size and location
In the above script, a new rectangle is created on the first page of a new document. The rectangle appears
at the default location (near the upper left corner of the page) and has a default size (around ten points
square). Moving the rectangle and changing its dimensions are both accomplished by filling its geometric
bounds property with new values, as shown in the MakeRectangleWithProperties script.
Rem Given a page "myPage", create a new rectangle and specify its size and location...
Set myRectangle = myPage.Rectangles.Add
myRectangle.GeometricBounds = Array(72, 72, 144, 144)
Chapter Update Status
CS6 Unchanged
CHAPTER 6: Working with Page Items Creating Page Items 112
Page item types
It is important to note that you cannot create a “generic” page item--you have to create a page item of a
specific type (a rectangle, oval, graphic line, polygon, text frame, or button). You will also notice that
InDesign changes the type of a page item as the geometry of the page item changes. A rectangle, for
example, is always made up of a single, closed path containing four path points and having 90 degree
interior angles. Change the location of a single point, however, or add another path, and the type of the
page item changes to a polygon. Open the path and remove two of the four points, and InDesign will
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.
To determine the type of a page item, use this example:
myPageItemType = TypeName(myPageItem)
The result of the above will be a string containing the type of the page item.
Getting the type of a page item
When you have a reference to a generic page item, and want to find out what type of a page item it is, use
TypeName to get the specific type.
Rem Given a generic page item "myPageItem"...
myType = TypeName(myPageItem)
MsgBox myType
Referring to page items
When you refer to page items inside a given container (a document, layer, page, spread, group, text frame,
or page item), you use the PageItems collection of the container object. This gives you a collection of the
top level page items inside the object. For example:
Rem Given a reference to InDesign "myInDesign"...
SSet myPageItems = myInDesign.Documents.Item(1).Pages.Item(1).PageItems
The resulting collection (myPageItems) does not include objects inside groups (though it does include the
group), objects inside other page items (thought it does contain the parent page item), or page items in
text frames. To get a reference to all of the items in a given container, including items nested inside other
page items, use the AllPageItems property.
Rem Given a reference to InDesign "myInDesign"...
Set myAllPageItems = myInDesign.Documents.Item(1).Pages.Item(1).AllPageItems
The resulting collection (myAllPageItems) includes all objects on the page, regardless of their position in
the hierarchy.
Another way to refer to page items is to use their label property, much as you can use the name property
of other objects (such as paragraph styles or layers). In the following examples, we will get an array of page
items whose label has been set to myLabel.
Rem Given a reference to InDesign "myInDesign"...
Set myPageItems = myInDesign.Documents.Item(1).Pages.Item(1).PageItems.Item("myLabel")
CHAPTER 6: Working with Page Items Creating Page Items 113
If no page items on the page have the specified label, InDesign returns an empty array.
Page-item geometry
If you are working with page items, it is almost impossible to do anything without understanding the way
that rulers and measurements work together to specify the location and shape of an InDesign page item. If
you use the Control panel in InDesign’s user interface, you probably are already familiar with InDesigns
geometry, but here is a quick summary:
Object are constructed relative to the coordinates shown on the rulers.
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.
Path points contain an anchor point (the location of the point itself) and two control handles (left
direction, which controls the curve of the line segment preceding the point on the path; and right
direction, which controls the curve of the segment following the point). Each of these properties
contains an array in the form (x, y) (where x is the horizontal location of the point, and y is the vertical
location). This array holds the location, in current ruler coordinates, of the point or control handle.
All of the above means that if your scripts need to construct page items, you also need to control the
location of the zero point, and you may want to set the measurement units in use.
Working with paths and path points
For most simple page items, you do not need to worry about the paths and path points that define the
shape of the object. Rectangles, ellipses, and text frames can be created by specifying their geometric
bounds, as we did in the earlier example in this chapter.
In some cases, however, you may want to construct or change the shape of a path by specifying path point
locations, you can either set the anchor point, left direction, and right direction of each path point on the
path individually (as shown in the DrawRegularPolygon_Slow script), or you can use the EntirePath
property of the path to set all of the path point locations at once (as shown in the
DrawRegularPolygon_Fast script). The latter approach is much faster.
The items in the array you use for the EntirePath property can contain anchor points only, or a anchor
points and control handles. Here is an example array containing only anchor point locations:
Array(Array(x1, y1), Array(x2, y2), ...)
Where x and y specify the location of the anchor.
Here is an example containing fully-specified path points (i.e., arrays containing the left direction, anchor,
and right direction, in that order):
Array(Array(Array(xL1, YL1), Array(x1, y1), Array(xR1, yR1)), Array(Array(xL2, YL2),
Array(x2, y2), Array(xR2, yR2)), ...)
Where xL and yL specify the left direction, x and y specify the anchor point, and xR and yR specify the right
direction.
You can also mix the two approaches, as shown in the following example:
CHAPTER 6: Working with Page Items Grouping Page Items 114
Array(Array(Array(xL1, YL1), Array(x1, y1), Array(xR1, yR1)), Array(x2, y2), ...)
Note that the original path does not have to have the same number of points as you specify in the
array—InDesign will add or subtract points from the path as it applies the array to the EntirePath property.
The AddPathPoint script shows how to add path points to a path without using the EntirePath property.
Rem Given a graphic line "myGraphicLine"...
Set myPathPoint = myGraphicLine.Paths.Item(1).PathPoints.Add
Rem Move the path point to a specific location.
myPathPoint.Anchor = Array(144, 144)
The DeletePathPoint script shows how to delete a path point from a path.
Rem Given a polygon "myPolygon", remove the
Rem last path point in the first path.
myPolygon.Paths.Item(1).PathPoints.Item(-1).Delete
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). In InDesign scripting,
you tell the object containing the page items you want to group (usually a page or spread) to group the
page items, as shown in the Group script.
Rem Given a page "myPage" containing at least two ovals and two rectangles...
ReDim myArray(0)
Rem Add the items to the array.
myPush myArray, myPage.Rectangles.Item(1), True
myPush myArray, myPage.Rectangles.Item(2), True
myPush myArray, myPage.Ovals.Item(1), True
myPush myArray, myPage.Ovals.Item(1), True
Rem Group the items.
To ungroup, you tell the group itself to ungroup, as shown in the Ungroup script.
Rem Given a group "myGroup"...
Set myPageItems = myGroup.Ungroup
There is no need to ungroup a group to change the shape, formatting, or content of the page items in the
group. Instead, simply get a reference to the page item you want to change, just as you would with any
other page item.
Duplicating and Moving Page Items
In the InDesign user interface, you can move page items by selecting them and dragging them to a new
location. You can also create copies of page items by copying and pasting, by holding down Option/Alt as
you drag an object, or by choosing Duplicate, Paste In Place, or Step and Repeat from the Edit menu. In
InDesign scripting, you can use the move method to change the location of page items, and the duplicate
method to create a copy of a page item (and, optionally, move it to another location).
The move method can take one of two optional parameters: MoveTo and MoveBy. Both parameters consist
of an array of two measurement units, consisting of a horizontal value and a vertical value. MoveTo
specifies an absolute move to the location specified by the array, relative to the current location of the zero
CHAPTER 6: Working with Page Items Duplicating and Moving Page Items 115
point. MoveBy specifies how far to move the page item relative to the current location of the page item
itself. The Move script shows the difference between these two approaches.
Rem Given a reference to a rectangle "myRectangle"...
Rem Move the rectangle to the location (12, 12).
Rem Absolute move:
myRectangle.Move Array(12, 12)
Rem Move the rectangle *by* 12 points horizontally, 12 points vertically.
Rem Relative move (note empty first parameter):
myRectangle.Move , Array(12, 12)
Rem Move the rectangle to another page (rectangle appears at (0,0).
Set myPage = myInDesign.Documents.Item(1).Pages.Add
myRectangle.Move myPage
Rem To move a page item to another document, use the Duplicate method.
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).
Use the duplicate method to create a copy of a page item. By default, the duplicate method creates a
clone” of an object in the same location as the original object. Optional parameters can be used with the
duplicate method to move the duplicated object to a new location (including other pages in the same
document, or to another document entirely).
Rem Given a reference to a rectangle "myRectangle"...
Rem Duplicate the rectangle and move the
Rem duplicate to the location (12, 12).
Rem Absolute move:
Set myDuplicate = myRectangle.Duplicate(Array(12, 12))
Rem Duplicate the rectangle and move the duplicate *by* 12
Rem points horizontally, 12 points vertically.
Rem Relative move (note empty first parameter):
Set myDuplicate = myRectangle.Duplicate (, Array(12, 12))
Rem Duplicate the rectangle to another page (rectangle appears at (0,0).
Set myPage = myInDesign.Documents.Item(1).Pages.Add
Set myDuplicate = myRectangle.Duplicate(myPage)
Rem Duplicate the rectangle to another document.
Set myDocument = myInDesign.Documents.Add
Set myDuplicate = myRectangle.Duplicate(myDocument.Pages.Item(1))
You can also use copy and paste in InDesign scripting, but scripts using on these methods require that you
select objects (to copy) and rely on the current view to set the location of the pasted elements (when you
paste). This means that scripts that use copy and paste tend to be more fragile (i.e., more likely to fail) than
scripts that use duplicate and move. Whenever possible, try to write scripts that do not depend on the
current view or selection state.
Creating compound paths
InDesign can combine the paths of two or more page items into a single page item containing multiple
paths using the Object > Paths > Make Compound Path menu option. You can do this in InDesign scripting
using the MakeCompoundPath method of a page item, as shown in the following script fragment (for the
complete script, refer to the MakeCompoundPath script).
Rem Given a rectangle "myRectangle" and an Oval "myOval"...
myRectangle.MakeCompoundPath myOval
When you create a compound path, regardless of the types of the objects used to create the compound
path, the type of the resulting object is polygon.
CHAPTER 6: Working with Page Items Duplicating and Moving Page Items 116
To release a compound path and convert each path in the compound path into a separate page item, use
the ReleaseCompoundPath method of a page item, as shown in the following script fragment (for the
complete script, refer to the ReleaseCompoundPath script).
Rem Given a polygon "myPolygon" (all compound paths are type Polygon)...
Set mPageItems = myPolygon.ReleaseCompoundPath
Using Pathfinder operations
The InDesign Pathfinder features offer ways to work with relationships between page items on an
InDesign page. You can merge the paths of page items, or subtract the area of one page item from another
page item, or create a new page item from the area of intersection of two or more page items. Every page