Search code examples
adobe-illustratoradobe-scriptui

Illustrator script (or action) to make 1 random layer visible per group


Similar to this question but with adobe Illustrator: Photoshop action to make 1 random layer visible within each group

I want to use an illustrator script (or action) to generate images that are composed of a random sampling of grouped layers.

  1. With in each of the 12 groups, I want to make 1 layer per group visible.
  2. Export the visible layers as an svg. Bonus points if I can change the file format.
  3. Repeat the process n times

I know this is similar to the code linked above though I want to be able to use illustrator instead of photoshop if possible.


Solution

  • It could be something like this:

    function main() {
        var doc = app.activeDocument;
    
        // hide all items
        var i = doc.pageItems.length;
        while(i--) doc.pageItems[i].hidden = true;
    
        // show one random item on every layer
        var i = doc.layers.length;
        while(i--) { 
            var items = doc.layers[i].pageItems;
            var index = Math.round(Math.random()*(items.length-1));
            items[index].hidden = false;
        }
    
        // save svg
        var counter = 0;
        var file = File(Folder.desktop + '/' + counter + '.svg') ;
        while (file.exists) {
            file = File(Folder.desktop + '/' + counter++ + '.svg');
        }
        doc.exportFile(file, ExportType.SVG);
    
        // save png
        var counter = 0;
        var file = File(Folder.desktop + '/' + counter + '.png') ;
        while (file.exists) {
            file = File(Folder.desktop + '/' + counter++ + '.png');
        }
        var options = new ExportOptionsPNG24();
        options.artBoardClipping = true;
        doc.exportFile(file, ExportType.PNG24, options);
    }
    
    // repeat the script N times
    var n = 3;
    while(n--) main();
    

    It hides all the page items, shows one random item on every layer, and saves the document as SVG and PNG in the desktop folder.