Skip to main content
joplrw10
Participant
February 26, 2023
Answered

Scripting with Artboards not identifying artboards in PSD

  • February 26, 2023
  • 4 replies
  • 2702 views

Currently using Photoshop 2023 CC. 

I'm utilizing the following script to open an image from a folder, copy it into each artboard in the template, then save the samplate, close the image then go to the next file in the folder. 
When I run this script, the artboards are not identifying, but the appropriate names are being searched for. I have also attempted to do this from a layer level and search for layer names, but that also wasn't successful. 

I have attached the file as well that is being opened prior to initializing the script, and the image paths are appropriately finding the image files when the script initiates. 

 

// Define the folder path where the images are located
var folderPath = "FolderPath";

// Get a list of all the files in the folder
var fileList = Folder(folderPath).getFiles();

// Define the artboard names
var artboardNames = ["A2", "2x3 ratio", "3x4 ratio", "4x5 ratio", "11x14"];

// Store a reference to the template document
var templateDoc = app.activeDocument;

// Loop through each file in the folder
for (var i = 0; i < fileList.length; i++) {

  // Open the image file in a new document
  var doc = app.open(fileList[i]);

  // Loop through each named artboard in the template document and copy the contents of the image document into it
  for (var j = 0; j < artboardNames.length; j++) {
    
    // Switch back to the template document
    app.activeDocument = templateDoc;

    // Get the artboard by name
    var artboard = null;
    try {
      artboard = app.activeDocument.artboards.getByName(artboardNames[j]);
    } catch (e) {
      alert("Error: Could not find artboard " + artboardNames[j] + " in document");
      continue;
    }
    
    // Copy the contents of the image document into the target artboard
    doc.activeLayer.copy();
    app.activeDocument.artboards.setActiveArtboardIndex(j);
    app.activeDocument.paste();
    
  }

  // Save the document as a PSD file to a folder
  var savePath = "ExportFolderPath" + fileList[i].name;
  var saveFile = new File(savePath);
  var saveOptions = new PhotoshopSaveOptions();
  saveOptions.embedColorProfile = true;
  saveOptions.alphaChannels = true;
  saveOptions.layers = true;
  app.activeDocument.saveAs(saveFile, saveOptions, true, Extension.LOWERCASE);
  
  // Close the image document without saving changes
  doc.close(SaveOptions.DONOTSAVECHANGES);

  // Switch back to the template document
  app.activeDocument = templateDoc;
  
}

 

This topic has been closed for replies.
Correct answer c.pfaffenbichler

I changed fileList and savePath for my testing, but maybe this can help illustrate my previous 

observations. 

// 2023, use it at your own risk;
var fileList = selectFile(true);

// Define the artboard names
var artboardNames = ["A2", "2x3 ratio", "3x4 ratio", "4x5 ratio", "11x14"];

// Store a reference to the template document
var templateDoc = app.activeDocument;

// Loop through each file in the folder
for (var i = 0; i < fileList.length; i++) {
    placeScaleRotateFile (fileList[i], 0, 0, 100, 100, 0);
    duplicateToArtBoards();

  // Save the document as a PSD file to a folder
  //var savePath = "ExportFolderPath" + fileList[i].name;
  var savePath = "~/Desktop/" + fileList[i].name;
  var saveFile = new File(savePath);
  var saveOptions = new PhotoshopSaveOptions();
  saveOptions.embedColorProfile = true;
  saveOptions.alphaChannels = true;
  saveOptions.layers = true;
  app.activeDocument.saveAs(saveFile, saveOptions, true, Extension.LOWERCASE);
// revert;
executeAction( stringIDToTypeID( "revert" ), undefined, DialogModes.NO );
  // Switch back to the template document
  app.activeDocument = templateDoc;
  
}

////// select file //////
function selectFile (multi) {
    if (multi == true) {var theString = "please select files"}
    else {var theString = "please select one file"};
    if ($.os.search(/windows/i) != -1) {var theFiles = File.openDialog (theString, '*.jpg;*.tif;*.psd;*.png', multi)}
    else {var theFiles = File.openDialog (theString, getFiles, multi)};
////// filter files  for mac //////
    function getFiles (theFile) {
        if (theFile.name.match(/\.(jpg|tif|psd|png)$/i) || theFile.constructor.name == "Folder") {
            return true
            };
        };
    return theFiles
    };
