Automating Photoshop to edit en rename +600 files with the name of the folder - photoshop

I have +600 product images on my mac already cut out and catalogued in their own folder. They are all PSD's and I need a script that will do the following.
Grab the name of the folder
Grab all the PSD's in said folder
Combine them in one big PSD in the right order (the filenames are saved sequentially as 1843, 1845, 1846 so they need to open in that order)
save that PSD
save the separate layers as PNG with the name from the folder + _1, _2, _3
I have previous experience in Bash (former Linux user) and tried for hours in Automator but to no success.

Welcome to Stack Overflow. The quick answer is yes this is possible to do via scripting. I might even suggest breaking down into two scripts, one to grab and save the PSDs and the second to save out the layers.
It's not very clear about "combining" the PSDs or about "separate layers, only I don't know if they are different canvas sizes, where you want each PSD to be positioned (x, y offsets & layering) Remember none of use have your files infront of us to refer from.
In short, if you write out pseudo code of what is it you expect your code to do it makes it easier to answer your question.
Here's a few code snippets to get you started:
This will open a folder and retrieve alls the PSDs as an array:
// get all the files to process
var folderIn = Folder.selectDialog("Please select folder to process");
if (folderIn != null)
{
var tempFileList = folderIn.getFiles();
}
var fileList = new Array(); // real list to hold images, not folders
for (var i = 0; i < tempFileList.length; i++)
{
// get the psd extension
var ext = tempFileList[i].toString();
ext = ext.substring(ext.lastIndexOf("."), ext.length);
if (tempFileList[i] instanceof File)
{
if (ext == ".psd") fileList.push (tempFileList[i]);
// else (alert("Ignoring " + tempFileList[i]))
}
}
alert("Files:\n" + fileList.length);
You can save a png with this
function save_png(afilePath)
{
// Save as a png
var pngFile = new File(afilePath);
pngSaveOptions = new PNGSaveOptions();
pngSaveOptions.embedColorProfile = true;
pngSaveOptions.formatOptions = FormatOptions.STANDARDBASELINE;
pngSaveOptions.matte = MatteType.NONE; pngSaveOptions.quality = 1;
activeDocument.saveAs(pngFile, pngSaveOptions, false, Extension.LOWERCASE);
}
To open a psd just use
app.open(fileRef);
To save it
function savePSD(afilePath)
{
// save out psd
var psdFile = new File(afilePath);
psdSaveOptions = new PhotoshopSaveOptions();
psdSaveOptions.embedColorProfile = true;
psdSaveOptions.alphaChannels = true;
activeDocument.saveAs(psdFile, psdSaveOptions, false, Extension.LOWERCASE);
}

Related

Adobe illustrator linked file name to a layer name script

I want the layer enter image description here
to have the name of the linked file without .eps at the end.
Anyway, I found an answer. So for anyone looking here it is, although it does take to click on every layer, at least you don't have to type it.
function test() {
var sel_itemPlaced = app.activeDocument.selection[0]; // be sure that a linked item (and not an embedded) is selected
var fileName = sel_itemPlaced.file.name;
var textContents = fileName.replace(/\%20/g, " "); //change %20 to spaces
textContents = textContents.replace(/\.[^\.]*$/, ""); //remove extension
var _item = sel_itemPlaced;
while (_item.parent.typename != 'Layer') {
_item = _item.parent;
}
_item.parent.name = textContents;
}
test();
It does work for all placed images and all layers at once:
var images = app.activeDocument.placedItems;
for (var i=0; i<images.length; i++)
images[i].layer.name = images[i].file.name.replace(/\.[^\.]+$/, "");

How to name tabs in pdf export to xls

