How do I place an image in a text frame using javascript in Indesign?

Ryan Malley picture Ryan Malley · Jul 17, 2013 · Viewed 7k times · Source

I am making a scripted community directory, and I am using script labels to find text boxes and fill them with appropriate information from a JSON file. The problem I am having is that I cannot figure out how to place an image into a frame that I already have reference to. The filepath is in the JSON file, and I know it exists. Does anyone know how to load the file and replace the contents of the box with the image I have. Also, if the image could be fitted to the size of that box, how would it work?

Answer

Jongware picture Jongware · Jul 18, 2013

So you have a text frame (filled with your data) and you want to replace it with an image?

Use this -- the first line assumes you selected your text frame, but of course you can replace it with the reference:

a_frame = app.selection[0];
a_frame.place (File(Folder.myDocuments+'/yourImageName.png'), false);
a_frame.fit (FitOptions.CONTENT_TO_FRAME);
a_frame.fit (FitOptions.PROPORTIONALLY);
a_frame.fit (FitOptions.CENTER_CONTENT);

See TextFrame.place for "place", and TextFrame.fit for "fitting". It doesn't actually matter you are using TextFrame commands here to place and fit an image -- all ID uses is its frame.

The 3 FitOptions in a row ensure that 1. the entire image fits inside your frame, but most likely out of proportion; 2. scales down proportionally; and 3. centers the image inside the frame. Kind of odd, but it seems InDesign's user interface fit options are not all reflected in the scriptable FitOptions.