8 Replies Latest reply on Jun 5, 2013 5:32 AM by patrickbcm

    find text place image

    patrickbcm

      Hello

       

      I have a script that find text and replaced it with a image, but it makes a new document and i want it in the same document that i have open.

      Can somebody help me with this problem. See script below. I work with Indesign CS 5 mac.

       

      Kinde regards,

      Patrick

       

      #target indesign

      var myDialogResult = CreateDialog();

      if (myDialogResult == undefined) exit();

      CheckIfChosenFoldersExist();

      var myIndFiles = [];

      var mySubFolders = [];

      CheckFolder(myDialogResult.indFolder);

      if (myIndFiles.length == 0) err("No InDesign files have been found in the selected folder and its subfolders.");

      var myStartFolder = myDialogResult.imagesFolder.parent;

       

       

      mySubFolders = getSubFolders(myStartFolder);

       

       

      WriteToFile("\r--------------------- Script started -- " + GetDate() + "---------------------\n");

      app.scriptPreferences.userInteractionLevel = UserInteractionLevels.neverInteract;

       

       

      for (f = 0; f < myIndFiles.length; f++) {

                ProcessIndFile(myIndFiles[f]);

      }

       

       

      app.scriptPreferences.userInteractionLevel = UserInteractionLevels.interactWithAll;

      app.findGrepPreferences = app.changeGrepPreferences = null;

      WriteToFile("--------------------- Script finished -- " + GetDate() + "---------------------\r\r");

      alert("All done!");

      // ------------------------------------------------- FUNCTIONS -------------------------------------------------

      function PlaceImages() {

                app.findGrepPreferences = app.changeGrepPreferences = null;

                app.findGrepPreferences.findWhat = '@.+?@';

                var myFoundItems = app.activeDocument.findGrep();

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

                          var myName = myFoundItems[i].contents.replace (/@/g, "");

                          var myFile = new File(myDialogResult.imagesFolder + "/" + myName);

                          var myFrame = myFoundItems[i].parentTextFrames[0];

       

                          if (myFile.exists) {

                                    PlaceIntoFrame(myFrame, myFile);

                                    continue;

                          }

       

       

                          if (!SearchInSubfolders(myName, myFrame)) {

                                    WriteToFile("\tNOT FOUND  -- " + myFile.fsName + "\n");

                          }

                }

      }

      //---------------------------------------------------------------------------------------- ----------------------

      function SearchInSubfolders(myName, myFrame) {

                for (j = 0; j < mySubFolders.length; j++) {

                          var myFolder = mySubFolders[j];

                          var myFile = new File(myFolder + "/" + myName);

                          if (myFile.exists) {

                                    PlaceIntoFrame(myFrame, myFile);

                                    return true;

                          }

                }

                return false;

      }

      //---------------------------------------------------------------------------------------- ----------------------

      function PlaceIntoFrame(myFrame, myFile) {

                try {

                          if (myFrame.characters.length < 100) {

                                    myFrame.getElements()[0].place(myFile);

       

                                    switch(myDialogResult.myRadSelected)          {

                                              case 2:

                                                        myFrame.fit(FitOptions.CENTER_CONTENT);

                                              break;

       

       

                                              case 3:

                                                        myFrame.fit(FitOptions.FRAME_TO_CONTENT);

                                              break;

       

                                              case 4:

                                                        myFrame.fit(FitOptions.PROPORTIONALLY);

                                              break;

       

                                              default:

                                              // do nothing

                                    }

                          }

       

                          WriteToFile("\tPlaced -- " + myFile.fsName+ "\n");

                }

                catch(e) {

                          WriteToFile("\tSome error occured while placing -- " + myFile.fsName + "\n");

                }

      }

      //---------------------------------------------------------------------------------------- ----------------------

      function CheckFolder(folder) {

                var fileList = folder.getFiles()

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

                          var file = fileList[i];

                          if (file instanceof File && file.name.match(/\.indd$/i)) {

                                    myIndFiles.push(file);

                          }

                          else if (file instanceof Folder) {

                                    CheckFolder(file);

                          }

                }

      }

      //---------------------------------------------------------------------------------------- ----------------------

      function getSubFolders(theFolder) {

                var myFileList = theFolder.getFiles();

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

                          var myFile = myFileList[i];

                          if (myFile instanceof Folder){

                                    mySubFolders.push(myFile.absoluteURI);

                                    getSubFolders(myFile);

                          }

                }

                return mySubFolders;

      }

      //---------------------------------------------------------------------------------------- ----------------------

      function err(e, icon){

                alert(e, "Place Images Script", icon);

                exit();

      }

       

       

      function ProcessIndFile(myFile) {

                try {

                          var myDoc = app.open(myFile);

                          WriteToFile(myDoc.name + "\n");

                          var myNewFile = new File(myFile.fsName.replace(/\.indd$/i, "_Backup.indd"));

                          myFile.copy(myNewFile);

                }

                catch(e) {

                          WriteToFile("Cannot open file -- " + myFile.fsName + "\nError: " + e.message + " (Error# " + e.number  + ")\n");

                }

                PlaceImages();

                myDoc = myDoc.save();

                myDoc.close();

      }

      //---------------------------------------------------------------------------------------- ----------------------

      function CreateDialog() {

                var myIndFolder, myImagesFolder;

                if (app.extractLabel("Kas_PlaceImages_IndFolderPath") != "") {

                          var myIndFolderPath = app.extractLabel("Kas_PlaceImages_IndFolderPath");

                }

                else {

                          var myIndFolderPath = "No folder has been selected";

                }

                if (app.extractLabel("Kas_PlaceImages_ImageFolderPath") != "") {

                          var myImageFolderPath = app.extractLabel("Kas_PlaceImages_ImageFolderPath");

                }

                else {

                          var myImageFolderPath = "No folder has been selected";

                }

                var myDialog = new Window('dialog', 'Place Images');

                myDialog.orientation = 'row';

                myDialog.alignChildren = 'top';

                var myPanel = myDialog.add('panel', undefined, 'Choose folders for:');

                var myIndFolderStTxt = myPanel.add('statictext', undefined, myIndFolderPath);

                var myButtonInd = myPanel.add('button', undefined, 'InDesign files', {name:'indd'});

                var myImagesFolderStTxt = myPanel.add('statictext', undefined, myImageFolderPath);

                var myButtonImages = myPanel.add('button', undefined, 'Image files', {name:'images'});

       

                var myGroup = myDialog.add('group');

                myGroup.orientation = 'column';

                var myRadioPanel = myGroup.add('panel', undefined, 'After placing:');

                myRadioPanel.alignChildren = 'left';

                var myRadioBtn1 = myRadioPanel.add('radiobutton', undefined, 'do nothing');

                var myRadioBtn2 = myRadioPanel.add('radiobutton', undefined, 'center content');

                var myRadioBtn3 = myRadioPanel.add('radiobutton', undefined, 'fit frame to content');

                var myRadioBtn4 = myRadioPanel.add('radiobutton', undefined, 'fit content proportionally');

       

                if (app.extractLabel("Kas_PlaceImages_RadioSelected") != "") {

                          eval("myRadioBtn" + app.extractLabel("Kas_PlaceImages_RadioSelected") + ".value= true");

                }

                else {

                          myRadioBtn1.value = true;

                }

       

                var myOkCancelGroup = myGroup.add('group');

                myOkCancelGroup.orientation = 'row';

                var myOkBtn = myOkCancelGroup.add('button', undefined, 'Place', {name:'ok'});

                var myCancelBtn = myOkCancelGroup.add('button', undefined, 'Quit', {name:'cancel'});

       

       

                myButtonInd.onClick = function() {

                          myIndFolder = Folder.selectDialog ('Chose a folder for InDesign documents');

                          if (myIndFolder != null) {

                                    myIndFolderStTxt.text = myIndFolder.fsName;

                          }

                }

                myButtonImages.onClick = function() {

                          myImagesFolder = Folder.selectDialog ('Chose a folder for Images');

                          if (myImagesFolder != null) {

                                    myImagesFolderStTxt.text = myImagesFolder.fsName;

                          }

                }

                var myShowDialog = myDialog.show();

       

       

                if (myIndFolder == undefined) {

                          if (myIndFolderStTxt.text == "No folder has been selected") {

                                    myIndFolder = null;

                          }

                          else {

                                    myIndFolder = new Folder(myIndFolderStTxt.text);

                          }

                }

       

       

                if (myImagesFolder == undefined) {

                          if (myImagesFolderStTxt.text == "No folder has been selected") {

                                    myImagesFolder = null;

                          }

                          else {

                                    myImagesFolder = new Folder(myImagesFolderStTxt.text);

                          }

                }

       

       

                var myRadSelected;

                if (myRadioBtn1.value) {

                          myRadSelected = 1;

                }

                else if(myRadioBtn2.value) {

                          myRadSelected = 2;

                }

                else if(myRadioBtn3.value) {

                          myRadSelected = 3;

                }

                else if(myRadioBtn4.value) {

                          myRadSelected = 4;

                }

       

       

                app.insertLabel("Kas_PlaceImages_RadioSelected", myRadSelected + "");

                app.insertLabel("Kas_PlaceImages_IndFolderPath", myIndFolderStTxt.text);

                app.insertLabel("Kas_PlaceImages_ImageFolderPath", myImagesFolderStTxt.text);

       

                if (myShowDialog== 1) {

                          var myResult = {};

                          myResult.indFolder = myIndFolder;

                          myResult.imagesFolder = myImagesFolder;

                          myResult.myRadSelected = myRadSelected;

                }

                return myResult;

      }

      //---------------------------------------------------------------------------------------- ----------------------

      function WriteToFile(myText) {

                myFile = new File("~/Desktop/Place Images Report.txt");

                if ( myFile.exists ) {

                          myFile.open("e");

                          myFile.seek(0, 2);

                }

                else {

                          myFile.open("w");

                }

                myFile.write(myText);

                myFile.close();

      }

      //---------------------------------------------------------------------------------------- ----------------------

      function GetDate() {

                var myDate = new Date();

                if ((myDate.getYear() - 100) < 10) {

                          var myYear = "0" + new String((myDate.getYear() - 100));

                } else {

                          var myYear = new String ((myDate.getYear() - 100));

                }

                var myDateString = (myDate.getMonth() + 1) + "/" + myDate.getDate() + "/" + myYear + " " + myDate.getHours() + ":" + myDate.getMinutes() + ":" + myDate.getSeconds();

                return myDateString;

      }

      //---------------------------------------------------------------------------------------- ----------------------

      function CheckIfChosenFoldersExist() {

                 if (myDialogResult.indFolder == null) {

                          err("No folder has been chosen for InDesign files.", true);

                }

                else if (myDialogResult.indFolder.constructor.name == "Folder") {

                          if (!myDialogResult.indFolder.exists) {

                                    err("Folder \"" + myDialogResult.indFolder.fsName + "\" chosen for InDesign files does not exist.", true);

                          }

                }

       

       

                if (myDialogResult.imagesFolder == null) {

                          err("No folder has been chosen for pictures.", true);

                }

                else if (myDialogResult.imagesFolder.constructor.name == "Folder") {

                          if (!myDialogResult.imagesFolder.exists) {

                                    err("Folder \"" + myDialogResult.imagesFolder.fsName + "\" chosen for images does not exist.", true);

                          }

                }

      }

        • 1. Re: find text place image
          Jump_Over Level 5

          Hi,

           

          Looks like it is opening every doc from chosen folder (and subfolders)
          making a backup copy

          and placing images to original.

           

          How your "new document" is named and where is saved?

           

          Jarek

          • 2. Re: find text place image
            patrickbcm Level 1

            It's saved in the folder that i choose in opening and the name is the originals name and at the end _backup

            • 3. Re: find text place image
              Jump_Over Level 5

              Hi,

               

              Accorging to this function:

               

              function ProcessIndFile(myFile) {
              try {
                   var myDoc = app.open(myFile);
                   WriteToFile(myDoc.name + "\n");
                   var myNewFile = new File(myFile.fsName.replace(/\.indd$/i, "_Backup.indd"));
                   myFile.copy(myNewFile);
                   }
              catch(e) {
                   WriteToFile("Cannot open file -- " + myFile.fsName + "\nError: " + e.message + " (Error# " + e.number  + ")\n");
                   }
              PlaceImages();
              myDoc = myDoc.save();
              myDoc.close();
              }
              

               

              it supposes to make a backup copy first and place images after.

               

              However you could deactivate two lines:

                   //var myNewFile = new File(myFile.fsName.replace(/\.indd$/i, "_Backup.indd"));
                   //myFile.copy(myNewFile);
              

               

               

              Jarek

              1 person found this helpful
              • 4. Re: find text place image
                patrickbcm Level 1

                Yes it's working.

                Thanks a lot

                • 5. Re: find text place image
                  paolbot

                  Try this, I use it every day

                   

                  /*******************ImagePlacer***************************

                      this script will addimages to the document by

                      substituting them with the name of the image file

                      between @s (file format included[@mypic.bmp@]),

                      selecting them from a specified file (see below)

                      and applying object styles to them, as well as

                      applying the right tab i necesary.

                      It then looks for overflows in the document. If an

                      overset is found, it will resize to margin size the

                      text frame and if overset continues, it will add a

                      new page and frame, which then will be linked

                      to the previous frame, allowing the story flow.

                      -

                      Questo file deve essere copiato nella cartella Script di InDesign

                  **********************************************************/

                  //Creates a new document using the specified document preset.

                  //Replace "myDocumentPreset" in the following line with the name

                  //of the document preset you want to use.

                  var myDocument = app.documents.add(true,app.documentPresets.item("MyPreset"));

                   

                   

                  //If the active document has not been saved (ever), save it.

                  if(app.activeDocument.saved == false){

                  //If you do not provide a file name, InDesign displays the Save dialog box.

                  app.activeDocument.save(new File("/Users/paolbot/Desktop/Document.indd"));

                  }

                   

                   

                  function main()

                  {

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

                  var myPage = myDocument.pages.item(0);

                  var myTextFrame = myPage.textFrames.add({geometricBounds:myGetBounds(myDocument,myPage)});

                  myTextFrame.textFramePreferences.textColumnCount = 7;

                  myTextFrame.place(File("/Users/paolbot/Desktop/text.txt"));

                  //Place a text file in the text frame.

                  //Parameters for TextFrame.place():

                  //File as File object,

                  //[ShowingOptions as Boolean = False]

                  //You'll have to fill in your own file path.

                   

                   

                  //Define GREP search

                  var grepFind ="@@@.+@@@";

                   

                   

                  //Name of the folder where pdf are

                  var myFiguresFolder = "pictures";

                   

                   

                  // Stile Paragrafo applicato

                  var myPStyle = myDocument.paragraphStyles.item("Normal");

                     

                  var NextPStyleCS = myDocument.paragraphStyles.item("Par_Style");

                  var NextPStyleEN = myDocument.paragraphStyles.item("Par_Style_en");

                  var NextPStyleDE = myDocument.paragraphStyles.item("Par_Style_de");

                   

                   

                  // Text style applied

                  var myCStyle = myDocument.characterStyles.item("text");

                   

                   

                  //Object style applyed

                  var myOStyle = "";

                  var oStyle_1 = myDocument.objectStyles.item("Pictures");

                  var oStyle_2 = myDocument.objectStyles.item("Pictures");

                  var oStyle_3 = myDocument.objectStyles.item("Pictures");

                   

                   

                  //MEASUREMENTS

                  var maxWidth = 467; //Maximum width of an image

                  var maxHeight = 666; //Maximum Height of an image

                  var colWidth = 468; //Width of the main columb (340pt) + maximum Tab (128pt)

                  var maxTab = 0;

                  var xTab;

                  var xtTab;

                  var minTWidth = 340; //any image with a width below this will have the maximum Tab (maxTab) applied.

                  var PWidth; //Width of the Picture

                  var PHeight;//Picture Height

                  var myTotal;

                  • 6. Re: find text place image
                    patrickbcm Level 1

                    No i get thisSchermafbeelding 2013-06-05 om 13.41.37.png

                    • 7. Re: find text place image
                      Laubender Adobe Community Professional & MVP

                      @patrick – there is one closing bracket missing at the end of function main(){…}.
                      Just add the closing } at the very end of the script.

                       

                      (Did not test it, so I don't know, if other lines are missing too ;-))

                       

                      Uwe

                      • 8. Re: find text place image
                        patrickbcm Level 1

                        No now i get another fold.

                         

                        I changed the script what i use before what Jarek wrote and my problem is solved.