0 Replies Latest reply on Nov 30, 2016 1:14 PM by ArgoChristian

    Adding page range to existing InDesign script.

    ArgoChristian Level 1

      Hello everyone. As the title says, I am attempting to add a page range function to an existing Javascript.

      InDesign CS6
      Mac

       

      About the existing script.
      This script was made for us to count images and log them into individual .csv's. In some cases, it counts just the images on the page (.JPG's). Then it logs them into a .csv file for input into a separate tool we use. In other cases it opens up a placed InDesign file, counts and logs the images in the placed InDesign file into a .csv file, again, for input into a separate tool we use. The end result is the "whole" InDesign document having .csv's made, when at times we only want 1 or 2 pages. This is cumbersome when you have a 900 page book going on and you only need 1 or 2 .csv's from each document.

       

       

      About the Page Range function script.

      I did some searching and came across this thread which, coincidentally pretty much solved most of my issue, how to make a page range script. https://forums.adobe.com/message/7484207#7484207

       

      So, I started playing with the page range script, inserting it where it made sense it should go, to no avail. I am getting the impression my existing script has something in it to make it continue to do all pages.

       

      So, me being me, I decided since the creator of our existing script is too busy to update it, I would give it a shot and try to learn a little more about scripting. My knowledge is limited. I am just looking for a little guidance here. This existing script (to me anyway) is really complicated. I just cannot seem to find where I am going wrong or where the existing script is forcing my combined script to continue to do all pages instead of using the page range function I inserted. I could have inserted the page range portion in the completely wrong place in the script. What I did works (almost), it's just ignoring the page range function. Any help or guidance is greatly appreciated.

      Christian

       

      Combined script.

       

      #target "indesign"

       

       

      try {

          //assumes document is open

          var docRef = app.documents.item(0);

          var maxPages = docRef.pages.count();

        //provide variable to hold user's response

        var userResponse = dialogWChoices ("Dialog Name", true, "Label here", maxPages);

          //enter call to function that processes all pages

          if (userResponse[0] == 0) {

              myProcess (docRef, 0, maxPages);

           } else {

               var minPageRef = userResponse[1] - 1;

               var maxPageRef = userResponse[2] - 1;

               myProcess (docRef, minPageRef, maxPageRef);

           }

      } catch (e) {

      }

      alert ("Process Done!\rWith the selected pages.");

      //function to process range of pages

      function myProcess (docRef, minPageRef, maxPageRef) {

          var thisPage, thisFrame, docOffset;

          //our code start from here

          function trim(s) {

        return s.replace(/^(\s|\n|\t|\uFEFF)+|(\s|\n|\t|\uFEFF)+$/g, '');

      };

       

       

      function ltrim(s) {

        return s.replace(/^(\s|\n|\t|\uFEFF)+/, '');

      };

       

       

      function rtrim(s) {

        return s.replace(/(\s|\n|\t|\uFEFF)+$/, '');

      };

       

       

      //var foo = File.saveDialog("Choose folder that count files will be placed in.");

      //exit();

       

       

      $.level = 2

       

       

        var rootFileFolder = app.activeDocument.filePath.fsName;

       

       

      var rootFileFolderObj = new Folder(rootFileFolder);

      var saveCountsToFolderObj = rootFileFolderObj.selectDlg("This script will create a series of .csv files containing image counts for each page in the current document.\nPlease select the folder to save the count files to.");

      if (saveCountsToFolderObj == null) {

        alert("No output folder was selected. Aborting script.\n\nPlease run again and select an output folder.");

        exit();

      }

      var saveCountsToFolder = saveCountsToFolderObj.fsName;

      if (saveCountsToFolder.indexOf("/") != -1) {

        saveCountsToFolder += "/";

      } else if (saveCountsToFolder.indexOf("\\") != -1) {

        saveCountsToFolder += "\\";

      }

       

       

      try {

        var filePathMinusExtension = app.activeDocument.fullName.fsName.substr(0, app.activeDocument.fullName.fsName.lastIndexOf("."));

        var logfile = File(filePathMinusExtension + "_DebugLog.txt");

        logfile.encoding = "UTF-8";

        logfile.open("w");

        //var csvFilePath = filePathMinusExtension + "_ImageCounts.csv"

        //var countFile = File(csvFilePath);

        //countFile.open("w");

      } catch (e) {

        alert("Error!\n\nDocument must be saved once before image count file can be created.");

        exit();

      }

      var globalGraphicCounts = [];

       

       

      var embededDocCount = 0;

      var AnalysedPageCount = 0;

      var emptyCountFileCount = 0;

       

       

      function log(inStr) {

        //date = new Date();

       

       

        logfile.writeln(inStr);

        //$.writeln(date.toLocaleTimeString() + "  :  " + inStr);

      }

       

       

      function getImpPage(obj) {

        if (obj.constructor.name == "ImportedPage")

        return obj;

        try {

        return (obj.hasOwnProperty("importedPages") ? obj.importedPages[0] : obj.indesignPageItems[0]);

        } catch (e) {

        return null;

        }

      } // end of getImpPage

       

       

       

       

      function LogPageDetails(inPage, inFileName, inGraphicCountsArray) {

        AnalysedPageCount++;

        var pageGraphicCounts;

        // If an existing graphic counts array is passed in, then we are recusivly counting an embeded document, and just add the graphics to the existing page.

        if (inGraphicCountsArray)

        pageGraphicCounts = inGraphicCountsArray;

        else

        pageGraphicCounts = [];

       

       

        var pageTitle = "UntitledPage_Number_" + inPage.id;

       

       

        log("--------------------------------------------------");

        log("   Begin analysing page - " + inPage.name + "   id: " + inPage.id + " of document " + inFileName);

        log("--------------------------------------------------");

        log("   Page has " + inPage.allPageItems.length + " items");

        log("   Page has " + inPage.allGraphics.length + " graphics items");

       

       

        //if (inPage.allGraphics.length > 0) {

        //log("Global graphic items:");

        //for (gi = 0; gi < inPage.allGraphics.length; gi++) {

        // var myGi = inPage.allGraphics[gi];

        // if (myGi.imageTypeName != "InDesign") {

        //log("   Graphics Item[" + gi + "]  file name: " + myGi.itemLink.name);

        //log("   Graphics Item[" + gi + "]  id: " + myGi.id);

        //log("   Graphics Item[" + gi + "]  image Type: " + myGi.imageTypeName);

        //log("   Graphics Item[" + gi + "]  file: " + myGi.itemLink.filePath);

        //log("    Graphics Item[" + gi + "]  layer id: " + myGi.itemLayer.id);

        //log("   ..................................");

        // }

        //}

        //}

       

       

        log("Page items:");

        for (var pgItmNo = 0; pgItmNo < inPage.allPageItems.length; pgItmNo++) {

        var pgItm = inPage.allPageItems[pgItmNo];

        var pgItmType = pgItm.constructor.name;

        log("   Page item " + pgItmNo + "  Type  " + pgItmType);

       

       

        if (pgItm.allGraphics.length > 0) {

        log("Page Item all graphics list contains " + pgItm.allGraphics.length + " items");

        for (gi = 0; gi < pgItm.allGraphics.length; gi++) {

        var myGi = pgItm.allGraphics[gi];

        if (myGi.imageTypeName != "InDesign") {

        //log("      Inner graphics Item[" + gi + "]  file name: " + myGi.itemLink.name);

        //log("      Inner graphics Item[" + gi + "]  id: " + myGi.id);

        //log("      Inner graphics Item[" + gi + "]  image Type: " + myGi.imageTypeName);

        //log("      Inner graphics Item[" + gi + "]  layer id: " + myGi.itemLayer.id);

        //log("      Inner graphics Item[" + gi + "]  file: " + myGi.itemLink.filePath);

        //log("      ..................................");

       

       

        //if (globalGraphicCounts[myGi.itemLink.name] == null) {

        //    globalGraphicCounts[myGi.itemLink.name] = 1;

        //} else {

        //    globalGraphicCounts[myGi.itemLink.name] += 1;

        //}

        } else {

        log("   Found item of type inDesign. Name: " + myGi.name + "Skipping for now, as not sure what to do here");

        }

        }

        }

       

       

        if (pgItmType == "TextFrame") {

        log("   Text object frame style: " + pgItm.appliedObjectStyle.name);

        if (pgItm.paragraphs.length > 0) {

        log("   text frame has " + pgItm.paragraphs.length + " paragraphs");

        for (var paragraphNumber = 0; paragraphNumber < pgItm.paragraphs.length; paragraphNumber++) {

        var myParagraph = pgItm.paragraphs[paragraphNumber];

        var myParagraphStyle = myParagraph.appliedParagraphStyle.name.toLowerCase();

        log("   Text paragraph style: |" + myParagraphStyle + "|");

       

       

        if (myParagraphStyle == "page head and subhead_top left_nested_every page") {

        var paragraphTexts = myParagraph.texts;

        log("   Found page title paragraph. Number of text sections: " + paragraphTexts.length);

        if (paragraphTexts.length > 0) {

        log("    Number of text sections in page title paragraph: " + paragraphTexts.length);

        for (var textNumber = 0; textNumber < paragraphTexts.length; textNumber++) {

        var myText = paragraphTexts[textNumber].contents;

        log("   In inner text block loop. Counter: " + textNumber + "   text: " + myText);

        if (myText.length > 0) {

        pageTitle = myText;

        log("Found page title!   Title: " + pageTitle);

        } else {

        log("   Skipping blank page title text section");

        }

        }

        } else {

        log("   Found no text sections in page title paragraph.");

        }

        } else {

        log("   Found text element that is not page title.");

        }

        }

       

       

        }

       

        //if (pgItm.textVariableInstances.length > 0) {

        // log("   Text frame contains " + pgItm.textVariableInstances.length + " variable instances");

        // for (var vii = 0; vii < pgItm.textVariableInstances.length; vii++) {

        // var vi = pgItm.textVariableInstances[vii];

        // log("         VariableInstance name: " + vi.name + "     Visible: " + pgItm.visible);

        // }

        //}

        //if (pgItm.groups.length > 0)

        // log("      Text frame  contains " + pgItm.groups.length + " other groups.");

        //if (pgItm.textFrames.length > 0)

        // log("      Text frame  contains " + pgItm.textFrames.length + " text frames.");

        //if (pgItm.tables.length > 0)

        // log("      Text frame  contains " + pgItm.tables.length + " Tables.");

        //if (pgItm.allPageItems.length > 0)

        // log("      Text frame  contains " + pgItm.allPageItems.length + " Total page items.");

        //if (pgItm.allGraphics.length > 0)

        // log("      Text frame  contains " + pgItm.AllGraphics.length + " Total graphics.");

       

       

        } else if (pgItmType == "Group") {

        var tfs = pgItm.textFrames;

        log("      In group, with " + tfs.length + " text frames.");

        for (tfi = 0; tfi < tfs.length; tfi++) {

        var tf = pgItm.textFrames[tfi];

        log("Looking at text frame " + tfi);

        if (tf.textVariableInstances.length > 0) {

        for (var vii = 0; vii < tf.textVariableInstances.length; vii++) {

        var vi = tf.textVariableInstances[vii];

        log("         VariableInstance name: " + vi.name + "    Visible: " + tf.visible);

        }

        }

        if (tf.groups.length > 0)

        log("      Text frame  contains " + tf.groups.length + " other groups.");

        if (tf.textFrames.length > 0)

        log("      Text frame  contains " + tf.textFrames.length + " text frames.");

        if (tf.tables.length > 0)

        log("      Text frame  contains " + tf.tables.length + " Tables.");

        if (tf.allPageItems.length > 0)

        log("      Text frame  contains " + tf.allPageItems.length + " Total page items.");

        if (tf.allGraphics.length > 0)

        log("      Text frame  contains " + tf.AllGraphics.length + " Total graphics.");

        }

        } else if (pgItmType == "Rectangle") {

        var tfs = pgItm.textFrames;

        for (tfi = 0; tfi < tfs.length; tfi++) {

        var tf = pgItm.textFrames[tfi];

        log("      In rectangle with " + tf.textVariableInstances.length + "text variables.");

        if (tf.textVariableInstances.length > 0) {

        for (var vii = 0; vii < tf.textVariableInstances.length; vii++) {

        var vi = tf.textVariableInstances[vii]

        log("         VariableInstance name: " + vi.name + "     Visible: " + tf.visible);

        }

        }

        if (tf.groups.length > 0)

        log("      Rectangle frame  contains " + tf.groups.length + " other groups.");

        if (tf.textFrames.length > 0)

        log("      Rectangle frame  contains " + tf.textFrames.length + " text frames.");

        //if (tf.tables.length > 0) log("   Text frame  contains " + tf.tables.length + " Tables.");

        if (tf.allPageItems.length > 0)

        log("      Rectangle frame  contains " + tf.allPageItems.length + " Total page items.");

        if (tf.allGraphics.length > 0)

        log("      Rectangle frame  contains " + tf.AllGraphics.length + " Total graphics.");

        }

        } else if (pgItmType == "ImportedPage") {

        embededDocumentFilename = "";

        if (pgItm && pgItm.itemLink && pgItm.itemLink.filePath)

        embededDocumentFilename = pgItm.itemLink.filePath;

        log("------------------------------------------------------------------------------------ -");

        log("    Begin embeded document - filename: " + embededDocumentFilename);

        log("------------------------------------------------------------------------------------ -");

        embededDocCount++;

        //if (pgItm.allPageItems.length > 0) log("   Text frame  contains " + pgItm.allPageItems.length + " other groups.");

        //if (pgItm.groups.length > 0) log("   Text frame  contains " + pgItm.groups.length + " other groups.");

        //if (pgItm.textFrames.length > 0) log("   Text frame  contains " + pgItm.textFrames.length + " text frames.");

        //if (pgItm.tables.length > 0) log("   Text frame  contains " + pgItm.tables.length + " Tables.");

        //if (pgItm.allPageItems.length > 0) log("   Text frame  contains " + pgItm.allPageItems.length + " Total page items.");

       

       

        try {

        log("   Name of embeded file to analyse: " + pgItm.itemLink.filePath);

        var newDoc = app.open(File(pgItm.itemLink.filePath))

        log("   Number of pages in embeded document to analyse: " + newDoc.pages.length);

        for (ImportedDocPageIndex = 0; ImportedDocPageIndex < newDoc.pages.length; ImportedDocPageIndex++) {

        var attachedPage = newDoc.pages[ImportedDocPageIndex];

       

       

        LogPageDetails(attachedPage, pgItm.itemLink.filePath + " (embeded)", pageGraphicCounts);

        }

        log("  Closing embeded document. Name: " + embededDocumentFilename);

        newDoc.close();

        log("Done closing embeded document. Name: " + embededDocumentFilename);

       

       

        } catch (e) {

        log("  Could not read embeded doc");

        }

        log("------------------------------------------------------------------------------------ -");

        log("    END embeded document - filename: " + embededDocumentFilename);

        log("------------------------------------------------------------------------------------ -");

        } else if (pgItmType == "PDF") {

        log("         Embeded Pdf found. Name: " + pgItm.itemLink.name);

       

       

        if (pgItm.itemLayer.visible == true && pgItm.visible == true) {

        log("         Layer is visible: " + pgItm.itemLayer.visible + "  Item is visible: " + pgItm.visible + "      **** Counting ****");

        if (globalGraphicCounts[pgItm.itemLink.name] == null) {

        globalGraphicCounts[pgItm.itemLink.name] = 1;

        } else {

        globalGraphicCounts[pgItm.itemLink.name] += 1;

        }

       

       

        if (pageGraphicCounts[pgItm.itemLink.name] == null) {

        pageGraphicCounts[pgItm.itemLink.name] = 1;

        } else {

        pageGraphicCounts[pgItm.itemLink.name] += 1;

        }

        //log("Page counts array is now of size: " + pageGraphicCounts.length);

        } else {

        log("         Layer is visible: " + pgItm.itemLayer.visible + "  Item visisble: " + pgItm.visible + "  *** NOT Counting ***");

        }

       

       

        } else if (pgItmType == "Image") {

        log("         Image item found.");

        if (pgItm.imageTypeName != "InDesign") {

        log("         Image file name: " + pgItm.itemLink.name + " id: " + pgItm.id + " Type: " + pgItm.imageTypeName + "layer id: " + pgItm.itemLayer.id);

        //log("         Image file: " + pgItm.itemLink.filePath);

       

       

        // Don't count it if the layer it is in is not visible

        if (pgItm.itemLayer.visible == true && pgItm.visible == true) {

        log("         Image layer is visible: " + pgItm.itemLayer.visible + "  Item is visible: " + pgItm.visible + "      **** Counting ****");

        if (globalGraphicCounts[pgItm.itemLink.name] == null) {

        globalGraphicCounts[pgItm.itemLink.name] = 1;

        } else {

        globalGraphicCounts[pgItm.itemLink.name] += 1;

        }

        if (pageGraphicCounts[pgItm.itemLink.name] == null) {

        pageGraphicCounts[pgItm.itemLink.name] = 1;

        } else {

        pageGraphicCounts[pgItm.itemLink.name] += 1;

        }

        //log("Page counts array is now of size: " + pageGraphicCounts.length);

       

       

        } else {

        log("         Image layer is visible: " + pgItm.itemLayer.visible + "  Item visisble: " + pgItm.visible + "  *** NOT Counting ***");

        }

        }

        } else if (pgItmType == "GraphicLine" || pgItmType == "Oval") {}

        else {

        log("      Unknown item of type " + pgItmType);

        //if (pgItm.groups && pgItm.groups.length > 0) log("   Text frame  contains " + pgItm.groups.length + " other groups.");

        //if (pgItm.textFrames && pgItm.textFrames.length > 0) log("   Text frame  contains " + pgItm.textFrames.length + " text frames.");

        //if (pgItm.tables && pgItm.tables.length > 0) log("   Text frame  contains " + pgItm.tables.length + " Tables.");

        if (pgItm.allPageItems && pgItm.allPageItems.length > 0)

        log("      Text frame  contains " + pgItm.allPageItems.length + " Total page items.");

        try {

        if (pgItm.allGraphics && pgItm.allGraphics.length > 0)

        log("      Text frame  contains " + pgItm.allGraphics.length + " Total graphics.");

        } catch (e) {}

        }

        }

        log("--------------------------------------------------");

        log("   End analysing page - " + inPage.name + "   id: " + inPage.id + " of document " + inFileName);

        log("--------------------------------------------------");

       

       

        // Only log graphics counts if this is NOT an embeded page. In this case, a parent page count array will not be passed in.

        var fooPageName = inPage.name;

        log("Checking if I need to log page counts for page: " + pageTitle + "   Embeded?   " + (inGraphicCountsArray != null));

        if (inGraphicCountsArray == null) {

        try {

        log("Logging page counts for page: " + trim(pageTitle));

        log("  PageTitle length: " + pageTitle.length + "   trimmed: " + trim(pageTitle).length);

        var titleChars = "";

        for (i = 0; i < pageTitle.length; i++) {

        titleChars += "|" + pageTitle.charCodeAt(i) + "| ";

        }

        log("  Characters in pageTitle: " + titleChars);

        var csvPageFilePath = saveCountsToFolder + trim(pageTitle) + ".csv"

        var pageCountFile = File(csvPageFilePath);

        log("Logging page counts to file: " + csvPageFilePath);

        var fileLineCount = 0;

        pageCountFile.encoding = "utf-8";

        pageCountFile.open("w");

        for (var gn in pageGraphicCounts) {

        pageCountFile.writeln(gn + "," + pageGraphicCounts[gn]);

        log("     Page count entry: " + gn + ":\t\t\t" + pageGraphicCounts[gn]);

        fileLineCount++;

        }

        pageCountFile.close();

        log(" Closed page count file: " + csvPageFilePath);

        if (fileLineCount == 0) {

        log("Removing empty count file " + csvPageFilePath + ".");

        pageCountFile.remove();

        emptyCountFileCount++;

        }

       

       

        } catch (e) {

        log("  Error!Unable to write image counts to output file. Please make sure directory where document is located is writable.");

        alert("Error!\n\nUnable to write image counts to output file. Please make sure directory where document is located is writable.");

        exit();

        }

        } else {

        log("   Not writing graphics count file, as  I'm analysing an embeded page. ");

        }

       

       

        log("Leaving routine...");

       

       

      }

       

       

      log("---------------------------------------------------------");

      log("Starting Analysis.");

      log("  File: " + app.activeDocument.fullName.fsName);

      log("  Number of pages to analyse: " + app.activeDocument.pages.length);

      log("---------------------------------------------------------");

      var myBaseDocument = app.activeDocument;

      var myBaseDocumentPageCount = myBaseDocument.pages.length;

      for (var pageIndex = 0; pageIndex < myBaseDocumentPageCount; pageIndex++) {

        log('On page ' + (pageIndex + 1));

        var myBaseDocumentPage = myBaseDocument.pages[pageIndex];

        LogPageDetails(myBaseDocumentPage, myBaseDocument.fullName.fsName, null);

       

       

      }

      log("Done.....");

      log("Number of imported/Embeded documents: " + embededDocCount);

      log("Number of pages analysed: " + AnalysedPageCount);

      log("------------------------------------------------------------");

      log("GraphicsTotals");

      try {

        var GraphicCountTotal = 0;

        var GraphicsSumTotal = 0;

        for (gn in globalGraphicCounts) {

        //countFile.writeln(gn + "," + globalGraphicCounts[gn]);

        log("     " + gn + ":\t\t\t" + globalGraphicCounts[gn]);

        GraphicCountTotal++;

        GraphicsSumTotal += globalGraphicCounts[gn];

        }

      } catch (e) {

        alert("Error!\n\nUnable to write image counts to output file. Please make sure directory where document is located is writable.");

        exit();

      }

      var finalReport = "Success!!\n\n " + GraphicCountTotal + " distinct graphics found.\n\n" + GraphicsSumTotal + " individual graphics found.\n\n" + AnalysedPageCount + " pages analysed.\n\n" + embededDocCount + " embeded documents traversed.\n\n" + emptyCountFileCount + " output files with no count skipped.\n\n" + "Counts written to " + saveCountsToFolder;

      log(finalReport);

      alert(finalReport);

      logfile.close();

                } //end our code

               

      //function gets page range or "all" from user

      function dialogWChoices (dlgName, cancelIt, dLabel, maxPages) {

          var userCancelled = false;

          var origValue = app.scriptPreferences.userInteractionLevel;

        //make sure that user interaction levels will allow a dialog

        app.scriptPreferences.userInteractionLevel = UserInteractionLevels.INTERACT_WITH_ALL;

        //create the dialog

        var dlgRef = app.dialogs.add({name:dlgName, canCel:cancelIt, label:dLabel});

        //add a column

        var dlgColumn1 = dlgRef.dialogColumns.add();

          var dlgColumn2 = dlgRef.dialogColumns.add();

          var dlgColumn3 = dlgRef.dialogColumns.add();

        //add widgets for first column

        dlgColumn1.staticTexts.add({staticLabel: "PageRange:"});

        //add widgets to second column

        var radioGroup = dlgColumn2.radiobuttonGroups.add();

          radioGroup.radiobuttonControls.add({staticLabel:"All", checkedState:true});

          radioGroup.radiobuttonControls.add({staticLabel:"Range", checkedState:true});

          //add widgets to third column; put reference into a variable

          var emptyRow = dlgColumn3.dialogRows.add();

          emptyRow.staticTexts.add ({staticLabel: ""});

          var inputRow = dlgColumn3.dialogRows.add();

          var firstField = inputRow.integerEditboxes.add({minWidth:36, minimumValue:1,maximumValue:maxPages});

          inputRow.staticTexts.add ({staticLabel: " thru "});

          var secondField = inputRow.integerEditboxes.add({minWidth:36, minimumValue:1, maximumValue:maxPages});

        //show the dialog and capture the result

        if (dlgRef.show() == true) {

              var firstVal = 0;

              var secondVal = 0;

              var selButton = radioGroup.selectedButton;

              if (selButton == 1) {

        var firstVal = firstField.editValue;

        var secondVal = secondField.editValue;

          }

        } else {

              userCancelled = true;

        }

             dlgRef.destroy();

             app.scriptPreferences.userInteractionLevel = origValue;

          if (userCancelled) {

             throw ("User Cancelled");

          }

        //destroy the dialog; script doesn't get here if user cancels

        return [selButton, firstVal, secondVal];

      }

       

      __________________________________________________________________________________________ _________________

      Existing script.

       

      #target "indesign"

       

       

      function trim(s) {

        return s.replace(/^(\s|\n|\t|\uFEFF)+|(\s|\n|\t|\uFEFF)+$/g, '');

      };

       

       

      function ltrim(s) {

        return s.replace(/^(\s|\n|\t|\uFEFF)+/, '');

      };

       

       

      function rtrim(s) {

        return s.replace(/(\s|\n|\t|\uFEFF)+$/, '');

      };

       

       

      //var foo = File.saveDialog("Choose folder that count files will be placed in.");

      //exit();

       

       

      $.level = 2

       

       

        var rootFileFolder = app.activeDocument.filePath.fsName;

       

       

      var rootFileFolderObj = new Folder(rootFileFolder);

      var saveCountsToFolderObj = rootFileFolderObj.selectDlg("This script will create a series of .csv files containing image counts for each page in the current document.\nPlease select the folder to save the count files to.");

      if (saveCountsToFolderObj == null) {

        alert("No output folder was selected. Aborting script.\n\nPlease run again and select an output folder.");

        exit();

      }

      var saveCountsToFolder = saveCountsToFolderObj.fsName;

      if (saveCountsToFolder.indexOf("/") != -1) {

        saveCountsToFolder += "/";

      } else if (saveCountsToFolder.indexOf("\\") != -1) {

        saveCountsToFolder += "\\";

      }

       

       

      try {

        var filePathMinusExtension = app.activeDocument.fullName.fsName.substr(0, app.activeDocument.fullName.fsName.lastIndexOf("."));

        var logfile = File(filePathMinusExtension + "_DebugLog.txt");

        logfile.encoding = "UTF-8";

        logfile.open("w");

        //var csvFilePath = filePathMinusExtension + "_ImageCounts.csv"

        //var countFile = File(csvFilePath);

        //countFile.open("w");

      } catch (e) {

        alert("Error!\n\nDocument must be saved once before image count file can be created.");

        exit();

      }

      var globalGraphicCounts = [];

       

       

      var embededDocCount = 0;

      var AnalysedPageCount = 0;

      var emptyCountFileCount = 0;

       

       

      function log(inStr) {

        //date = new Date();

       

       

        logfile.writeln(inStr);

        //$.writeln(date.toLocaleTimeString() + "  :  " + inStr);

      }

       

       

      function getImpPage(obj) {

        if (obj.constructor.name == "ImportedPage")

        return obj;

        try {

        return (obj.hasOwnProperty("importedPages") ? obj.importedPages[0] : obj.indesignPageItems[0]);

        } catch (e) {

        return null;

        }

      } // end of getImpPage

       

       

       

       

      function LogPageDetails(inPage, inFileName, inGraphicCountsArray) {

        AnalysedPageCount++;

        var pageGraphicCounts;

        // If an existing graphic counts array is passed in, then we are recusivly counting an embeded document, and just add the graphics to the existing page.

        if (inGraphicCountsArray)

        pageGraphicCounts = inGraphicCountsArray;

        else

        pageGraphicCounts = [];

       

       

        var pageTitle = "UntitledPage_Number_" + inPage.id;

       

       

        log("--------------------------------------------------");

        log("   Begin analysing page - " + inPage.name + "   id: " + inPage.id + " of document " + inFileName);

        log("--------------------------------------------------");

        log("   Page has " + inPage.allPageItems.length + " items");

        log("   Page has " + inPage.allGraphics.length + " graphics items");

       

       

        //if (inPage.allGraphics.length > 0) {

        //log("Global graphic items:");

        //for (gi = 0; gi < inPage.allGraphics.length; gi++) {

        // var myGi = inPage.allGraphics[gi];

        // if (myGi.imageTypeName != "InDesign") {

        //log("   Graphics Item[" + gi + "]  file name: " + myGi.itemLink.name);

        //log("   Graphics Item[" + gi + "]  id: " + myGi.id);

        //log("   Graphics Item[" + gi + "]  image Type: " + myGi.imageTypeName);

        //log("   Graphics Item[" + gi + "]  file: " + myGi.itemLink.filePath);

        //log("    Graphics Item[" + gi + "]  layer id: " + myGi.itemLayer.id);

        //log("   ..................................");

        // }

        //}

        //}

       

       

        log("Page items:");

        for (var pgItmNo = 0; pgItmNo < inPage.allPageItems.length; pgItmNo++) {

        var pgItm = inPage.allPageItems[pgItmNo];

        var pgItmType = pgItm.constructor.name;

        log("   Page item " + pgItmNo + "  Type  " + pgItmType);

       

       

        if (pgItm.allGraphics.length > 0) {

        log("Page Item all graphics list contains " + pgItm.allGraphics.length + " items");

        for (gi = 0; gi < pgItm.allGraphics.length; gi++) {

        var myGi = pgItm.allGraphics[gi];

        if (myGi.imageTypeName != "InDesign") {

        //log("      Inner graphics Item[" + gi + "]  file name: " + myGi.itemLink.name);

        //log("      Inner graphics Item[" + gi + "]  id: " + myGi.id);

        //log("      Inner graphics Item[" + gi + "]  image Type: " + myGi.imageTypeName);

        //log("      Inner graphics Item[" + gi + "]  layer id: " + myGi.itemLayer.id);

        //log("      Inner graphics Item[" + gi + "]  file: " + myGi.itemLink.filePath);

        //log("      ..................................");

       

       

        //if (globalGraphicCounts[myGi.itemLink.name] == null) {

        //    globalGraphicCounts[myGi.itemLink.name] = 1;

        //} else {

        //    globalGraphicCounts[myGi.itemLink.name] += 1;

        //}

        } else {

        log("   Found item of type inDesign. Name: " + myGi.name + "Skipping for now, as not sure what to do here");

        }

        }

        }

       

       

        if (pgItmType == "TextFrame") {

        log("   Text object frame style: " + pgItm.appliedObjectStyle.name);

        if (pgItm.paragraphs.length > 0) {

        log("   text frame has " + pgItm.paragraphs.length + " paragraphs");

        for (var paragraphNumber = 0; paragraphNumber < pgItm.paragraphs.length; paragraphNumber++) {

        var myParagraph = pgItm.paragraphs[paragraphNumber];

        var myParagraphStyle = myParagraph.appliedParagraphStyle.name.toLowerCase();

        log("   Text paragraph style: |" + myParagraphStyle + "|");

       

       

        if (myParagraphStyle == "page head and subhead_top left_nested_every page") {

        var paragraphTexts = myParagraph.texts;

        log("   Found page title paragraph. Number of text sections: " + paragraphTexts.length);

        if (paragraphTexts.length > 0) {

        log("    Number of text sections in page title paragraph: " + paragraphTexts.length);

        for (var textNumber = 0; textNumber < paragraphTexts.length; textNumber++) {

        var myText = paragraphTexts[textNumber].contents;

        log("   In inner text block loop. Counter: " + textNumber + "   text: " + myText);

        if (myText.length > 0) {

        pageTitle = myText;

        log("Found page title!   Title: " + pageTitle);

        } else {

        log("   Skipping blank page title text section");

        }

        }

        } else {

        log("   Found no text sections in page title paragraph.");

        }

        } else {

        log("   Found text element that is not page title.");

        }

        }

       

       

        }

       

        //if (pgItm.textVariableInstances.length > 0) {

        // log("   Text frame contains " + pgItm.textVariableInstances.length + " variable instances");

        // for (var vii = 0; vii < pgItm.textVariableInstances.length; vii++) {

        // var vi = pgItm.textVariableInstances[vii];

        // log("         VariableInstance name: " + vi.name + "     Visible: " + pgItm.visible);

        // }

        //}

        //if (pgItm.groups.length > 0)

        // log("      Text frame  contains " + pgItm.groups.length + " other groups.");

        //if (pgItm.textFrames.length > 0)

        // log("      Text frame  contains " + pgItm.textFrames.length + " text frames.");

        //if (pgItm.tables.length > 0)

        // log("      Text frame  contains " + pgItm.tables.length + " Tables.");

        //if (pgItm.allPageItems.length > 0)

        // log("      Text frame  contains " + pgItm.allPageItems.length + " Total page items.");

        //if (pgItm.allGraphics.length > 0)

        // log("      Text frame  contains " + pgItm.AllGraphics.length + " Total graphics.");

       

       

        } else if (pgItmType == "Group") {

        var tfs = pgItm.textFrames;

        log("      In group, with " + tfs.length + " text frames.");

        for (tfi = 0; tfi < tfs.length; tfi++) {

        var tf = pgItm.textFrames[tfi];

        log("Looking at text frame " + tfi);

        if (tf.textVariableInstances.length > 0) {

        for (var vii = 0; vii < tf.textVariableInstances.length; vii++) {

        var vi = tf.textVariableInstances[vii];

        log("         VariableInstance name: " + vi.name + "    Visible: " + tf.visible);

        }

        }

        if (tf.groups.length > 0)

        log("      Text frame  contains " + tf.groups.length + " other groups.");

        if (tf.textFrames.length > 0)

        log("      Text frame  contains " + tf.textFrames.length + " text frames.");

        if (tf.tables.length > 0)

        log("      Text frame  contains " + tf.tables.length + " Tables.");

        if (tf.allPageItems.length > 0)

        log("      Text frame  contains " + tf.allPageItems.length + " Total page items.");

        if (tf.allGraphics.length > 0)

        log("      Text frame  contains " + tf.AllGraphics.length + " Total graphics.");

        }

        } else if (pgItmType == "Rectangle") {

        var tfs = pgItm.textFrames;

        for (tfi = 0; tfi < tfs.length; tfi++) {

        var tf = pgItm.textFrames[tfi];

        log("      In rectangle with " + tf.textVariableInstances.length + "text variables.");

        if (tf.textVariableInstances.length > 0) {

        for (var vii = 0; vii < tf.textVariableInstances.length; vii++) {

        var vi = tf.textVariableInstances[vii]

        log("         VariableInstance name: " + vi.name + "     Visible: " + tf.visible);

        }

        }

        if (tf.groups.length > 0)

        log("      Rectangle frame  contains " + tf.groups.length + " other groups.");

        if (tf.textFrames.length > 0)

        log("      Rectangle frame  contains " + tf.textFrames.length + " text frames.");

        //if (tf.tables.length > 0) log("   Text frame  contains " + tf.tables.length + " Tables.");

        if (tf.allPageItems.length > 0)

        log("      Rectangle frame  contains " + tf.allPageItems.length + " Total page items.");

        if (tf.allGraphics.length > 0)

        log("      Rectangle frame  contains " + tf.AllGraphics.length + " Total graphics.");

        }

        } else if (pgItmType == "ImportedPage") {

        embededDocumentFilename = "";

        if (pgItm && pgItm.itemLink && pgItm.itemLink.filePath)

        embededDocumentFilename = pgItm.itemLink.filePath;

        log("------------------------------------------------------------------------------------ -");

        log("    Begin embeded document - filename: " + embededDocumentFilename);

        log("------------------------------------------------------------------------------------ -");

        embededDocCount++;

        //if (pgItm.allPageItems.length > 0) log("   Text frame  contains " + pgItm.allPageItems.length + " other groups.");

        //if (pgItm.groups.length > 0) log("   Text frame  contains " + pgItm.groups.length + " other groups.");

        //if (pgItm.textFrames.length > 0) log("   Text frame  contains " + pgItm.textFrames.length + " text frames.");

        //if (pgItm.tables.length > 0) log("   Text frame  contains " + pgItm.tables.length + " Tables.");

        //if (pgItm.allPageItems.length > 0) log("   Text frame  contains " + pgItm.allPageItems.length + " Total page items.");

       

       

        try {

        log("   Name of embeded file to analyse: " + pgItm.itemLink.filePath);

        var newDoc = app.open(File(pgItm.itemLink.filePath))

        log("   Number of pages in embeded document to analyse: " + newDoc.pages.length);

        for (ImportedDocPageIndex = 0; ImportedDocPageIndex < newDoc.pages.length; ImportedDocPageIndex++) {

        var attachedPage = newDoc.pages[ImportedDocPageIndex];

       

       

        LogPageDetails(attachedPage, pgItm.itemLink.filePath + " (embeded)", pageGraphicCounts);

        }

        log("  Closing embeded document. Name: " + embededDocumentFilename);

        newDoc.close();

        log("Done closing embeded document. Name: " + embededDocumentFilename);

       

       

        } catch (e) {

        log("  Could not read embeded doc");

        }

        log("------------------------------------------------------------------------------------ -");

        log("    END embeded document - filename: " + embededDocumentFilename);

        log("------------------------------------------------------------------------------------ -");

        } else if (pgItmType == "PDF") {

        log("         Embeded Pdf found. Name: " + pgItm.itemLink.name);

       

       

        if (pgItm.itemLayer.visible == true && pgItm.visible == true) {

        log("         Layer is visible: " + pgItm.itemLayer.visible + "  Item is visible: " + pgItm.visible + "      **** Counting ****");

        if (globalGraphicCounts[pgItm.itemLink.name] == null) {

        globalGraphicCounts[pgItm.itemLink.name] = 1;

        } else {

        globalGraphicCounts[pgItm.itemLink.name] += 1;

        }

       

       

        if (pageGraphicCounts[pgItm.itemLink.name] == null) {

        pageGraphicCounts[pgItm.itemLink.name] = 1;

        } else {

        pageGraphicCounts[pgItm.itemLink.name] += 1;

        }

        //log("Page counts array is now of size: " + pageGraphicCounts.length);

        } else {

        log("         Layer is visible: " + pgItm.itemLayer.visible + "  Item visisble: " + pgItm.visible + "  *** NOT Counting ***");

        }

       

       

        } else if (pgItmType == "Image") {

        log("         Image item found.");

        if (pgItm.imageTypeName != "InDesign") {

        log("         Image file name: " + pgItm.itemLink.name + " id: " + pgItm.id + " Type: " + pgItm.imageTypeName + "layer id: " + pgItm.itemLayer.id);

        //log("         Image file: " + pgItm.itemLink.filePath);

       

       

        // Don't count it if the layer it is in is not visible

        if (pgItm.itemLayer.visible == true && pgItm.visible == true) {

        log("         Image layer is visible: " + pgItm.itemLayer.visible + "  Item is visible: " + pgItm.visible + "      **** Counting ****");

        if (globalGraphicCounts[pgItm.itemLink.name] == null) {

        globalGraphicCounts[pgItm.itemLink.name] = 1;

        } else {

        globalGraphicCounts[pgItm.itemLink.name] += 1;

        }

        if (pageGraphicCounts[pgItm.itemLink.name] == null) {

        pageGraphicCounts[pgItm.itemLink.name] = 1;

        } else {

        pageGraphicCounts[pgItm.itemLink.name] += 1;

        }

        //log("Page counts array is now of size: " + pageGraphicCounts.length);

       

       

        } else {

        log("         Image layer is visible: " + pgItm.itemLayer.visible + "  Item visisble: " + pgItm.visible + "  *** NOT Counting ***");

        }

        }

        } else if (pgItmType == "GraphicLine" || pgItmType == "Oval") {}

        else {

        log("      Unknown item of type " + pgItmType);

        //if (pgItm.groups && pgItm.groups.length > 0) log("   Text frame  contains " + pgItm.groups.length + " other groups.");

        //if (pgItm.textFrames && pgItm.textFrames.length > 0) log("   Text frame  contains " + pgItm.textFrames.length + " text frames.");

        //if (pgItm.tables && pgItm.tables.length > 0) log("   Text frame  contains " + pgItm.tables.length + " Tables.");

        if (pgItm.allPageItems && pgItm.allPageItems.length > 0)

        log("      Text frame  contains " + pgItm.allPageItems.length + " Total page items.");

        try {

        if (pgItm.allGraphics && pgItm.allGraphics.length > 0)

        log("      Text frame  contains " + pgItm.allGraphics.length + " Total graphics.");

        } catch (e) {}

        }

        }

        log("--------------------------------------------------");

        log("   End analysing page - " + inPage.name + "   id: " + inPage.id + " of document " + inFileName);

        log("--------------------------------------------------");

       

       

        // Only log graphics counts if this is NOT an embeded page. In this case, a parent page count array will not be passed in.

        var fooPageName = inPage.name;

        log("Checking if I need to log page counts for page: " + pageTitle + "   Embeded?   " + (inGraphicCountsArray != null));

        if (inGraphicCountsArray == null) {

        try {

        log("Logging page counts for page: " + trim(pageTitle));

        log("  PageTitle length: " + pageTitle.length + "   trimmed: " + trim(pageTitle).length);

        var titleChars = "";

        for (i = 0; i < pageTitle.length; i++) {

        titleChars += "|" + pageTitle.charCodeAt(i) + "| ";

        }

        log("  Characters in pageTitle: " + titleChars);

        var csvPageFilePath = saveCountsToFolder + trim(pageTitle) + ".csv"

        var pageCountFile = File(csvPageFilePath);

        log("Logging page counts to file: " + csvPageFilePath);

        var fileLineCount = 0;

        pageCountFile.encoding = "utf-8";

        pageCountFile.open("w");

        for (var gn in pageGraphicCounts) {

        pageCountFile.writeln(gn + "," + pageGraphicCounts[gn]);

        log("     Page count entry: " + gn + ":\t\t\t" + pageGraphicCounts[gn]);

        fileLineCount++;

        }

        pageCountFile.close();

        log(" Closed page count file: " + csvPageFilePath);

        if (fileLineCount == 0) {

        log("Removing empty count file " + csvPageFilePath + ".");

        pageCountFile.remove();

        emptyCountFileCount++;

        }

       

       

        } catch (e) {

        log("  Error!Unable to write image counts to output file. Please make sure directory where document is located is writable.");

        alert("Error!\n\nUnable to write image counts to output file. Please make sure directory where document is located is writable.");

        exit();

        }

        } else {

        log("   Not writing graphics count file, as  I'm analysing an embeded page. ");

        }

       

       

        log("Leaving routine...");

       

       

      }

       

       

      log("---------------------------------------------------------");

      log("Starting Analysis.");

      log("  File: " + app.activeDocument.fullName.fsName);

      log("  Number of pages to analyse: " + app.activeDocument.pages.length);

      log("---------------------------------------------------------");

      var myBaseDocument = app.activeDocument;

      var myBaseDocumentPageCount = myBaseDocument.pages.length;

      for (var pageIndex = 0; pageIndex < myBaseDocumentPageCount; pageIndex++) {

        log('On page ' + (pageIndex + 1));

        var myBaseDocumentPage = myBaseDocument.pages[pageIndex];

        LogPageDetails(myBaseDocumentPage, myBaseDocument.fullName.fsName, null);

       

       

      }

      log("Done.....");

      log("Number of imported/Embeded documents: " + embededDocCount);

      log("Number of pages analysed: " + AnalysedPageCount);

      log("------------------------------------------------------------");

      log("GraphicsTotals");

      try {

        var GraphicCountTotal = 0;

        var GraphicsSumTotal = 0;

        for (gn in globalGraphicCounts) {

        //countFile.writeln(gn + "," + globalGraphicCounts[gn]);

        log("     " + gn + ":\t\t\t" + globalGraphicCounts[gn]);

        GraphicCountTotal++;

        GraphicsSumTotal += globalGraphicCounts[gn];

        }

      } catch (e) {

        alert("Error!\n\nUnable to write image counts to output file. Please make sure directory where document is located is writable.");

        exit();

      }

      var finalReport = "Success!!\n\n " + GraphicCountTotal + " distinct graphics found.\n\n" + GraphicsSumTotal + " individual graphics found.\n\n" + AnalysedPageCount + " pages analysed.\n\n" + embededDocCount + " embeded documents traversed.\n\n" + emptyCountFileCount + " output files with no count skipped.\n\n" + "Counts written to " + saveCountsToFolder;

      log(finalReport);

      alert(finalReport);

      logfile.close();