Page 1 of 1

Get contents of folder with script for InDesign

Posted: Thu Jul 13, 2023 9:34 pm
by JimmyHartington
I have a script, which places 6 images into a template InDesign file.
It works if I predefine an array with all the 6 images.

Instead I would like to have the script look in a certain folder and make an array of all the files in the folder.
See code below.
But it returns "ERROR: folderPath.getFiles is not a function".
With my Google searching it seems that getFiles should work.

Code: Select all

if (($error == null) && ($doc != null))

{

    try {

// Define image folder
var folderPath = "D:\\TEST\\Place-images-InDesign\\images\\";

// Get the list of files in the folder
var images = folderPath.getFiles();

// Get the active document
var doc = $doc;

// Loop through each graphic frame
for (var i = 0; i < doc.rectangles.length; i++) {
    // Place the image in the frame
    doc.rectangles[i].place(images[i]);
    // Fit the image to the frame
    doc.rectangles[i].fit(FitOptions.FILL_PROPORTIONALLY);
}


        $outfiles.push($outfile);

    } catch (theError) {

        $doc.close(SaveOptions.no);

        $error = theError.description;

    }

}

Re: Get contents of folder with script for InDesign

Posted: Fri Jul 14, 2023 9:06 am
by freddyp
folderPath is a string and getFiles is not a function available for strings. getFiles is a method of a Folder object, so you have to create a Folder object:

Code: Select all

var folderObj = new Folder("D:\\TEST\\Place-images-InDesign\\images\\");
//and then you can do
var folderList = folderObj.getFiles("*.jpg");
//the mask argument is optional in which case it list all files
The elements of the array returned by getFiles are File or Folder objects. The latter is when there is a subfolder.

Search on the internet for "adobe javascript tools guide". That documentation contains more info about how to work with files and folders in your Creative Suite scripts.

Re: Get contents of folder with script for InDesign

Posted: Fri Jul 14, 2023 10:24 am
by JimmyHartington
Thanks. As always it works when you suggest a solution :D
And thanks for the tip with finding this site: https://extendscript.docsforadobe.dev

This is the finished script:

Code: Select all

if ($error == null && $doc != null) {
  try {
    // Define image folder
    var folderObj = new Folder("D:\\TEST\\Place-images-InDesign\\images\\");

    // Get the list of files in the folder
    var images = folderObj.getFiles("*.jpg");

    // Get the active document
    var doc = $doc;

    // Loop through each graphic frame
    for (var i = 0; i < doc.rectangles.length; i++) {
      // Place the image in the frame
      doc.rectangles[i].place(images[i]);
      // Fit the image to the frame
      doc.rectangles[i].fit(FitOptions.FILL_PROPORTIONALLY);
    }
    $outfiles.push($outfile);
  } catch (theError) {
    $doc.close(SaveOptions.no);
    $error = theError.description;
  }
}