4

How to Group all Objects on a document in Illustrator CC with Javascript? I try to make a script and I need to group all the objects in the document without errors and correctly. In the official guideline I did not find such a function. The code below does not correctly group objects. Objects change places and move to the foreground or to the background. Who can help me?

function group(){     
    var docRef = app.activeDocument;
    var layerRef = docRef.layers[0];

    layerRef.hasSelectedArtwork=true;
    docSelection = app.activeDocument.selection;
    newGroup = app.activeDocument.groupItems.add();
    for ( i = 0; i < docSelection.length; i++ ) {
        newItem = docSelection[i];
        newItem.moveToBeginning( newGroup );
    }
}
ekad
  • 14,436
  • 26
  • 44
  • 46
Max_Pro
  • 101
  • 1
  • 10

2 Answers2

2

I tried to do the same thing with your code and get everything reversed. The problem is in your loop you take the element [i] and move it to the group, so the selection array doesn't has the same length and the loop from 0 to length is no more valid. I tried a loop on the selection array from 0 to length, but just moving the last selection element each time :

layer.hasSelectedArtwork = true;
var selection = activeDocument.selection;
var groupItem = layer.groupItems.add();
var count = selection.length;
for(var i = 0; i < count; i++) {
    var item = selection[selection.length - 1];
    item.moveToBeginning(groupItem);
}

For me, it works. I hope it can help you.

superrache
  • 650
  • 11
  • 26
1

It can be done this way:

app.executeMenuCommand('selectall');
app.executeMenuCommand('group');

Probably it makes sense to unhide and unlock all objects before:

app.executeMenuCommand('showAll');
app.executeMenuCommand('unlockAll');

The comprehensive (?) list of Illustrator's menu commands is here: https://github.com/ten-A/AiMenuObject

Yuri Khristich
  • 13,448
  • 2
  • 8
  • 23