Skip to main content
Participant
January 24, 2024
Answered

Photoshop Script rename and export Artboard to PNG

  • January 24, 2024
  • 2 replies
  • 745 views

Hello
I try to create a Photoshop Script to rename and export all Artboards to png.
the Rename Function works well and the export too except the size of each Artboards...
thanks a lot

//////////////////////////////////////////////////

// CREATE USER INTERFACE
(function () {
var title = "Script";

// Reusable UI variables.
var g; // group
var p; // panel
var w; // window

// Permanent UI variables.
var btnCancel;
var btnOk;
var inpTitle;
var inpSeason;
var inpLanguage;

// CREATE USER INTERFACE
w = new Window("dialog", title);
w.alignChildren = "fill";
p = w.add("panel");
g = p.add("group");
g.add("statictext", undefined, "Title :");
inpTitle = g.add("edittext");
inpTitle.characters = 15;
g = p.add("group");
g.add("statictext", undefined, "Season :");
inpSeason = g.add("edittext");
inpSeason.characters = 15;
g = p.add("group");
g.add("statictext", undefined, "Language :");
inpLanguage = g.add("edittext");
inpLanguage.characters = 15;
g = w.add("group");
g.alignment = "center";
btnOk = g.add("button", undefined, "Ok");
btnCancel = g.add("button", undefined, "Cancel");

// UI EVENT HANDLERS
btnOk.onClick = function () {
w.close(1);
};
btnCancel.onClick = function () {
w.close(0);
};

// Show THE WINDOW
if (w.show() == 1) {
process();
}

function process() {
var doc = app.activeDocument;
var layers = doc.layers;

// Calculate the total number of artboards
var totalArtboards = 0;
for (var i = 0, l = layers.length; i < l; i++) {
doc.activeLayer = layers[i];
if (isArtBoard(doc.activeLayer)) {
totalArtboards++;
}
}

// Process artboards with a progress bar
var progressBar = new ProgressBar("Processing...", totalArtboards);
try {
for (var i = 0, l = layers.length; i < l; i++) {
doc.activeLayer = layers[i];
if (isArtBoard(doc.activeLayer)) {
// Update progress bar
progressBar.update(i - 1);

// Change the artboard name
doc.activeLayer.name = inpTitle.text + "_" + inpSeason.text + "_Main_" + doc.activeLayer.name;

// Export the artboard as PNG
exportArtboardToPNG(doc, doc.activeLayer, inpTitle.text + "_" + inpSeason.text + "_Main_" + doc.activeLayer.name + "_" + inpLanguage.text);
}
}
} finally {
// Close progress bar
progressBar.close();
}
}

function exportArtboardToPNG(doc, layer, filename) {
var exportOptions = new ExportOptionsSaveForWeb();
exportOptions.format = SaveDocumentType.PNG;
exportOptions.PNG8 = false;
exportOptions.transparency = true;
exportOptions.interlaced = false;
exportOptions.quality = 100;

// Save current ruler unit
var originalRulerUnits = app.preferences.rulerUnits;
app.preferences.rulerUnits = Units.PIXELS;

// Check if the layer is an artboard
if (isArtBoard(layer)) {
// Set canvas size to match layer dimensions
var bounds = layer.bounds;
var width = bounds[2] - bounds[0];
var height = bounds[1] - bounds[3];
doc.resizeCanvas(width, height, AnchorPosition.TOPLEFT);

// Export the layer as PNG
var exportFile = new File(doc.path + "/" + filename + ".png");
doc.exportDocument(exportFile, ExportType.SAVEFORWEB, exportOptions);

// Restore original ruler unit
app.preferences.rulerUnits = originalRulerUnits;

// Undo the resizeCanvas to keep the original document intact
doc.activeHistoryState = doc.historyStates[doc.historyStates.length - 2];
} else {
alert("Unable to export layer. Make sure the layer is an artboard or text layer.");
}
}

function isArtBoard(layer) {
// Check if the layer is an artboard
try {
return layer.isBackgroundLayer || layer.grouped || layer.layers.length > 0;
} catch (e) {
return false;
}
}

function ProgressBar(title, maxSteps) {
this.window = new Window("palette", title);
this.progress = this.window.add("progressbar", undefined, 0, maxSteps);
this.progress.maximumSize.width = 300;
this.window.show();

this.update = function (step) {
this.progress.value = step;
this.window.update();
};

this.close = function () {
this.window.close();
};
}

})();
//////////////////////////////////////////////////
This topic has been closed for replies.
Correct answer Stephen Marsh

