Skip to main content
New Participant
April 30, 2010
Answered

Using datasets

  • April 30, 2010
  • 3 replies
  • 7352 views

Hi,

In a photoshop dataset, I wish to do the following-

1. save as .jpg

2. name the file using a variable used in the document

how can this be done? i am using cs4

Correct answer Kukurykus

I corrected the script that now it works.

3 replies

Stephen Marsh
Adobe Expert
February 18, 2025

@Valerio231295248snk 

 

Here is an updated version of the script, it will hopefully gracefully handle quoted strings, tested in v2019, v2020, v2021, v2024 and v2025 on Mac and Windows:

 

/* 
Photoshop Variables Data Sets to JPEG 2025 Update.jsx
v1.1
Updated and extended by Stephen Marsh, 18th February 2025 - tested with v2019, v2021, v2024 and v2025
Original script by Mike Hale, 2010
~ The active document must have Data Sets already defined. 
~ The first column in the CSV will be used as the suffix for the JPEG file names, mapped to the appropriate text layer.
https://community.adobe.com/t5/photoshop-ecosystem-discussions/using-datasets/td-p/2665594
https://forums.adobe.com/thread/628182
https://forums.adobe.com/message/2773935#2773935
*/

#target photoshop;

// Adjust the following "user friendly" variables as required. A GUI for these file format options isn't planned!

var separator = '_'; // '_' | ' ' | '-' (underscore, space or hyphen)

var jpegEmbedColorProfile = true; // Boolean: true | false
var jpegFormatOptions = FormatOptions.STANDARDBASELINE; // FormatOptions.STANDARDBASELINE | FormatOptions.OPTIMIZEDBASELINE | FormatOptions.PROGRESSIVE
var jpegMatte = MatteType.NONE; // MatteType.NONE | MatteType.WHITE | MatteType.BLACK
var jpegQuality = 10; // Numeric: 0 - 12 (low quality to highest quality)


///// FUNCTIONS /////

function fileImportDataSets(file) {
    var desc = new ActionDescriptor();
    var ref = new ActionReference();
    ref.putClass(stringIDToTypeID("dataSetClass"));
    desc.putReference(charIDToTypeID("null"), ref);
    desc.putPath(charIDToTypeID("Usng"), new File(file));
    desc.putEnumerated(charIDToTypeID("Encd"), stringIDToTypeID("dataSetEncoding"), stringIDToTypeID("dataSetEncodingAuto"));
    desc.putBoolean(stringIDToTypeID("eraseAll"), true); // Remove all existing data sets
    desc.putBoolean(stringIDToTypeID("useFirstColumn"), true);
    executeAction(stringIDToTypeID("importDataSets"), desc, DialogModes.NO);
};

function applyDataSet(setName) {
    var s2t = function (s) {
        return app.stringIDToTypeID(s);
    };
    var descriptor = new ActionDescriptor();
    var reference = new ActionReference();
    reference.putName(s2t("dataSetClass"), setName);
    descriptor.putReference(s2t("null"), reference);
    executeAction(s2t("apply"), descriptor, DialogModes.NO);
};

