Search code examples
javascriptscriptingadobeadobe-illustrator

Adobe Illustrator JavaScript - Applying a dataset to each open document in a loop


I've written a simple script to open two documents in Adobe Illustrator (File -> Scripts) and apply some commands to those documents.

The purpose of the script; with no documents open in Illustrator, the script will:

  1. Open the required documents.
  2. Load an XML variable library into those documents.
  3. Display the dataset in that library (there is only one dataset).
  4. Save the file in a given location.
  5. Close the file.

The script:

try
{
    var doc_1 = open(File("C:/file1.ai"));
    var doc_2 = open(File("C:/file2.ai"));

    var sourceDoc;
    var targetFile; 

    var options = new IllustratorSaveOptions();

    for (var i = 0; i < app.documents.length; i++ ) 
    {
        sourceDoc = app.documents[i];

        sourceDoc.importVariables(new File("C:/variables.xml"));

        sourceDoc.dataSets[0].display();

        targetFile = new File("C:/output" + sourceDoc.name + '.ai');

        sourceDoc.saveAs( targetFile, options );

        sourceDoc.close();
    }
}
catch(err)
{
    alert(err);
}

This code works only for the last opened file (file2.ai). file1.ai is never touched, almost as if there is no loop.

What could be causing this?


Solution

  • When closing the first file in the loop you just moved app.documents[1] to app.documents[0]

    You want top loop through them backwards

    try your loop with

    for (var i = app.documents.length; i >0 ; i-- )