Skip to main content
Participant
October 29, 2022
Question

How to batch color hundreds of text boxes with matching swatches?

  • October 29, 2022
  • 1 reply
  • 444 views
I have an indesign file where I need to color the background of a text box. The text contained within that text box is also the name of a corresponding swatch. I have imported hundreds of swatches, with matching texts.

I want to use Data Merge or XML import to batch color each entry in my database.

How could I achieve this ?

I have tried several old scripts that used HEX, RGB or CMYK but none of them worked with recent Indesign versions.

This topic has been closed for replies.

1 reply

m1b
Community Expert
Community Expert
October 29, 2022

Hi @Federico267836568h03, please try this script and let me know if I have understood your request. - Mark

/**
 * Set the fillColor of any text frame
 * whose contents matches a swatch name.
 * @author m1b
 * @version 2022-10-29
 * @discussion https://community.adobe.com/t5/indesign-discussions/how-to-batch-color-hundreds-of-text-boxes-with-matching-swatches/m-p/13305809
 */
function main() {

    var doc = app.activeDocument,
        textFrames = doc.textFrames,
        swatches = doc.swatches;

    for (var i = 0; i < textFrames.length; i++)
        for (var j = 0; j < swatches.length; j++)
            if (swatches[j].name == textFrames[i].contents.replace(/(^\s*|\s*$)/g,'')) // trim whitespace
                textFrames[i].fillColor = swatches[j];

} // end main

app.doScript(main, ScriptLanguage.JAVASCRIPT, undefined, UndoModes.ENTIRE_SCRIPT, 'Fill Text Frames');

 

Robert at ID-Tasker
Legend
October 29, 2022

I'm pretty sure you don't have to iterate through all the swatches and compare each one?? 

 

So this should work as well:

 

textFrames[i].fillColor = doc.swatches(textFrames[i].contents.replace(/(^\s*|\s*$)/g,''))) // trim whitespace

 

At least in VB you could do something like that - is it not possible in JS?

But then you would need to use try catch 

m1b
Community Expert
Community Expert
October 29, 2022

Sure you could do it like this:

for (var i = 0; i < textFrames.length; i++) {

    var sw = swatches.itemByName(textFrames[i].contents.replace(/(^\s*|\s*$)/g, ''));
    
    if (sw.isValid)
        textFrames[i].fillColor = sw;

}

 I think this might be faster. Good idea. Feel free to do a test to see if it is actually faster.

- Mark