////// duplicate to artboards //////
function duplicateToArtBoards () {
    if (documents.length == 0) {return};
    // get list of selected layers;
    var ref = new ActionReference();
    ref.putProperty (stringIDToTypeID ("property"), stringIDToTypeID ("targetLayersIDs"));
    ref.putEnumerated( charIDToTypeID("Dcmn"), charIDToTypeID("Ordn"), charIDToTypeID("Trgt") ); 
    var targetLayersIDs = executeActionGet(ref).getList(stringIDToTypeID("targetLayersIDs"));
    if (targetLayersIDs.count != 1) {
        alert ("select exactly one layer");
        return
    };
    // get current layer’s id;
    var layerID = getLayerId ();
    // collect artboards;
    var theArtBoards = collectArtBoards ();
    if (theArtBoards.length == 0) {
        alert ("no artboards");
        return
    };
    // get active layer’s artboard’s id;
    var theLayer = activeDocument.activeLayer;
    var thePar = theLayer.parent;
    while (thePar.parent != activeDocument) {
        var thePar = thePar.parent;
    };
    activeDocument.activeLayer = thePar;
    var artboardID = getLayerId ();
    activeDocument.activeLayer = theLayer;
    // process artboards;
    var theAdd = 0;
    for (var m = 0; m < theArtBoards.length; m++) {
    // if not on the original artboard;
        if (theArtBoards[m][2] != artboardID) {
    // =======================================================
    var idlayer = stringIDToTypeID( "layer" );
        var desc17 = new ActionDescriptor();
            var ref6 = new ActionReference();
            ref6.putEnumerated( idlayer, stringIDToTypeID( "ordinal" ), stringIDToTypeID( "targetEnum" ) );
        desc17.putReference( stringIDToTypeID( "null" ), ref6 );
        var idto = stringIDToTypeID( "to" );
            var ref7 = new ActionReference();
            ref7.putIndex( idlayer, theArtBoards[m][1] + theAdd - 1 );
            theAdd++;
        desc17.putReference( idto, ref7 );
        desc17.putBoolean( stringIDToTypeID( "duplicate" ), true );
        desc17.putBoolean( stringIDToTypeID( "adjustment" ), false );
        desc17.putInteger( stringIDToTypeID( "version" ), 5 );
        var idlayerID = stringIDToTypeID( "layerID" );
            var list6 = new ActionList();
            list6.putInteger( 36 );
        desc17.putList( idlayerID, list6 );
    executeAction( stringIDToTypeID( "move" ), desc17, DialogModes.NO );
    // align;
    var idalign = stringIDToTypeID( "align" );
    var idnull = stringIDToTypeID( "null" );
    var idusing = stringIDToTypeID( "using" );
    var idalignToCanvas = stringIDToTypeID( "alignToCanvas" );
        var desc1575 = new ActionDescriptor();
        var ref83 = new ActionReference();
        ref83.putEnumerated( stringIDToTypeID( "layer" ),stringIDToTypeID( "ordinal" ), stringIDToTypeID( "targetEnum" ));
        desc1575.putReference( idnull, ref83 );
        desc1575.putEnumerated( idusing, stringIDToTypeID( "alignDistributeSelector" ), stringIDToTypeID( "ADSCentersH" ) );
        desc1575.putBoolean( idalignToCanvas, false );
    executeAction( idalign, desc1575, DialogModes.NO );
        var desc1577 = new ActionDescriptor();
        var ref84 = new ActionReference();
        ref84.putEnumerated( stringIDToTypeID( "layer" ),stringIDToTypeID( "ordinal" ), stringIDToTypeID( "targetEnum" ));
        desc1577.putReference( idnull, ref84 );
        desc1577.putEnumerated( idusing, stringIDToTypeID( "alignDistributeSelector" ), stringIDToTypeID( "ADSCentersV" ) );
        desc1577.putBoolean( idalignToCanvas, false );
    executeAction( idalign, desc1577, DialogModes.NO );
    // reselect original layer;
    selectLayerByID (layerID, false);
        }
    };
    };