function getDataSetNames(csvFileRef) {
    var _ftn = function (string) {
        var csvItems = string.split(",");
        //var datasetName = csvItems[0];
        var datasetName = csvItems[0].replace(/(^['"]|['"]$)/g, ''); // Clean both single and double quote-escaped values
        return datasetName;
    };
    csvFileRef.open();
    var datasetArray = [];
    var i = 0;
    var csvString;
    while (!csvFileRef.eof) {
        csvString = csvFileRef.readln();
        // Skip empty lines
        if (csvString.length < 2) continue;
        datasetArray[i] = _ftn(csvString);
        i++;
    }
    csvFileRef.close();
    return datasetArray;
};

function padNumber(number) {
    var str = number.toString();
    while (str.length < 4) {
        str = "0" + str;
    }
    return str;
};

// File format functions
function jpegSaveOptions() {
    var jpgOptions = new JPEGSaveOptions();
    jpgOptions.formatOptions = jpegFormatOptions;
    jpgOptions.embedColorProfile = jpegEmbedColorProfile;
    jpgOptions.matte = jpegMatte;
    jpgOptions.quality = jpegQuality;
    return jpgOptions;
};

///// SCRIPT EXECUTION /////

try {
    if (app.documents.length > 0) {
        (function () {

            // Confirm with the user that the file meets the criteria
            if (!confirm("Data Sets must be created before running this script. The text layer for the file name suffix must be active... Continue?", false)) {
                return;
            }

            // Test if the active layer is a text layer
            if (app.activeDocument.activeLayer.kind !== LayerKind.TEXT) {
                app.beep();
                alert("The active layer isn't a text layer!" + "\r" + "The text layer for the file name suffix must be active...");
                return;
            }

            // Prompt and import the CSV file into the template
            var csvFileRef = File.openDialog("Please select CSV file:");
            // Test if Cancel button returns null, then do nothing
            if (csvFileRef === null) {
                //app.beep();
                return;
            }
            fileImportDataSets(csvFileRef);

            // Select the save folder
            var saveFolder = Folder.selectDialog("Please select the output folder to save the files to:");
            // Test if Cancel button returns null, then do nothing
            if (saveFolder === null) {
                //app.beep();
                return;
            }

            // Set up the dataset array
            var datasetNames = getDataSetNames(csvFileRef);

            // JPEG Save options  
            var jpgOptions = jpegSaveOptions();

            // Initialize the counter for the saved files
            var fileCounter = 0;

            // Loop over the data sets
            for (i = 1; i < datasetNames.length; i++) {

                applyDataSet(datasetNames[i]);

                // Remove the filename extension
                var docName = app.activeDocument.name.replace(/\.[^\.]+$/, '');

                // The textItem.contents of active layer to be used as the filename suffix
                var suffix = app.activeDocument.activeLayer.textItem.contents;
                // The dataset index is used as the filename suffix
                // var suffix = padNumber(i); // This will create "0001", "0002", "0003", "0010", "0100" etc.

                // Save the file
                var jpgSaveFile = new File(saveFolder + "/" + docName + separator + suffix + ".jpg");
                app.activeDocument.saveAs(jpgSaveFile, jpgOptions, true, Extension.LOWERCASE);

                // Increment the counter
                fileCounter++;
            }

            // End of script notification
            app.beep();
            alert(fileCounter + " JPEG files have been saved to:" + "\n" + saveFolder.fsName);

            // Close the template without saving so as not to affect the original data sets
            app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);

        })();
    } else {
        app.beep();
        alert('A template file must be open before running this script...');
    }
} catch (error) {
    app.beep();
    alert(error + ', Line: ' + error.line);
}

 

 

Participating Frequently
February 19, 2025

@Stephen Marsh I have created a video that illustrates my point. Please see the attached video. I hope it makes sense now.

 

Here are the two things I wish to achieve:

  1. I do not want to replace text layers, but image layers
  2. Instead of File>Export DataSets as Files, I want to Export the Linked DataSets as JPGs
Stephen Marsh
Adobe Expert
February 19, 2025
quote

@Stephen Marsh I have created a video that illustrates my point. Please see the attached video. I hope it makes sense now.

 

Here are the two things I wish to achieve:

  1. I do not want to replace text layers, but image layers
  2. Instead of File>Export DataSets as Files, I want to Export the Linked DataSets as JPGs

By @iRushab

 

I'm standing on the shoulders of giants, who are sadly departed.

 

The referenced script is for saving the data sets directly as JPEG images, with the first column in the spreadsheet used for the suffix, which is taken from a text layer.

 

I haven't tested with pixel replacement, but it should be the same.

 

Let me try and come back to you...

Stephen Marsh
Adobe Expert
May 10, 2024

@rejin89342351 – Thank you for your comment! I have updated the code, and tested it in v2019, v2021, v2024:

 

/* 
Photoshop Variables DataSets to JPEG 2024 Update.jsx
https://community.adobe.com/t5/photoshop-ecosystem-discussions/using-datasets/td-p/2665594
by Mike Hale. Updated 10th May 2024 - tested with v2019, v2021 and v2024
It is assumed that the activeDocument has datasets defined and uses the first fieldname in the dataset csv as the savename for the jpg
*/

#target photoshop;

try {

     if (app.documents.length > 0) {

          (function () {

               ///// FUNCTIONS /////

               fileImportDataSets = function (file) {
                    var desc = new ActionDescriptor();
                    var ref = new ActionReference();
                    ref.putClass(stringIDToTypeID("dataSetClass"));
                    desc.putReference(charIDToTypeID("null"), ref);
                    desc.putPath(charIDToTypeID("Usng"), new File(file));
                    desc.putEnumerated(charIDToTypeID("Encd"), stringIDToTypeID("dataSetEncoding"), stringIDToTypeID("dataSetEncodingAuto"));
                    desc.putBoolean(stringIDToTypeID("eraseAll"), true);
                    desc.putBoolean(stringIDToTypeID("useFirstColumn"), true);
                    executeAction(stringIDToTypeID("importDataSets"), desc, DialogModes.NO);
               };

               applyDataSet = function (setName) {
                    var s2t = function (s) {
                         return app.stringIDToTypeID(s);
                    };
                    var descriptor = new ActionDescriptor();
                    var reference = new ActionReference();
                    reference.putName(s2t("dataSetClass"), setName);
                    descriptor.putReference(s2t("null"), reference);
                    executeAction(s2t("apply"), descriptor, DialogModes.NO);
               };

               getDataSetNames = function (csvFileRef) {
                    _ftn = function (string) {
                         var csvItems = string.split(",");
                         datasetName = csvItems[0];
                         return datasetName;
                    };
                    csvFileRef.open();
                    var datasetArray = new Array();
                    var i = 0;
                    while (csvString = csvFileRef.readln()) {
                         // Skip empty lines
                         if (csvString.length < 2) continue;
                         datasetArray[i] = _ftn(csvString);
                         i++;
                    }
                    csvFileRef.close();
                    return datasetArray;
               };

               // Prompt and import the CSV file into the template
               var csvFileRef = File.openDialog("Please select CSV file:");
               // Test if Cancel button returns null, then do nothing
               if (csvFileRef === null) {
                    app.beep();
                    return;
               }
               fileImportDataSets(csvFileRef);

               // Set up the dataset array
               var datasetNames = getDataSetNames(csvFileRef);

               // JPEG Save options  
               var jpgOptns = new JPEGSaveOptions();
               jpgOptns.formatOptions = FormatOptions.STANDARDBASELINE;
               jpgOptns.embedColorProfile = true;
               jpgOptns.matte = MatteType.NONE;
               jpgOptns.quality = 10;

               // Select the text layer named 'name'
               app.activeDocument.activeLayer = app.activeDocument.artLayers.getByName("name");

               // Loop over the data sets
               for (i = 1; i < datasetNames.length; i++) {
                    applyDataSet(datasetNames[i]);
                    // Remove the filename extension
                    var docName = app.activeDocument.name.replace(/\.[^\.]+$/, '');
                    // The textItem.contents of layer 'name' is used as the filename suffix
                    var suffix = app.activeDocument.activeLayer.textItem.contents;
                    // Save the file
                    jpgSaveFile = new File(csvFileRef.path + "/" + docName + "_" + suffix + ".jpg");
                    app.activeDocument.saveAs(jpgSaveFile, jpgOptns, true, Extension.LOWERCASE);
               }

          })();

     } else {
          alert('A template file must be open before running this script...');
     }

} catch (error) {
     alert(error + ', Line: ' + error.line + "\rHint: Is there an active text layer named 'name'?");
}

 

https://prepression.blogspot.com/2017/11/downloading-and-installing-adobe-scripts.html

 

Participating Frequently
February 17, 2025

Thanks for sharing the script. I was able to install it but could not run the script. I already have the CSV file and the dataset defined; instead of exporting datasets to PSD, I intend to export them to jpg. Can you please share step-by-step screenshots on how to go about doing it?

Stephen Marsh
Adobe Expert
February 17, 2025
quote

I was able to install it but could not run the script.


By @iRushab

 

I'm not sure what this really means. What Photoshop version? To confirm the steps:

 

  1. Copy the code text to the clipboard
  2. Open a new blank file in a plain-text editor (not in a word processor)
  3. Paste the code in
  4. Save as a plain text format file – .txt
  5. Rename the saved file extension from .txt to .jsx
  6. Install or browse to the .jsx file to run (see below)

 

Adobe Photoshop Script Installation Location

Scripts are installed in the /Presets/Scripts folder

Mac OS Example:

  • /Applications⁩/Adobe Photoshop CC 2019⁩/Presets⁩/Scripts
  • /Applications/Adobe Photoshop 2021/Presets/Scripts
 
(If this path does not match your version, it should be a simple enough process to find the correct folder using this guide)

Win OS Example:
  • C:\Program Files\Adobe\Adobe Photoshop CC 2018\Presets\Scripts
  • C:\Program Files\Adobe\Adobe Photoshop 2021\Presets\Scripts
 
(If this path does not match your version, it should be a simple enough process to find the correct folder using this guide)
 
NOTE: If running, Adobe Photoshop must be quit and restarted for newly added scripts to become accessible.

Alternatively, select File > Scripts > Browse and navigate to the script file. Scripts recorded into an Action via the Browse command will record the entire absolute path to the script, often making them unsuitable for use on multiple computers. Installed scripts will only record the script name into an Action, which is the better option for Actions that will be installed on multiple computers.
Inspiring
April 30, 2010

Here is one way to save the sets as jpgs. It assumes that the activeDocument has datasets defined and uses the first fieldname in the dataset csv as the savename for the jpg.

fileImportDataSets = function(file) { 
    var desc = new ActionDescriptor(); 
        var ref = new ActionReference(); 
        ref.putClass( stringIDToTypeID( "dataSetClass" ) ); 
    desc.putReference( charIDToTypeID( "null" ), ref ); 
    desc.putPath( charIDToTypeID( "Usng" ), new File( file ) ); 
    desc.putEnumerated( charIDToTypeID( "Encd" ), stringIDToTypeID( "dataSetEncoding" ), stringIDToTypeID( "dataSetEncodingAuto" ) ); 
    desc.putBoolean( stringIDToTypeID( "eraseAll" ), true ); 
    desc.putBoolean( stringIDToTypeID( "useFirstColumn" ), true ); 
executeAction( stringIDToTypeID( "importDataSets" ), desc, DialogModes.NO ); 
}
applyDataSet = function(setName) { 
    var desc = new ActionDescriptor(); 
        var setRef = new ActionReference(); 
        setRef.putName( stringIDToTypeID( "dataSetClass" ), setName ); 
    desc.putReference( charIDToTypeID( "null" ), setRef ); 
executeAction( charIDToTypeID( "Aply" ), desc, DialogModes.NO ); 
}
getDataSetNames = function(csvFileRef) {
     _ftn = function(string){
          var csvItems = string.split(",");
          datasetName = csvItems[0]          
          return datasetName;
     }
     csvFileRef.open();
     var datasetArray = new Array();
     var i = 0;
     while (csvString = csvFileRef.readln()) {
          if (csvString.length < 2) continue; // Skip empty lines
       datasetArray[i] = _ftn(csvString);  
       i++;
     }
     csvFileRef.close();
     return datasetArray;
}
// jpeg options used for all the saves
var jpgOptns = new JPEGSaveOptions();
     jpgOptns.formatOptions = FormatOptions.STANDARDBASELINE;
     jpgOptns.embedColorProfile = true;
     jpgOptns.matte = MatteType.NONE;
     jpgOptns.quality = 8; 
//prompt for file
var csvFileRef = File.openDialog("Please select CSV file"); 
fileImportDataSets(csvFileRef); //inport the CSV file into the template
var datasetNames = getDataSetNames(csvFileRef);// set up the dataset array
//setup a loop for your data set names 
for (i=1; i < datasetNames.length; i++) {
     applyDataSet(datasetNames[i]);
     //edit the file if needed 
     //save the file. Here I use testItem.contents of layer 'name' as the filename
     app.activeDocument.activeLayer = app.activeDocument.artLayers.getByName("name"); 
     jpgSaveFile = new File(csvFileRef.path + "/" + app.activeDocument.activeLayer.textItem.contents + ".jpg");
     app.activeDocument.saveAs (jpgSaveFile ,jpgOptns , true, Extension.LOWERCASE);
}//loop to next data set
ishook
Known Participant
May 1, 2019

I'm getting an error when I run it on line 52,  "Error 1302, No such element. "... app.activeDocument.activeLayer = app.activeDocument.artLayers.getByName("name");

Any ideas?

ishook
Known Participant
May 1, 2019

Nevermind! I just renamed my variable from 'filename' to what you had as 'name' and it worked great. This 10 year old java script is a life saver.