Captions

To round off this section on text frames and rectangles, let’s try to fill another gap in InDesign’s object model: captions. Captions were added in CS5 but they’re a bit unwieldy, and I for one prefer to continue to script captions.

A caption, naturally, is just a text frame positioned in relation to a picture. Take the following photograph and its caption (I shaded the caption’s frame for clarity):

image with no caption

The caption is a text frame whose left and right sides are the same as the photograph’s; the caption’s top coincides with the photograph’s bottom; the caption’s bottom is a given distance from its top. Here is a script:

if (app.selection.length == 1 || app.selection[0].constructor.name != "Rectangle")
     exit ();
var myPicture = app.selection[0];
var gb = myPicture.geometricBounds;
// add a frame to to picture's parent, which is a Page
var myCaption = myPicture.parent.textFrames.add ();
// set position and size of the caption
myCaption.geometricBounds = [gb[2], gb[1], gb[2]+14, gb[3]];
// apply object style to the caption -- we assume it's present
myCaption.applyObjectStyle (app.activeDocument.objectStyles.item ("caption"));
// add placeholder contents
myCaption.contents = "Caption";
// group the picture and the caption
myPicture.parent.groups.add ([myPicture, myCaption]);

This an easy way to add captions. We first check if it’s safe to continue, which we define here as “there’s one ...

Get Scripting InDesign CS3/4 with JavaScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.