////// collect layers with certain name //////
function collectArtBoards () {
// get number of layers;
    var ref = new ActionReference();
    ref.putProperty(stringIDToTypeID('property'), stringIDToTypeID('numberOfLayers'));
    ref.putEnumerated( charIDToTypeID("Dcmn"), charIDToTypeID("Ordn"), charIDToTypeID("Trgt") ); 
    var applicationDesc = executeActionGet(ref);
    var theNumber = applicationDesc.getInteger(stringIDToTypeID("numberOfLayers"));
// process the layers;
    var theLayers = new Array;
    for (var m = 0; m <= theNumber; m++) {
    try {
    var ref = new ActionReference();
    ref.putIndex( charIDToTypeID( "Lyr " ), m);
    var layerDesc = executeActionGet(ref);
    var layerSet = typeIDToStringID(layerDesc.getEnumerationValue(stringIDToTypeID("layerSection")));
    if (layerSet == "layerSectionStart") {
    var artBoardRect = layerDesc.getObjectValue(stringIDToTypeID("artboard")).getObjectValue(stringIDToTypeID("artboardRect"));
    var v01 = artBoardRect.getDouble(artBoardRect.getKey(0));
    var v02 = artBoardRect.getDouble(artBoardRect.getKey(1));
    var v03 = artBoardRect.getDouble(artBoardRect.getKey(2));
    var v04 = artBoardRect.getDouble(artBoardRect.getKey(3));
    var theName = layerDesc.getString(stringIDToTypeID('name'));
    var theID = layerDesc.getInteger(stringIDToTypeID('layerID'));
    var theIndex = layerDesc.getInteger(stringIDToTypeID('itemIndex'));
// collect if the rect values are not identical:
    if (v01 != v03 && v01 != v04) {theLayers.push([theName, theIndex, theID])}
    };
    }
    catch (e) {};
    };
    return theLayers
    };
////// based on code by mike hale and paul riggott //////
function selectLayerByID(index,add){ 
    add = undefined ? add = false:add 
    var ref = new ActionReference();
        ref.putIdentifier(charIDToTypeID("Lyr "), index);
        var desc = new ActionDescriptor();
        desc.putReference(charIDToTypeID("null"), ref );
            if(add) desc.putEnumerated( stringIDToTypeID( "selectionModifier" ), stringIDToTypeID( "selectionModifierType" ), stringIDToTypeID( "addToSelection" ) ); 
            desc.putBoolean( charIDToTypeID( "MkVs" ), false ); 
        try{
        executeAction(charIDToTypeID("slct"), desc, DialogModes.NO );
    }catch(e){
    alert(e.message); 
    }
    };
////// get active layer’s id //////
function getLayerId () {
    var ref = new ActionReference();
    ref.putProperty (stringIDToTypeID ("property"), stringIDToTypeID ("layerID"));
    ref.putEnumerated( charIDToTypeID("Lyr "), charIDToTypeID("Ordn"), charIDToTypeID("Trgt") ); 
    return executeActionGet(ref).getInteger(stringIDToTypeID("layerID"));
};
////// place //////
function placeScaleRotateFile (file, xOffset, yOffset, theXScale, theYScale, theAngle) {
    // =======================================================
        var desc5 = new ActionDescriptor();
        desc5.putPath( charIDToTypeID( "null" ), new File( file ) );
        desc5.putEnumerated( charIDToTypeID( "FTcs" ), idQCSt = charIDToTypeID( "QCSt" ), charIDToTypeID( "Qcsa" ) );
        var idOfst = charIDToTypeID( "Ofst" );
            var desc6 = new ActionDescriptor();
            var idPxl = charIDToTypeID( "#Pxl" );
            desc6.putUnitDouble( charIDToTypeID( "Hrzn" ), idPxl, xOffset );
            desc6.putUnitDouble( charIDToTypeID( "Vrtc" ), idPxl, yOffset );
        var idOfst = charIDToTypeID( "Ofst" );
        desc5.putObject( idOfst, idOfst, desc6 );
        var idPrc = charIDToTypeID( "#Prc" );
        desc5.putUnitDouble( charIDToTypeID( "Wdth" ), idPrc, theYScale );
        desc5.putUnitDouble( charIDToTypeID( "Hght" ), idPrc, theXScale );
        desc5.putUnitDouble( charIDToTypeID( "Angl" ), charIDToTypeID( "#Ang" ),theAngle );	
        desc5.putBoolean( charIDToTypeID( "Lnkd" ), false );
    executeAction( charIDToTypeID( "Plc " ), desc5, DialogModes.NO );
    return app.activeDocument.activeLayer;
    };

 

