Skip to main content
Participant
February 23, 2023
Question

Script not working

  • February 23, 2023
  • 1 reply
  • 351 views

Hello, I'm starting to learn Javascript. I am trying to get a batch script to process all the EPS files in a selected folder and save them to a new folder. But when I start the script I saw only an issue that Layer 1 was not found.

Here is the code:

var destFolder, sourceFolder, files, sourceDoc;


// Select the source folder.
sourceFolder = Folder.selectDialog( 'Select the folder with the eps files that you want to remove the green on', '~' );

// If a valid folder is selected
if ( sourceFolder != null )
{
files = new Array();

// Get all files matching the pattern
files = sourceFolder.getFiles("*.eps");

if ( files.length > 0 )
{
// Get the destination to save the files
destFolder = Folder.selectDialog( 'Select the folder where you want to save the finished eps files.', '~' );
for ( i = 0; i < files.length; i++ )
{
sourceDoc = app.open(files[i]); // returns the document object


}
}
}
function main() {

var layerName = "Layer 1";
try {
var _layer = doc.layers[layerName];
} catch (e) {
alert("No layer exists with name " + layerName);
}
app.executeMenuCommand("deselectall");
var _pageItems = doc.pageItems;
for (var i = 0; i < _pageItems.length; i++) {
if (
_pageItems[i].stroked &&
_pageItems[i].strokeColor.red == 230 &&
_pageItems[i].strokeColor.blue == 0 &&
_pageItems[i].strokeColor.green == 126
) {
_pageItems.selected = true;
break;
}
}
app.executeMenuCommand("Find Stroke Color menu item");
var _allItems = app.selection;
for (var i = 0; i < _allItems.length; i++) {
_allItems[i].move(_layer, ElementPlacement.PLACEATEND);
}

// Save the EPS file and close

sourceDoc.save();
sourceDoc.close();
}

main();

This topic has been closed for replies.

1 reply

jduncan
Community Expert
Community Expert
February 23, 2023

I'm on my phone so I can't run your code but at a quick glance, there seem to be some structural issues that are going to trip you up. The specific error you are asking about is probably because you are referencing the variable `doc` but never actually set it anywhere in your script.

 

Typically, you'll see scripters set the variable `doc` to the active document (e.g. `var doc = app.activeDocument`). There are different reasons for doing this but mostly it just saves you from having to type `app.activeDocument` a bunch throughout your script.

 

Without a reference set for `doc`, your code is trying to get a layer from a non-existent object in the line `var _layer = doc.layers[layerName]`.

 

One more note, your `main()` function is never called inside of your loop through the `sourceFolder` files so it will only run on the last opened file. If you are wanting to do the work inside of your `main()` function to all of the files you'll need to call it inside of your loop.