@André35017048q0of 

 

Save for Web (Legacy) includes all visible artboards in the export, it doesn't save each artboard individually unless you isolate the visibility to the active artboard. Save for Web (Legacy) pre-dates Artboards, so we are lucky that it works as expected! :]

 

I also note that the script is renaming the artboards in the layers panel, is this what you want? I would expect the script to only name the output files, leaving the artboards named as they were.

 

EDIT: Perhaps something like this (I have also set the Title field to be active by default) –

 

//////////////////////////////////////////////////
// CREATE USER INTERFACE
(function () {
    var title = "Script";

    // Reusable UI variables.
    var g; // group
    var p; // panel
    var w; // window

    // Permanent UI variables.
    var btnCancel;
    var btnOk;
    var inpTitle;
    var inpSeason;
    var inpLanguage;

    // CREATE USER INTERFACE
    w = new Window("dialog", title);
    w.alignChildren = "fill";
    p = w.add("panel");
    g = p.add("group");
    g.add("statictext", undefined, "Title :");
    inpTitle = g.add("edittext");
    inpTitle.characters = 15;
    // Set the title field to be active
    inpTitle.active = true;
    g = p.add("group");
    g.add("statictext", undefined, "Season :");
    inpSeason = g.add("edittext");
    inpSeason.characters = 15;
    g = p.add("group");
    g.add("statictext", undefined, "Language :");
    inpLanguage = g.add("edittext");
    inpLanguage.characters = 15;
    g = w.add("group");
    g.alignment = "center";
    btnOk = g.add("button", undefined, "Ok");
    btnCancel = g.add("button", undefined, "Cancel");

    // UI EVENT HANDLERS
    btnOk.onClick = function () {
        w.close(1);
    };
    btnCancel.onClick = function () {
        w.close(0);
    };

    // Show THE WINDOW
    if (w.show() == 1) {
        process();
    }

    function process() {
        var doc = app.activeDocument;
        var layers = doc.layers;

        // Calculate the total number of artboards
        var totalArtboards = 0;
        for (var i = 0, l = layers.length; i < l; i++) {
            doc.activeLayer = layers[i];
            if (isArtBoard(doc.activeLayer)) {
                totalArtboards++;
            }
        }

        // Process artboards with a progress bar
        var progressBar = new ProgressBar("Processing...", totalArtboards);
        try {
            for (var i = 0, l = layers.length; i < l; i++) {
                doc.activeLayer = layers[i];
                if (isArtBoard(doc.activeLayer)) {
                    // Update progress bar
                    progressBar.update(i - 1);

                    // Toggle the active artboard visibility
                    toggleLayerVisibility(true);

                    // Change the artboard name
                    doc.activeLayer.name = inpTitle.text + "_" + inpSeason.text + "_Main_" + doc.activeLayer.name;

                    // Export the artboard as PNG
                    exportArtboardToPNG(doc, doc.activeLayer, inpTitle.text + "_" + inpSeason.text + "_Main_" + doc.activeLayer.name + "_" + inpLanguage.text);

                    // Toggle the active artboard visibility
                    toggleLayerVisibility(true);
                }
            }
        } finally {
            // Close progress bar
            progressBar.close();
        }
    }

    function exportArtboardToPNG(doc, layer, filename) {
        var exportOptions = new ExportOptionsSaveForWeb();
        exportOptions.format = SaveDocumentType.PNG;
        exportOptions.PNG8 = false;
        exportOptions.transparency = true;
        exportOptions.interlaced = false;
        exportOptions.quality = 100;

        // Save current ruler unit
        var originalRulerUnits = app.preferences.rulerUnits;
        app.preferences.rulerUnits = Units.PIXELS;

        // Check if the layer is an artboard
        if (isArtBoard(layer)) {
            // Set canvas size to match layer dimensions
            var bounds = layer.bounds;
            var width = bounds[2] - bounds[0];
            var height = bounds[1] - bounds[3];
            doc.resizeCanvas(width, height, AnchorPosition.TOPLEFT);

            // Export the layer as PNG
            var exportFile = new File(doc.path + "/" + filename + ".png");
            doc.exportDocument(exportFile, ExportType.SAVEFORWEB, exportOptions);

            // Restore original ruler unit
            app.preferences.rulerUnits = originalRulerUnits;

            // Undo the resizeCanvas to keep the original document intact
            doc.activeHistoryState = doc.historyStates[doc.historyStates.length - 2];
        } else {
            alert("Unable to export layer. Make sure the layer is an artboard or text layer.");
        }
    }

    function isArtBoard(layer) {
        // Check if the layer is an artboard
        try {
            return layer.isBackgroundLayer || layer.grouped || layer.layers.length > 0;
        } catch (e) {
            return false;
        }
    }

    function ProgressBar(title, maxSteps) {
        this.window = new Window("palette", title);
        this.progress = this.window.add("progressbar", undefined, 0, maxSteps);
        this.progress.maximumSize.width = 300;
        this.window.show();

        this.update = function (step) {
            this.progress.value = step;
            this.window.update();
        };

        this.close = function () {
            this.window.close();
        };
    }

    function toggleLayerVisibility(toggleOptionsPalette) {
        var s2t = function (s) {
            return app.stringIDToTypeID(s);
        };
        var descriptor = new ActionDescriptor();
        var list = new ActionList();
        var reference = new ActionReference();
        reference.putEnumerated(s2t("layer"), s2t("ordinal"), s2t("targetEnum"));
        list.putReference(reference);
        descriptor.putList(s2t("null"), list);
        descriptor.putBoolean(s2t("toggleOptionsPalette"), toggleOptionsPalette);
        executeAction(s2t("show"), descriptor, DialogModes.NO);
    }

})();
//////////////////////////////////////////////////

 

 