4 replies

Stephen Marsh
Community Expert
Community Expert
February 26, 2023

@joplrw10 

 

Where did you get the following bolded bit from? Was it ChatGPT?

 

artboard = app.activeDocument.artboards.getByName(artboardNames[j]);

 

and

 

app.activeDocument.artboards.setActiveArtboardIndex(j);
c.pfaffenbichler
Community Expert
c.pfaffenbichlerCommunity ExpertCorrect answer
Community Expert
February 26, 2023

I changed fileList and savePath for my testing, but maybe this can help illustrate my previous 

observations. 

// 2023, use it at your own risk;
var fileList = selectFile(true);

// Define the artboard names
var artboardNames = ["A2", "2x3 ratio", "3x4 ratio", "4x5 ratio", "11x14"];

// Store a reference to the template document
var templateDoc = app.activeDocument;

// Loop through each file in the folder
for (var i = 0; i < fileList.length; i++) {
    placeScaleRotateFile (fileList[i], 0, 0, 100, 100, 0);
    duplicateToArtBoards();

  // Save the document as a PSD file to a folder
  //var savePath = "ExportFolderPath" + fileList[i].name;
  var savePath = "~/Desktop/" + fileList[i].name;
  var saveFile = new File(savePath);
  var saveOptions = new PhotoshopSaveOptions();
  saveOptions.embedColorProfile = true;
  saveOptions.alphaChannels = true;
  saveOptions.layers = true;
  app.activeDocument.saveAs(saveFile, saveOptions, true, Extension.LOWERCASE);
// revert;
executeAction( stringIDToTypeID( "revert" ), undefined, DialogModes.NO );
  // Switch back to the template document
  app.activeDocument = templateDoc;
  
}

////// select file //////
function selectFile (multi) {
    if (multi == true) {var theString = "please select files"}
    else {var theString = "please select one file"};
    if ($.os.search(/windows/i) != -1) {var theFiles = File.openDialog (theString, '*.jpg;*.tif;*.psd;*.png', multi)}
    else {var theFiles = File.openDialog (theString, getFiles, multi)};
////// filter files  for mac //////
    function getFiles (theFile) {
        if (theFile.name.match(/\.(jpg|tif|psd|png)$/i) || theFile.constructor.name == "Folder") {
            return true
            };
        };
    return theFiles
    };