I have a PDF form that has many form fields. My requirement is to export the form data (some of it anyway) into an excel (xls) format on a network drive that is being picked up and used by another process (that I do not have access or code to change) to load into a database using Acrobat Javascript when a button on the PDF is clicked. As this is a distributed form and the network drive is common, it did not make sense to setup ODBC connections to the database nor did I have access to do so.
The issues I am having are:
I need to specifically name the Worksheet so that the process correctly processes the xls file.
I need to save the information to the network drive without prompting the user, which the code below does.
The fieldNames seem to be losing spaces when they export to xls.
So far nothing I tried has worked nor do any of the references I have gone though provide such information. I can push data into a .csv and .txt files and have tried creating a new Report something like the following:
var rep = new Report();
var values = "";
...
rep.writeText(values);
var docRep = rep.open("myreport.pdf");
docRep.saveAs("/c/temp/Upload.txt","com.adobe.acrobat.plain-text")
docRep.closeDoc(true);
app.alert("Upload File Saved", 3);
but it only allows the .txt extension not the xls or csv extension. I managed to export the csv in another way.
Below is a small snippet of my code:
var fieldNames = [];
var result ="";
fieldNames.push("Inn Code");
fieldValues.push('"' + this.getField("Hotel Info Inn Code").value + '"');
fieldNames.push("Business Unit");
fieldValues.push('"' + this.getField("Hotel Info Business Unit").value + '"');
for ( var i=0; i < fieldNames.length; i++ ) {
result += (fieldNames[i] + "\t");
}
for ( var i=0; i < fieldValues.length; i++ ) {
result += (fieldValues[i] + "\t");
}
this.createDataObject({cName: "Upload.xls", cValue: cMyC});
this.exportDataObject({cName: "Upload.xls", nLaunch: 0});
Any help or suggestions provided would be greatly appreciated!
Update (For anyone else who encounters this need).
I determined that the tab name using the method above is the same as the save name. The other issue I encountered was that the xls file was really a csv with an xls extension. To resolve this I decided to export an csv I am formatting or a text file and an external process to reformat the file as an xls.
var fieldNames = [];
var fieldValues = [];
var result = '';
// FIELD VALUES
fieldNames.push('"Column Name 1"');
fieldValues.push('\r\n' + '"' + this.getField("Field Name 1").value + '"');
fieldNames.push('"Column Name 2"');
fieldValues.push('"' + this.getField("Field Name 2").value + '"');
for ( var i=0; i < fieldNames.length; i++ ) {
if (i != fieldNames.length-1){
result += (fieldNames[i] + ",");
} else {
result += (fieldNames[i]);
}
}
for ( var i=0; i < fieldValues.length; i++ ) {
if (i != fieldValues.length-1){
result += (fieldValues[i] + ",");
} else {
result += (fieldValues[i]);
}
}
I used the following to output a csv file:
this.createDataObject('UploadFile.csv', result);
this.exportDataObject({ cName:'UploadFile.csv', nLaunch:'0'});
The issue is that this prompts the user where to save the file and I wanted a silent specific location so I wound up doing the following in place of the create and export object above to output a txt file silently without prompting the user:
var rep = new Report();
rep.writeText(result);
var docRep = rep.open("myreport.pdf");
docRep.saveAs("/c/temp/UploadFile.txt","com.adobe.acrobat.plain-text")
docRep.closeDoc(true);
You will have to go into Edit > Preferences > Security (Enhanced) then choose the output folder (C:\Temp) in my case to output silently if you chose to employ this method.

How do you modify this script to run TinyPNG on opened files instead of having to use the open dialog to select a file?

