Pelemeshka
Pelemeshka

Reputation: 13

How to access artboard element in a Photoshop script?

I need to replace text elements in a photoshop template via a script. When it's a regular file, everything works fine. But if it's a project where artboards are used, I have no way to select the active layer I want to change. The layer names are fixed and I just want to refer to them by name, but no matter how much I search I can't find a way.

This is how I access the layers in a normal file:

#target photoshop;

var fileRef = new File("I:/ps15.psd");

if (fileRef.exists) {

    app.open(fileRef); //open file

    activeDocument.activeLayer = activeDocument.artLayers.getByName("layer_1"); //find the layer with the name I want

    activeDocument.activeLayer.textItem.contents = "Hi!"; //text replacement

    app.activeDocument.close(SaveOptions.SAVECHANGES); //close file

} else { alert("File not found"); }

I've found functions that determine if a layer is an artboard, but I've never been able to figure out how to select the active layer in them.

Upvotes: 1

Views: 394

Answers (2)

Ghoul Fool
Ghoul Fool

Reputation: 6967

Artboards are really a type of layer groups, which is a type of layer. So you have you called them by name from their parent group and the child.

var srcDoc = app.activeDocument;

// Get layer called "Layer 2"
srcDoc.activeLayer = srcDoc.artLayers.getByName("Layer 2"); 

// Get layer called "my layer 2" in group called "myGroup"
srcDoc.activeLayer = srcDoc.layerSets.getByName("myGroup").artLayers.getByName("my layer 2");

// Get layer called "Layer 1" in artboard "Artboard 1"
srcDoc.activeLayer = srcDoc.layerSets.getByName("Artboard 1").artLayers.getByName("Layer 1");

Alternatively, get it's layer ID and then make that the active layer.

Upvotes: 1

L_KOFY__L
L_KOFY__L

Reputation: 11

I think this code can help you out:

#target photoshop;
var fileRef = new File("I:/ps15.psd");

if (fileRef.exists) {
    app.open(fileRef);
    var layerName = "layer_1";
    var newText = "Hi!";

    var targetLayer = findLayerByNameInArtboards(activeDocument, layerName);

    if (targetLayer) {
        targetLayer.textItem.contents = newText;
        app.activeDocument.save();
        app.activeDocument.close(SaveOptions.SAVECHANGES);
    } else {
        alert("Layer not found: " + layerName);
    }
} else {
    alert("File not found");
}

function findLayerByNameInArtboards(document, layerName) {
    for (var i = 0; i < document.layerSets.length; i++) {
        var layerSet = document.layerSets[i];
        for (var j = 0; j < layerSet.artLayers.length; j++) {
            var layer = layerSet.artLayers[j];
            if (layer.name === layerName) {
                return layer;
            }
        }
    }
    return null;
}

Upvotes: 1

Related Questions