////// duplicate to artboards //////
function duplicateToArtBoards () {
    if (documents.length == 0) {return};
    // get list of selected layers;
    var ref = new ActionReference();
    ref.putProperty (stringIDToTypeID ("property"), stringIDToTypeID ("targetLayersIDs"));
    ref.putEnumerated( charIDToTypeID("Dcmn"), charIDToTypeID("Ordn"), charIDToTypeID("Trgt") ); 
    var targetLayersIDs = executeActionGet(ref).getList(stringIDToTypeID("targetLayersIDs"));
    if (targetLayersIDs.count != 1) {
        alert ("select exactly one layer");
        return
    };
    // get current layer’s id;
    var layerID = getLayerId ();
    // collect artboards;
    var theArtBoards = collectArtBoards ();
    if (theArtBoards.length == 0) {
        alert ("no artboards");
        return
    };
    // get active layer’s artboard’s id;
    var theLayer = activeDocument.activeLayer;
    var thePar = theLayer.parent;
    while (thePar.parent != activeDocument) {
        var thePar = thePar.parent;
    };
    activeDocument.activeLayer = thePar;
    var artboardID = getLayerId ();
    activeDocument.activeLayer = theLayer;
    // process artboards;
    var theAdd = 0;
    for (var m = 0; m < theArtBoards.length; m++) {
    // if not on the original artboard;
        if (theArtBoards[m][2] != artboardID) {
    // =======================================================
    var idlayer = stringIDToTypeID( "layer" );
        var desc17 = new ActionDescriptor();
            var ref6 = new ActionReference();
            ref6.putEnumerated( idlayer, stringIDToTypeID( "ordinal" ), stringIDToTypeID( "targetEnum" ) );
        desc17.putReference( stringIDToTypeID( "null" ), ref6 );
        var idto = stringIDToTypeID( "to" );
            var ref7 = new ActionReference();
            ref7.putIndex( idlayer, theArtBoards[m][1] + theAdd - 1 );
            theAdd++;
        desc17.putReference( idto, ref7 );
        desc17.putBoolean( stringIDToTypeID( "duplicate" ), true );
        desc17.putBoolean( stringIDToTypeID( "adjustment" ), false );
        desc17.putInteger( stringIDToTypeID( "version" ), 5 );
        var idlayerID = stringIDToTypeID( "layerID" );
            var list6 = new ActionList();
            list6.putInteger( 36 );
        desc17.putList( idlayerID, list6 );
    executeAction( stringIDToTypeID( "move" ), desc17, DialogModes.NO );
    // align;
    var idalign = stringIDToTypeID( "align" );
    var idnull = stringIDToTypeID( "null" );
    var idusing = stringIDToTypeID( "using" );
    var idalignToCanvas = stringIDToTypeID( "alignToCanvas" );
        var desc1575 = new ActionDescriptor();
        var ref83 = new ActionReference();
        ref83.putEnumerated( stringIDToTypeID( "layer" ),stringIDToTypeID( "ordinal" ), stringIDToTypeID( "targetEnum" ));
        desc1575.putReference( idnull, ref83 );
        desc1575.putEnumerated( idusing, stringIDToTypeID( "alignDistributeSelector" ), stringIDToTypeID( "ADSCentersH" ) );
        desc1575.putBoolean( idalignToCanvas, false );
    executeAction( idalign, desc1575, DialogModes.NO );
        var desc1577 = new ActionDescriptor();
        var ref84 = new ActionReference();
        ref84.putEnumerated( stringIDToTypeID( "layer" ),stringIDToTypeID( "ordinal" ), stringIDToTypeID( "targetEnum" ));
        desc1577.putReference( idnull, ref84 );
        desc1577.putEnumerated( idusing, stringIDToTypeID( "alignDistributeSelector" ), stringIDToTypeID( "ADSCentersV" ) );
        desc1577.putBoolean( idalignToCanvas, false );
    executeAction( idalign, desc1577, DialogModes.NO );
    // reselect original layer;
    selectLayerByID (layerID, false);
        }
    };
    };
////// collect layers with certain name //////
function collectArtBoards () {
// get number of layers;
    var ref = new ActionReference();
    ref.putProperty(stringIDToTypeID('property'), stringIDToTypeID('numberOfLayers'));
    ref.putEnumerated( charIDToTypeID("Dcmn"), charIDToTypeID("Ordn"), charIDToTypeID("Trgt") ); 
    var applicationDesc = executeActionGet(ref);
    var theNumber = applicationDesc.getInteger(stringIDToTypeID("numberOfLayers"));
// process the layers;
    var theLayers = new Array;
    for (var m = 0; m <= theNumber; m++) {
    try {
    var ref = new ActionReference();
    ref.putIndex( charIDToTypeID( "Lyr " ), m);
    var layerDesc = executeActionGet(ref);
    var layerSet = typeIDToStringID(layerDesc.getEnumerationValue(stringIDToTypeID("layerSection")));
    if (layerSet == "layerSectionStart") {
    var artBoardRect = layerDesc.getObjectValue(stringIDToTypeID("artboard")).getObjectValue(stringIDToTypeID("artboardRect"));
    var v01 = artBoardRect.getDouble(artBoardRect.getKey(0));
    var v02 = artBoardRect.getDouble(artBoardRect.getKey(1));
    var v03 = artBoardRect.getDouble(artBoardRect.getKey(2));
    var v04 = artBoardRect.getDouble(artBoardRect.getKey(3));
    var theName = layerDesc.getString(stringIDToTypeID('name'));
    var theID = layerDesc.getInteger(stringIDToTypeID('layerID'));
    var theIndex = layerDesc.getInteger(stringIDToTypeID('itemIndex'));
// collect if the rect values are not identical:
    if (v01 != v03 && v01 != v04) {theLayers.push([theName, theIndex, theID])}
    };
    }
    catch (e) {};
    };
    return theLayers
    };