2 replies

Stephen Marsh
Community Expert
Community Expert
January 25, 2024
Stephen Marsh
Community Expert
Stephen MarshCommunity ExpertCorrect answer
Community Expert
January 24, 2024

@André35017048q0of 

 

Save for Web (Legacy) includes all visible artboards in the export, it doesn't save each artboard individually unless you isolate the visibility to the active artboard. Save for Web (Legacy) pre-dates Artboards, so we are lucky that it works as expected! :]

 

I also note that the script is renaming the artboards in the layers panel, is this what you want? I would expect the script to only name the output files, leaving the artboards named as they were.

 

EDIT: Perhaps something like this (I have also set the Title field to be active by default) –

 

//////////////////////////////////////////////////
// CREATE USER INTERFACE
(function () {
    var title = "Script";

    // Reusable UI variables.
    var g; // group
    var p; // panel
    var w; // window

    // Permanent UI variables.
    var btnCancel;
    var btnOk;
    var inpTitle;
    var inpSeason;
    var inpLanguage;

    // CREATE USER INTERFACE
    w = new Window("dialog", title);
    w.alignChildren = "fill";
    p = w.add("panel");
    g = p.add("group");
    g.add("statictext", undefined, "Title :");
    inpTitle = g.add("edittext");
    inpTitle.characters = 15;
    // Set the title field to be active
    inpTitle.active = true;
    g = p.add("group");
    g.add("statictext", undefined, "Season :");
    inpSeason = g.add("edittext");
    inpSeason.characters = 15;
    g = p.add("group");
    g.add("statictext", undefined, "Language :");
    inpLanguage = g.add("edittext");
    inpLanguage.characters = 15;
    g = w.add("group");
    g.alignment = "center";
    btnOk = g.add("button", undefined, "Ok");
    btnCancel = g.add("button", undefined, "Cancel");

    // UI EVENT HANDLERS
    btnOk.onClick = function () {
        w.close(1);
    };
    btnCancel.onClick = function () {
        w.close(0);
    };

    // Show THE WINDOW
    if (w.show() == 1) {
        process();
    }

    function process() {
        var doc = app.activeDocument;
        var layers = doc.layers;

        // Calculate the total number of artboards
        var totalArtboards = 0;
        for (var i = 0, l = layers.length; i < l; i++) {
            doc.activeLayer = layers[i];
            if (isArtBoard(doc.activeLayer)) {
                totalArtboards++;
            }
        }

        // Process artboards with a progress bar
        var progressBar = new ProgressBar("Processing...", totalArtboards);
        try {
            for (var i = 0, l = layers.length; i < l; i++) {
                doc.activeLayer = layers[i];
                if (isArtBoard(doc.activeLayer)) {
                    // Update progress bar
                    progressBar.update(i - 1);

                    // Toggle the active artboard visibility
                    toggleLayerVisibility(true);

                    // Change the artboard name
                    doc.activeLayer.name = inpTitle.text + "_" + inpSeason.text + "_Main_" + doc.activeLayer.name;

                    // Export the artboard as PNG
                    exportArtboardToPNG(doc, doc.activeLayer, inpTitle.text + "_" + inpSeason.text + "_Main_" + doc.activeLayer.name + "_" + inpLanguage.text);

                    // Toggle the active artboard visibility
                    toggleLayerVisibility(true);
                }
            }
        } finally {
            // Close progress bar
            progressBar.close();
        }
    }

    function exportArtboardToPNG(doc, layer, filename) {
        var exportOptions = new ExportOptionsSaveForWeb();
        exportOptions.format = SaveDocumentType.PNG;
        exportOptions.PNG8 = false;
        exportOptions.transparency = true;
        exportOptions.interlaced = false;
        exportOptions.quality = 100;

        // Save current ruler unit
        var originalRulerUnits = app.preferences.rulerUnits;
        app.preferences.rulerUnits = Units.PIXELS;

        // Check if the layer is an artboard
        if (isArtBoard(layer)) {
            // Set canvas size to match layer dimensions
            var bounds = layer.bounds;
            var width = bounds[2] - bounds[0];
            var height = bounds[1] - bounds[3];
            doc.resizeCanvas(width, height, AnchorPosition.TOPLEFT);

            // Export the layer as PNG
            var exportFile = new File(doc.path + "/" + filename + ".png");
            doc.exportDocument(exportFile, ExportType.SAVEFORWEB, exportOptions);

            // Restore original ruler unit
            app.preferences.rulerUnits = originalRulerUnits;

            // Undo the resizeCanvas to keep the original document intact
            doc.activeHistoryState = doc.historyStates[doc.historyStates.length - 2];
        } else {
            alert("Unable to export layer. Make sure the layer is an artboard or text layer.");
        }
    }

    function isArtBoard(layer) {
        // Check if the layer is an artboard
        try {
            return layer.isBackgroundLayer || layer.grouped || layer.layers.length > 0;
        } catch (e) {
            return false;
        }
    }

    function ProgressBar(title, maxSteps) {
        this.window = new Window("palette", title);
        this.progress = this.window.add("progressbar", undefined, 0, maxSteps);
        this.progress.maximumSize.width = 300;
        this.window.show();

        this.update = function (step) {
            this.progress.value = step;
            this.window.update();
        };

        this.close = function () {
            this.window.close();
        };
    }

    function toggleLayerVisibility(toggleOptionsPalette) {
        var s2t = function (s) {
            return app.stringIDToTypeID(s);
        };
        var descriptor = new ActionDescriptor();
        var list = new ActionList();
        var reference = new ActionReference();
        reference.putEnumerated(s2t("layer"), s2t("ordinal"), s2t("targetEnum"));
        list.putReference(reference);
        descriptor.putList(s2t("null"), list);
        descriptor.putBoolean(s2t("toggleOptionsPalette"), toggleOptionsPalette);
        executeAction(s2t("show"), descriptor, DialogModes.NO);
    }

})();
//////////////////////////////////////////////////