I'm trying to modify this script to compress and then close all the opened files with the TinyPNG Photoshop plugin as opposed to having to choose one file at a time in an open dialog box. They do offer another script that allows you to compress a whole folder. However, I find myself needing to compress 10 out 50 images in a folder so I'd rather just be able to select those 10 or to open those 10 and run the script on all open files.
I've tried replacing
compressFile(File.openDialog("Choose a PNG or JPEG file to compress")
with
compressFile(app.activeDocument)
in an attempt to have the script just compress the current document.
Instead of using the active document it simply skips to the catch(error).
try {
// Compress Active File
compressFile(File.openDialog("Choose a PNG or JPEG file to compress"));
} catch(error) {
alert("No JPEG or PNG file selected or compression error.");
}
compressFile() requires a File object while activeDocument is a document object.
For opened documents you'll want a loop through the documents:
for (var i = documents.length - 1; i >= 0; i--) {
activeDocument = documents[i];
compressFile()
}
and in compressFile() you should get rid opener part (because all the documents are already opened) but you'll need to replace a file with actual document path:
// Compress the document
var tinify = new ActionDescriptor();
tinify.putPath(charIDToTypeID("In "), new File(activeDocument.path + "/" + activeDocument.name)); /* Overwrite original! */
tinify.putUnitDouble(charIDToTypeID("Scl "), charIDToTypeID("#Prc"), percentage);
For a files dialogue you can simply modify the last bit of Compress File.jsx:
//dialogue to select multiple files:
var startFolder = Folder.myDocuments,
myFiles = startFolder.openDlg(void(0), void(0), true);
if (myFiles != null) //if the dialogue wasn't cancelled
{
//launch compressFile for every selected file
for (var i = myFiles.length - 1; i >= 0; i--)
{
compressFile(myFiles[i])
}
}

Identify and extract or delete pages of a PDF based on a search string / text (action / javascript)

Good Evening (UK)
I'm trying to filter down a 1500+ page PDF file to only the pages which include a certain text string (typically one or two words). My laptop is locked down with respect to installing more software BUT I have used action(script)s quite a bit
I get the error below when I try to install this action into Abobe Acrobat X Pro (Win 7):
screen dump of error
called "Extract Commented Pages"... supposed to be OK for X and XI this looks like what I want.....
I wondered if there was something simple causing the problem but the actionscript file is rather... busy to say the least.
I used to have an action that I think was based on a legal redaction script but it is filed somewhere!
If you have already got an action that does this or a version of the above that doesn't give the error I get (unable to import the Action.... The file is either invalid or corrupt) I will forever by indebted to your gratitude
Many thanks, have a good weekend!
I recently came across a script found at the following link: http://forums.adobe.com/thread/1077118
I'm having some issues getting the script to run in Acrobat, despite everything looking alright in the script itself. I'll update if I find any errors.
Here is a copy of the script:
// Set the word to search for here
var sWord = "forms";
// Source document = current document
var sd = this;
var nWords, currWord, fp, fpa = [], nd;
var fn = sd.documentFileName.replace(/\.pdf$/i, "");
// Loop through the pages
for (var i = 0; i < sd.numPages; i += 1) {
// Get the number of words on the page
nWords = sd.getPageNumWords(i);
// Loop through the words on the page
for (var j = 0; j < nWords; j += 1) {
// Get the current word
currWord = sd.getPageNthWord(i, j);
if (currWord === sWord) {
// Extract the current page to a new file
fp = fn + "_" + i + ".pdf";
fpa.push(fp);
sd.extractPages({nStart: i, nEnd: i, cPath: fp});
// Stop searching this page
break;
}
}
}
// Combine the individual pages into one PDF
if (fpa.length) {
// Open the document that's the first extracted page
nd = app.openDoc({cPath: fpa[0], oDoc: sd});
// Append any other pages that were extracted
if (fpa.length > 1) {
for (var i = 1; i < fpa.length; i += 1) {
nd.insertPages({nPage: i - 1, cPath: fpa[i], nStart: 0, nEnd: 0});
}
}
// Save to a new document and close this one
nd.saveAs({cPath: fn + "_searched.pdf"});
nd.closeDoc({bNoSave: true});
}

How to automate Photoshop?

I am trying to automate the process of scanning/cropping photos in Photoshop. I need to scan 3 photos at a time, then use Photoshop's Crop and Straighten Photos command, which creates 3 separate images. After that I'd like to save each of the newly created images as a PNG.
I looked at the JSX scripts and they seem to a lot of promise. Is what I described possible to automate in Photoshop using JavaScript or VBScript or whatever?
I just found this script just did the work for me! It automatically crop & straighten the photo and save each result to directory you specified.
http://www.tranberry.com/photoshop/photoshop_scripting/PS4GeeksOrlando/IntroScripts/cropAndStraightenBatch.jsx
Save it to local then run it in the PS=>File=>Command=>Browse
P.S I found in the comment it said the script can be executed directly by double clicking from Mac Finder or Windows Explorer.
Backup gist for the script here
I actually got the answer on the Photoshop forums over at adobe. It turns out that Photoshop CS4 is totally scriptable via JavaScript, VBScript and comes with a really kick-ass Developer IDE, that has everything you'd expect (debugger, watch window, color coding and more). I was totally impressed.
Following is an extract for reference:
you can run the following script that will create a new folder off the existing one and batch split all the files naming them existingFileName#001.png and put them in the new folder (edited)
#target Photoshop
app.bringToFront;
var inFolder = Folder.selectDialog("Please select folder to process");
if(inFolder != null){
var fileList = inFolder.getFiles(/\.(jpg|tif|psd|)$/i);
var outfolder = new Folder(decodeURI(inFolder) + "/Edited");
if (outfolder.exists == false) outfolder.create();
for(var a = 0 ;a < fileList.length; a++){
if(fileList[a] instanceof File){
var doc= open(fileList[a]);
doc.flatten();
var docname = fileList[a].name.slice(0,-4);
CropStraighten();
doc.close(SaveOptions.DONOTSAVECHANGES);
var count = 1;
while(app.documents.length){
var saveFile = new File(decodeURI(outfolder) + "/" + docname +"#"+ zeroPad(count,3) + ".png");
SavePNG(saveFile);
activeDocument.close(SaveOptions.DONOTSAVECHANGES) ;
count++;
}
}
}
};
function CropStraighten() {
function cTID(s) { return app.charIDToTypeID(s); };
function sTID(s) { return app.stringIDToTypeID(s); };
executeAction( sTID('CropPhotosAuto0001'), undefined, DialogModes.NO );
};
function SavePNG(saveFile){
pngSaveOptions = new PNGSaveOptions();
pngSaveOptions.embedColorProfile = true;
pngSaveOptions.formatOptions = FormatOptions.STANDARDBASELINE;
pngSaveOptions.matte = MatteType.NONE;
pngSaveOptions.quality = 1;
pngSaveOptions.PNG8 = false; //24 bit PNG
pngSaveOptions.transparency = true;
activeDocument.saveAs(saveFile, pngSaveOptions, true, Extension.LOWERCASE);
}
function zeroPad(n, s) {
n = n.toString();
while (n.length < s) n = '0' + n;
return n;
};
Visit here for complete post.
Have you tried using Photoshop Actions? I don't now about the scanning part, but the rest can all be done by actions quite easily.