////// based on code by mike hale and paul riggott //////
function selectLayerByID(index,add){ 
    add = undefined ? add = false:add 
    var ref = new ActionReference();
        ref.putIdentifier(charIDToTypeID("Lyr "), index);
        var desc = new ActionDescriptor();
        desc.putReference(charIDToTypeID("null"), ref );
            if(add) desc.putEnumerated( stringIDToTypeID( "selectionModifier" ), stringIDToTypeID( "selectionModifierType" ), stringIDToTypeID( "addToSelection" ) ); 
            desc.putBoolean( charIDToTypeID( "MkVs" ), false ); 
        try{
        executeAction(charIDToTypeID("slct"), desc, DialogModes.NO );
    }catch(e){
    alert(e.message); 
    }
    };
////// get active layer’s id //////
function getLayerId () {
    var ref = new ActionReference();
    ref.putProperty (stringIDToTypeID ("property"), stringIDToTypeID ("layerID"));
    ref.putEnumerated( charIDToTypeID("Lyr "), charIDToTypeID("Ordn"), charIDToTypeID("Trgt") ); 
    return executeActionGet(ref).getInteger(stringIDToTypeID("layerID"));
};
////// place //////
function placeScaleRotateFile (file, xOffset, yOffset, theXScale, theYScale, theAngle) {
    // =======================================================
        var desc5 = new ActionDescriptor();
        desc5.putPath( charIDToTypeID( "null" ), new File( file ) );
        desc5.putEnumerated( charIDToTypeID( "FTcs" ), idQCSt = charIDToTypeID( "QCSt" ), charIDToTypeID( "Qcsa" ) );
        var idOfst = charIDToTypeID( "Ofst" );
            var desc6 = new ActionDescriptor();
            var idPxl = charIDToTypeID( "#Pxl" );
            desc6.putUnitDouble( charIDToTypeID( "Hrzn" ), idPxl, xOffset );
            desc6.putUnitDouble( charIDToTypeID( "Vrtc" ), idPxl, yOffset );
        var idOfst = charIDToTypeID( "Ofst" );
        desc5.putObject( idOfst, idOfst, desc6 );
        var idPrc = charIDToTypeID( "#Prc" );
        desc5.putUnitDouble( charIDToTypeID( "Wdth" ), idPrc, theYScale );
        desc5.putUnitDouble( charIDToTypeID( "Hght" ), idPrc, theXScale );
        desc5.putUnitDouble( charIDToTypeID( "Angl" ), charIDToTypeID( "#Ang" ),theAngle );	
        desc5.putBoolean( charIDToTypeID( "Lnkd" ), false );
    executeAction( charIDToTypeID( "Plc " ), desc5, DialogModes.NO );
    return app.activeDocument.activeLayer;
    };

 

joplrw10
joplrw10Author
Participant
February 26, 2023

I'm very new to scripting with Photoshop and am attempting to simplify a workflow for myself so there may be much better ways of doing things than I am aware of at the moment.

 

I will take a look at the script and see how I can make my own better. 

 

Thank you very much for your assistance! 

c.pfaffenbichler
Community Expert
Community Expert
February 26, 2023

Please try replacing 

 

      artboard = app.activeDocument.artboards.getByName(artboardNames[j]);

 

with 

 

      artboard = app.activeDocument.layerSets.getByName(artboardNames[j]);

 

(edited)

c.pfaffenbichler
Community Expert
Community Expert
February 26, 2023

First off: Copy/pasting in a Script seems like a bad idea because it is wasteful. 

 


doc.activeLayer.copy();


Secondly: Are you trying to copy content from an image that is not the foremost/active one? 

 


app.activeDocument.artboards.setActiveArtboardIndex(j);

Thirdly: What is setActiveArtboardIndex?

Are you trying to mesh Illustrator and Photoshop Scripting? 

 

Edit:

Fourthly: A Smart Object approach could help avoid pasting five times; maybe even avoid opening the other images at all and simply Replace Contents – though if the images are of diffreing sizes that might mean having to them.