Skip to main content
Known Participant
October 23, 2020
Answered

Illustrator Script to get the path item used fill color name

  • October 23, 2020
  • 8 replies
  • 4947 views

Hi guys,

Could any help me to get the illustrator image path item fill color used name through script.

 

This topic has been closed for replies.
Correct answer Charu Rajput

Hi Raghav,

I have merged your code and code shared by @pixxxelschubser  which is written by @Silly-V to get the swatches name from Indesign when ai file is placed in the Indesign documnt.

 

#target indesign
#targetengine "session"

var illustratorImages = [];
var filePath

function ImageColors() {

    var myDoc = app.activeDocument;
    var mypages = myDoc.spreads;
    if (mypages.length > 0) {
        for (var k = 0; k < mypages.length; k++) {
            var myPageItems = mypages[k].allGraphics;
            for (var l = 0; l < myPageItems.length; l++) {
                if (myPageItems[l].parentPage != null) {
                    if (myPageItems[l].itemLayer.visible == true && myPageItems[l].visible == true) {
                        if (myPageItems[l].itemLink.name.indexOf(".ai") != -1) {
                            var bt = new BridgeTalk();
                            bt.target = "illustrator";

                            var myScript = aiScript.toString() + "\r";
                            filePath = myPageItems[l].itemLink.filePath;
                            myScript += "aiScript(\"" + filePath + "\")";
                            bt.body = myScript;



                            bt.onResult = function (resObj) {
                                //get a string sent back from AI
                                alert("Illustrator sent this message back to InDesign. " + resObj.body.toString());
                            }

                            //error handler
                            bt.onError = function (inBT) { alert(inBT.body); };

                            //send to Illustrator
                            bt.send();
                        }
                    }
                }
            }

        }
    }
    return filePath
}
ImageColors()


function aiScript(path) {

    /*******************************************************************
    Prototype for indexOf()
    ********************************************************************/
    if (!Array.prototype.indexOf) {
        Array.prototype.indexOf = function (searchElement /*, fromIndex */) {
            "use strict";
            if (this == null) {
                throw new TypeError();
            }
            var t = Object(this);
            var len = t.length >>> 0;
            if (len === 0) {
                return -1;
            }
            var n = 0;
            if (arguments.length > 0) {
                n = Number(arguments[1]);
                if (n != n) { // shortcut for verifying if its NaN  
                    n = 0;
                } else if (n != 0 && n != Infinity && n != -Infinity) {
                    n = (n > 0 || -1) * Math.floor(Math.abs(n));
                }
            }
            if (n >= len) {
                return -1;
            }
            var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
            for (; k < len; k++) {
                if (k in t && t[k] === searchElement) {
                    return k;
                }
            }
            return -1;
        }
    }
    /*******************************************************************
    ********************************************************************/

    var colorUsed = new Array();
    var finalPath = path.replace(":", "/", "g");
    var doc = app.open(new File(finalPath));
    doc.selection = null;
    var _pageItems = doc.pageItems;
    for (var i = 0; i < _pageItems.length; i++) {
        doc.selection = null;
        _pageItems[i].selected = true;
        var selectedSwatches = doc.swatches.getSelected();
        if (selectedSwatches.length) {
            if (colorUsed.indexOf(selectedSwatches[0].name) == -1)
                colorUsed.push(selectedSwatches[0].name);
        }
    }
    doc.close(SaveOptions.DONOTSAVECHANGES);
    return colorUsed;
}  

 

 

This will return all swatches name that is used in ai file that you have placed in the indesign document. Currently this script will return duplicate swatches name if it is used twice or more in ai file.  I have attached the sample Indesign and AI file as well on which I have run the script. Keep both files at any location, and make sure you update the link in Indesign file as per your location of ai file on your machine.

Illustrator File 

Indesign File 

 

Let us know how it works for you.

 

EDIT : Added handling of unique names using Array.indexOf()

8 replies

Charu Rajput
Community Expert
Community Expert
October 28, 2020

