devwiki:photoshop_script:codegenerator

PS Script - Code Generator

Code Generator is a Photoshop javascript tool to automatically replace the top text layer in your Photoshop file with a sequential list of code/text/numbers, which is either from a CSV file format excel file or user's defintion of start number or end number with padding option.

Download is in the source code part below.

  • Purpose
    • often in coupon design or sequential page design, you need the design to stay same but one part of text to be changed for every copy. so this is the tool for it.
  • Idea behind it
    • since we need 3 things to start
      1. the overall design photoshop file
      2. the text-holding layer that needs to be changed for every copy
      3. the list of codes/numbers/names to be put in the text-holder
    • main programming logic
      1. get the user to input “the code list”
      2. get active photoshop document and find the text layer holding replaceable content
      3. for each code in the list, replace the text layer content, and save a copy into png file;
      4. repeat above steps till the whole list done
  • Problem Solving
    • How user input the “code list”?
      • let user to upload the “code list” from a excel file (best user-friendly way to create list)
      • or let user to tell from start number to end number (in case, the “code list” is a number list)
      • SPECIAL complex situation, if user have like multiple list to replace, in case, a contract for all employees, you better use a excel file, first column for name, 2nd column for start date, 3rd column for salary
    • How to format the code in the design?
      • of course, if it is from excel, it just keep the format as in excel, as pure text
      • if user input a number list from start number to end number, people may like keep it format like coupon way, like number with “0” padding in front, like “00001”
    • Where to find and Which text layer to use for replacement?
      • if for simple case, only one replaceable content, it is easy just to grab the top most text layer, (as most time user can accept as put replaceable text layer on top)
      • another solution is to use predefine “fix name” method, like name those layer as “CodeA”, “CodeB”, which force users to name their layer properly instead of intelligently search by the program itself. However, this is actually best way to save amount of programming time and deal with any complex replacing problem.
  • My solution and My Program Design in the actual implementation of this Code/Coupon Generator tool
    • Idea is simple, do what just user requires (deal with only 1 replaceable text layer, and only require it is on the top of other text layers.)
    • Keep excel input method for code list, best and most flexible way, for both programmer and users. (I use CSV file format, since people can use other spreadsheet tool to create, instead of forcing people stick with MS office tool and using Excel)
    • Also keep a simple sequence number input way, for user just want simple number list input, like 1-100. and a simple format option with padding.
    • of course, add input check for most parts to prevent user mistakes, but we assume most users are using for working, not for destroy the program, that is why I assume all users input meaningful content as instructed, means number is number, dont put “abc” inside number dialog, and people should use excel method (CSV file format) if you want to create “abc” list

