How to write text to a text file by Photoshop JavaScript?

torus picture torus · Jun 25, 2011 · Viewed 15.6k times · Source

I took a look at Photoshop CS5 Scripting Guide and Photoshop CS5 JavaScript Reference, but I couldn't find out a method to write text to a plain text file. Is there any way to do that?

I want to record the value of bounds of each layer object in a document.

Any hint?

Answer

psycho brm picture psycho brm · Sep 24, 2013

This works for me, saves text with the same name as original document, but with extension txt:

function saveTxt(txt)
{
    var Name = app.activeDocument.name.replace(/\.[^\.]+$/, '');
    var Ext = decodeURI(app.activeDocument.name).replace(/^.*\./,'');
    if (Ext.toLowerCase() != 'psd')
        return;

    var Path = app.activeDocument.path;
    var saveFile = File(Path + "/" + Name +".txt");

    if(saveFile.exists)
        saveFile.remove();

    saveFile.encoding = "UTF8";
    saveFile.open("e", "TEXT", "????");
    saveFile.writeln(txt);
    saveFile.close();
}

I don't know how it works, photoshop scripting is a huge mess, I just kept mixing together a few scripts that I found until it worked.

Also, if anyone needs this, here is a script that also saves active document as png image:

function savePng()
{
    var Name = app.activeDocument.name.replace(/\.[^\.]+$/, '');
    var Ext = decodeURI(app.activeDocument.name).replace(/^.*\./,'');
    if (Ext.toLowerCase() != 'psd')
        return;

    var Path = app.activeDocument.path;
    var saveFile = File(Path + "/" + Name +".png");

    if(saveFile.exists)
        saveFile.remove();

    var o = new ExportOptionsSaveForWeb();
        o.format = SaveDocumentType.PNG;
        o.PNG8 = false;
        o.transparency = true;
        o.interlaced = false;
        o.includeProfile = false;
    activeDocument.exportDocument(saveFile, ExportType.SAVEFORWEB, o);
}