Hi Raghav,

Find updated script with following handling

 

1. Handling of locked and hidden items.

2. Handling of getting all used swatches as a fillColor and strokeColor from Illustartor for all pageitems, either of locked or hidden.

3. For testing please use attach Indesign File, Illustrator File and also Action file.

 

#target indesign
#targetengine "session"

var illustratorImages = [];
var filePath
var actionScript = "~/Documents/Adobe Scripts/scriptResources_Packaging/Colors.aia"
var styleColors = []

function ImageColors() {
    var myDoc = app.activeDocument;
    var mypages = myDoc.spreads;
    if (mypages.length > 0) {
        for (var k = 0; k < mypages.length; k++) {
            var myPageItems = mypages[k].allGraphics;
            for (var l = 0; l < myPageItems.length; l++) {
                if (myPageItems[l].parentPage != null) {
                    if (myPageItems[l].itemLayer.visible == true && myPageItems[l].visible == true) {
                        if (myPageItems[l].itemLink.name.indexOf(".ai") != -1) {
                            var bt = new BridgeTalk();
                            bt.target = "illustrator";

                            var myScript = aiScript.toString() + "\r";
                            filePath = myPageItems[l].itemLink.filePath;
                            myScript += "aiScript(\"" + filePath + "\")";
                            bt.body = myScript;

                            bt.onResult = function (resObj) {
                                //get a string sent back from AI
                                styleColors = resObj.body.toString().split(",");
                                addSwatchesToIndesign();
                            }

                            //error handler
                            bt.onError = function (inBT) { alert(inBT.body); };

                            //send to Illustrator
                            bt.send(100);
                        }
                    }
                }
            }

        }
    }
}
ImageColors()


function aiScript(path) {

    /*******************************************************************
    Prototype for indexOf()
    ********************************************************************/
    if (!Array.prototype.indexOf) {
        Array.prototype.indexOf = function (searchElement /*, fromIndex */) {
            "use strict";
            if (this == null) {
                throw new TypeError();
            }
            var t = Object(this);
            var len = t.length >>> 0;
            if (len === 0) {
                return -1;
            }
            var n = 0;
            if (arguments.length > 0) {
                n = Number(arguments[1]);
                if (n != n) { // shortcut for verifying if its NaN  
                    n = 0;
                } else if (n != 0 && n != Infinity && n != -Infinity) {
                    n = (n > 0 || -1) * Math.floor(Math.abs(n));
                }
            }
            if (n >= len) {
                return -1;
            }
            var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
            for (; k < len; k++) {
                if (k in t && t[k] === searchElement) {
                    return k;
                }
            }
            return -1;
        }
    }
    /*******************************************************************
    ********************************************************************/

    var colorUsed = new Array();
    var finalPath = path.replace(":", "/", "g");
    var doc = app.open(new File(finalPath));

    var set = 'Colors';
    // Location of your saved Actions.aia file  
    var aia = File('~/Documents/Scripts/scriptResources/Colors.aia');//  
      
    try {
        app.unloadAction(set, '');
    } catch (e) { }
    app.loadAction(aia);
    doc.selection = null;

    var _pageItems = doc.pageItems;
    var isLocked = false;
    var isHidden = false

    var selectedSwatches = []
    for (var i = 0; i < _pageItems.length; i++) {
        doc.selection = null;
        isLocked = false;
        isHidden = false;
        selectedSwatches = [];
        if (_pageItems[i].locked) {
            _pageItems[i].locked = false;
            isLocked = true
        }
        if (_pageItems[i].hidden) {
            _pageItems[i].hidden = false;
            isHidden = true;
        }
        _pageItems[i].selected = true;
        app.doScript('add_used_colors', 'set');
        app.doScript('selct_fill_Color', 'set');
        selectedSwatches.push(doc.swatches.getSelected()[0]);
        app.doScript('select_stroke_Color', 'set');
        selectedSwatches.push(doc.swatches.getSelected()[0]);
        for (var s = 0; s < selectedSwatches.length; s++) {
            if (selectedSwatches[s].name.indexOf("[") == -1) {
                if (colorUsed.indexOf(selectedSwatches[s].name) == -1) {
                    colorUsed.push(selectedSwatches[s].name);
                }
            }
        }
        if (isLocked)
            _pageItems[i].locked = true;
        if (isHidden) {
            _pageItems[i].hidden = true;
        }
    }
    doc.close(SaveOptions.DONOTSAVECHANGES);
    return colorUsed;
}