Source code - Code Generator

  • How to use
    • Open your Photoshop design file, make sure the replaceable text layer is on the top of other text layer(above other text layer is enough, no need to above all layers)
    • Photoshop File > Script > Browse, and load the codeGenerator.js script file
      (if Photoshop don't show it in Browse window, make sure you change the Browse file type to “js” since by default it only show “jsx” file format, which is actual the same but a different name)
  • javascript code, click the file icon to download,
    codeGenerator.js
    // date: 2015-11-25, author: shining ying
    // Function: It will auto change the most top text layer
    // it also can read from CSV type Excel file for the codeList
    // if you want random code, then use this website to help for CSV file of code list
    //   http://www.generaterandomcodes.com/free-generate-random-codes-tool
     
    // ref: http://stackoverflow.com/questions/14571008/photoshop-scripting-changing-text-of-a-text-layer
     
    //#####################################
    // core functions
    //#####################################
     
    function getTextLayer(target) {
    // this basically loops all the layers to find the
    // upmost text layer with the content #nn... and returns it
        if (target == null) return false;
        var layers      = target.layers;
            layerLen    = layers.length;
        for (var i = 0; i < layerLen; i++) {
            var layer       = layers[i];
                isLayerSet  = layer.typename == 'LayerSet';
                isValid     = layer.kind == LayerKind.TEXT;
                //&& /^\s*#\d+\s*$/.test(layer.textItem.contents);
                // we're allowing spaces around the text just in case
            if (!isLayerSet && !isValid) continue;
            if (isLayerSet) {
                var found = getTextLayer(layer);
                if (found) return found;
            } else return layer;
        }
        return false;
    }
    // ref: http://stackoverflow.com/questions/10073699/pad-a-number-with-leading-zeros-in-javascript
    function pad(n, width, z) {
      z = z || '0';
      n = n + '';
      return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
    }
     
    function range(start, stop, step) {
        if (typeof stop == 'undefined') {
            // one param defined
            stop = start;
            start = 0;
        }
        if (typeof step == 'undefined') step = 1;
        if ((step > 0 && start >= stop) || (step < 0 && start <= stop)) return [];
        var result = [];
        for (var i = start; step > 0 ? i < stop : i > stop; i += step) result.push(i);
        return result;
    }
     
    //#####################################
    // generate png code file
    //#####################################
    function codeGeneratePNG( doc, txtLayer, theData ){
        // prepare dir to save the pictures
        var ext = '.png';
        dir = decodeURI(doc.path) + '/png_code';
        if (!Folder(dir).exists) Folder(dir).create();
     
        // Now we have the text layer, the very top one.
        var codeList = theData; //["000001","00002","00003"];
        var total = codeList.length;
        var padAmount = total.toString().length;
     
        for (i = 0; i < codeList.length; i++) { 
            code = codeList[i];
            // Step 1: update content
            txtLayer.textItem.contents = code;
     
            // Step 2: save the file
     
            fileName = dir + '/' + pad(i,padAmount) + ext;
     
            if (!File(fileName).exists){
                var file = new File(fileName);
                opts = new ExportOptionsSaveForWeb();
                with (opts) {
                    format = SaveDocumentType.PNG;
                    PNG8 = false;
                }
                doc.exportDocument(file, ExportType.SAVEFORWEB, opts);
                // save for web
            }
        }
     
        // done
        alert("Done, say 'Thank You.'\n       ^_^");
    }
     
    //#####################################
    // Start the Generating Process
    //#####################################
     
    var doc;
    try {
        doc = app.activeDocument;
        // the front document
    } catch(e) {}
    var txtLayer = getTextLayer(doc);
    // obviously, the text layer if found
     
    // User Menu now
    if (txtLayer) {
        var msg = "     Welcome to Photoshop Coupon or Code Generator!\n";
        msg+="                 ---------Written by Ying, the Great Programmer\n\n";
        msg+="Purpose of This Tool:\n";
        msg+="  Sometimes making Coupon design is easy, but save 700 coupons with different coupon code is tough; Then this tool is born to save your life.\n\n"
        msg+="How to Use this Tool:\n\n";
        msg+="1. Make sure\n  * you have the Code Text layer on the very top of all other text layers (as long as above all other text layer, it is fine),\n  * and You have set your Text Layer alignment and font and size already, then choose the way you want to generate code;\n\n"
        msg+="   1.1 if you choose to Generate Code by enter number range in next prompt dialog,\n      make sure the number is write as format as '1-200', or '10001-10005',\n      Dont write like '0001-0005', write as '1-5,4',\n      I will auto make them into 0001 to 0005 as with 4 paddings;\n\n";
        msg+="   1.2 if you choose to Generate Code by using a CSV file,\n      use excel to make the list of codes in first colume, and save as CSV file,\n      named as 'code.csv' and put next to your current Photoshop file inside the folder, by using a CSV file, it make your life easy if you are so special about the fancy code,\n      this tool can read it automatically, save your trouble on math and save my trouble on more auto code.\n\n";
        msg+="2. Once you are ready, click the 'Generate by Number' or 'Generate by CSV' button, if you are not sure yet, click 'Cancel';\n\n";
        msg+="3. While Generating, it will save all the generated files as PNG in a folder called 'png_code' next to your current PSD file. BE Patient, Generating can take time.\n\n\n         Cheers - Ying\n\n\n         Are you Ready?";
        //alert(msg);
        var ready = confirm(msg);
        if(ready){
            var byCSV = confirm(" * Click Yes to 'Generate by CSV file'.\n * Click No for 'Generate by Number Range' or 'Cancel'.");
            if(byCSV) {
                // alert("Doing CSV");
                //#####################################
                // get data from CSV file
                //#####################################
                var data = [];
                var dataFile = new File(decodeURI(doc.path) + '/code.csv');
                if (File(dataFile).exists){
                    dataFile.open('r');
                    //dataFile.readln(); // Skip first line
                    while (!dataFile.eof) {
                      var dataFileLine = dataFile.readln();
                      var dataFilePieces = dataFileLine.split(',');
                      if (dataFilePieces[0] != "") data.push(dataFilePieces[0]);
                    }
                    dataFile.close();
                    codeGeneratePNG(doc, txtLayer, data);
                }
                else alert("'code.csv' file doesn't exist next to the PSD file.")
            }
            else{
                var byNum = confirm(" * Click Yes to Generate by Number Range method.\n * Click No to Cancel.");
                if(byNum){
                    var rangeTxt = prompt(" * Write as format as '1-200', or '10001-10005';\n * Dont write like '0001-0005', write as '1-5,4', it will auto make them into 0001 to 0005 as with 4 paddings;", "");
                    //alert("Doing Number Range.")
                    //#####################################
                    // generate data from number range
                    //#####################################
                    inputs = rangeTxt.replace(/ /g,'').split(",");
                    if (inputs.length >=1){
                        var inputRange = inputs[0].split("-");
                        var numData = range( parseInt(inputRange[0]), parseInt(inputRange[1])+1 );
     
                        if(inputs.length >= 2){
                            inputPad = parseInt(inputs[1]);
                            var numFormatData = [];
                            for (i = 0; i < numData.length; i++) numFormatData.push( pad(numData[i],inputPad) );
                            codeGeneratePNG(doc, txtLayer, numFormatData);
                        }
                        else codeGeneratePNG(doc, txtLayer, numData);
                    }
                    else alert("Make sure enter correct format of number range.");
                }
            }
        }
    }
     
     
    /*
    if (doc) {
        doc.close(SaveOptions.DONOTSAVECHANGES);
        // close the original layered document without saving
    }
    */
    doc = null;
    // remove reference

Additional Reference

  • devwiki/photoshop_script/codegenerator.txt
  • Last modified: 2021/07/13 12:00
  • by ying