function addSwatchesToIndesign() {
    alert("All list of swatches from Illustrtaor --- " + styleColors);
    // Till here it brings all swatches from fill color and stroke color from Illustartor to Indesign

    // Update here correctly what exactly you want to do in Indesign document with name of the Illustrator swatches.
    /*var doc = app.activeDocument;
    var mySwatches = doc.swatches;
    for (t = 0; t < mySwatches.length; t++) {
        if (mySwatches[t].name.length > 0) {
            for (u = 0; u < styleColors.length; u++) {
                if (styleColors[u].search(mySwatches[t].name) == -1) {
                    color_add(doc, styleColors[u], ColorModel.PROCESS, styleColors[u])
                }

            }
        }
    }*/
}


function color_add(myDocument, myColorName, myColorModel, myColorValue) {
    if (myColorValue instanceof Array == false) {
        myColorValue = [(parseInt(myColorValue, 16) >> 16) & 0xff, (parseInt(myColorValue, 16) >> 😎 & 0xff, parseInt(myColorValue, 16) & 0xff];
        myColorSpace = ColorSpace.RGB;
    } else {
        if (myColorValue.length == 3)
            myColorSpace = ColorSpace.RGB;
        else
            myColorSpace = ColorSpace.CMYK;
    }
    try {
        myColor = myDocument.colors.item(myColorName);
        myName = myColor.name;
    }
    catch (myError) {
        myColor = myDocument.colors.add();
        myColor.properties = { name: myColorName, model: myColorModel, space: myColorSpace, colorValue: myColorValue };
    }
    return myColor;
}

 

 

Now, you need to update your method color_add and addSwatchesToIndesign as per your requirement. 

Indesign File 

Illustrator File 

Action File 

 

Best regards
Known Participant
October 28, 2020

 I got above action error while run the script  in both CC 19 & 20 versions. I dont have CC 21 version i was not able to test ur files

Charu Rajput
Community Expert
Community Expert
October 28, 2020

Hi,

I have tested in 2020, working fine. I don't have CC 2019. TRy to load this action file manually to see if it loaded successfully or not.

Best regards
Charu Rajput
Community Expert
Charu RajputCommunity ExpertCorrect answer
Community Expert
October 25, 2020

Hi Raghav,

I have merged your code and code shared by @pixxxelschubser  which is written by @Silly-V to get the swatches name from Indesign when ai file is placed in the Indesign documnt.

 

#target indesign
#targetengine "session"

var illustratorImages = [];
var filePath

function ImageColors() {

    var myDoc = app.activeDocument;
    var mypages = myDoc.spreads;
    if (mypages.length > 0) {
        for (var k = 0; k < mypages.length; k++) {
            var myPageItems = mypages[k].allGraphics;
            for (var l = 0; l < myPageItems.length; l++) {
                if (myPageItems[l].parentPage != null) {
                    if (myPageItems[l].itemLayer.visible == true && myPageItems[l].visible == true) {
                        if (myPageItems[l].itemLink.name.indexOf(".ai") != -1) {
                            var bt = new BridgeTalk();
                            bt.target = "illustrator";

                            var myScript = aiScript.toString() + "\r";
                            filePath = myPageItems[l].itemLink.filePath;
                            myScript += "aiScript(\"" + filePath + "\")";
                            bt.body = myScript;



                            bt.onResult = function (resObj) {
                                //get a string sent back from AI
                                alert("Illustrator sent this message back to InDesign. " + resObj.body.toString());
                            }

                            //error handler
                            bt.onError = function (inBT) { alert(inBT.body); };

                            //send to Illustrator
                            bt.send();
                        }
                    }
                }
            }

        }
    }
    return filePath
}
ImageColors()


function aiScript(path) {

    /*******************************************************************
    Prototype for indexOf()
    ********************************************************************/
    if (!Array.prototype.indexOf) {
        Array.prototype.indexOf = function (searchElement /*, fromIndex */) {
            "use strict";
            if (this == null) {
                throw new TypeError();
            }
            var t = Object(this);
            var len = t.length >>> 0;
            if (len === 0) {
                return -1;
            }
            var n = 0;
            if (arguments.length > 0) {
                n = Number(arguments[1]);
                if (n != n) { // shortcut for verifying if its NaN  
                    n = 0;
                } else if (n != 0 && n != Infinity && n != -Infinity) {
                    n = (n > 0 || -1) * Math.floor(Math.abs(n));
                }
            }
            if (n >= len) {
                return -1;
            }
            var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
            for (; k < len; k++) {
                if (k in t && t[k] === searchElement) {
                    return k;
                }
            }
            return -1;
        }
    }
    /*******************************************************************
    ********************************************************************/

    var colorUsed = new Array();
    var finalPath = path.replace(":", "/", "g");
    var doc = app.open(new File(finalPath));
    doc.selection = null;
    var _pageItems = doc.pageItems;
    for (var i = 0; i < _pageItems.length; i++) {
        doc.selection = null;
        _pageItems[i].selected = true;
        var selectedSwatches = doc.swatches.getSelected();
        if (selectedSwatches.length) {
            if (colorUsed.indexOf(selectedSwatches[0].name) == -1)
                colorUsed.push(selectedSwatches[0].name);
        }
    }
    doc.close(SaveOptions.DONOTSAVECHANGES);
    return colorUsed;
}  

 

 

This will return all swatches name that is used in ai file that you have placed in the indesign document. Currently this script will return duplicate swatches name if it is used twice or more in ai file.  I have attached the sample Indesign and AI file as well on which I have run the script. Keep both files at any location, and make sure you update the link in Indesign file as per your location of ai file on your machine.

Illustrator File 

Indesign File 

 

Let us know how it works for you.

 

EDIT : Added handling of unique names using Array.indexOf()

Best regards
Known Participant
October 26, 2020

Hi Charu,

I can't able to unique the same color names pushed in this array "colorUsed" using with below unique function why?

function aiScript(path) {
    var colorUsed = [];
    var finalPath = path.replace(":", "/", "g");
    var doc = app.open(new File(finalPath));
    doc.selection = null;
    var _pageItems = doc.pageItems;
    for (var i = 0; i < _pageItems.length; i++) {
        doc.selection = null;
        _pageItems[i].selected = true;
        var selectedSwatches = doc.swatches.getSelected();
        if (selectedSwatches.length) {
            colorUsed.push(selectedSwatches[0].name);
        }
        var finalArray = unique(colorUsed)
        alert(finalArray)
    }
    doc.close(SaveOptions.DONOTSAVECHANGES);
    return colorUsed;
} 

    function unique(array) {
        var o = {};
        r = [];
        for (i = 0; i < array.length; i++) {
            o[array[i]] = array[i];
        }
        for (i in o) {
            r.push(o[i]);
        }
        return r;
    };
Charu Rajput
Community Expert
Community Expert
October 26, 2020

Hi @Ragav@july2020 ,

I have updated the above answer that will handle the unique values as well now. I have used Array.indexOf() method to make sure colorUsed variable will have only unique names.

 

I hope this helps you.

Best regards
pixxxelschubser
Community Expert
Community Expert
October 24, 2020

Sorry, I made a mistake.

 

The behaviour has changed in the last versions. If a (swatch) color is applied to a pathItem and the pathItem is selected - you always will see the associated swatch (if a associated swatch exists) in Swatches Panel.

 

One possibility:

pathItem color name 

 

  • select one path item with a spot color and run the script snippet written by @Silly-V 
  • change the color to a global swatch and run the snippet again
  • change the color to a "normal" swatch and run the snippet again
  • change the color to a color from Colors Panel and run the snippet again

 

pixxxelschubser
Community Expert
Community Expert
October 24, 2020

Uff, exhausting.

 

Assumed:

You have an InDesign file.

In that InDesign file you have linked a few Illustrator files or graphics (NOT IMAGES!)

The Link Panel in ID shows the path to every linked file.

 

Every Illustrator file could contain several item/elements:

  • Paths
  • Compound Paths
  • IMAGES
  • which also could be nested in (possibly) nested Groups

and so on.

 

Further more the Illustrator file could contain swatches.

  • "normal" swatches
  • global swatches
  • spot color swatches

 

But not every path (in your Illustrator file) uses a swatch for it's fill or stroke color.

Therefore you can read only global or spot color swatch names.

 

Otherwise you have to check if the color is a RGB or CMYK or Greycolor (or others). And you have to loop through all layers, sublayers (possibly nested), groups (possibly nested), compound paths and paths. You will not receive any colors from placed elements such as IMAGES or meshed items or diagrams or the like. You will not get (all) the colors of paths with multiple fill colors (applied through Appearance Panel).

 

Can you see some of the problems?


In an Illustrator file, doing what you want is difficult. It's much more difficult to do what InDesign is supposed to do through BridgeTalk. But in addition to that:

@Ragav@july2020 wrote: "… I cant mention the proper terms, it may get confusing …"

 

Yes. It is very very confusing.

 

Known Participant
October 24, 2020

Thanks for understanding. 

The only posibilites is to get the global color name in the swatches right?

pixxxelschubser
Community Expert
Community Expert
October 24, 2020

@Ragav@july2020 

Please use the blue Reply button. This prevents deeply nested answers.

 

Your code is an InDesign script which use a BridgeTalk function to get the Illustrator swatches? Why? I thought you want to get the used colors? Or not?

 

And please: However, an Illustrator artwork is made up of paths (vector-based) and is usually referred to as a graphic. An Illustrator document can contain images, but the Ai file itself is not referred to as an image.

Known Participant
October 24, 2020

My requirement is to get the used colors name from the each page of the indesign document and updated in the slug table. I have a code to pull the colors used in the indesign document, and I need to took the colors from the AI images placed in the indesign document. 

That y I open the placed illustrator images via bridge talk and try to get the colors of AI file. But, I tried through swatches but it not get the all color names.

 

Sorry, Iam new to illustrator i cant mention the proper terms, it may get confusing.... SOrry for that.

 

 

Is not possible to pick the color name fill in the path of the AI file via script?

pixxxelschubser
Community Expert
Community Expert
October 23, 2020

Similar to your InDesign thread?

Indesign Script for get color name or values of illustrator images used in the document 

 

Why you do not try to get the colors of an image from Photoshop?

pixxxelschubser
Community Expert
Community Expert
October 23, 2020

Additional to what @Charu Rajput wrote - are we talking about a single path, or multiple paths, or compound paths, or grouped paths?

Or about selected paths (or paths in a document without selection)?

 

Or - what not possible is - paths with multiple fill colors (applied via Appearance Panel)?

 

Please describe a bit more in detail what you want.

Known Participant
October 23, 2020

Thanks for your replies,  if the illustrator image contains text, rectangle  and strokes. I need the script to pull the used color name in the images.

Known Participant
October 23, 2020

Whatever if the color process or spot, but the script to pull the used color name in the text, stroke or rectangle object of the image

Charu Rajput
Community Expert
Community Expert
October 23, 2020

Hi Raghav,

Could you please explain more or share some screenshot what exactly you want to extract and from where. You can use fillColor property but, it depends whether color is process or spot. So to help you more more information will be beneficial.

 

Best regards