3 Replies Latest reply on Jun 18, 2013 8:59 PM by jonht

    Need critique for my script

    Muthuraj Durairaj Level 1

      Hi All,

       

      I am beginner in Indesign Javascript. I am learning it by experimenting with the help of Adobe Forums help.

       

      I am in a need to develop a script which has to convert US letter sized layout into A4 letter sized layout with the same page/content flow as it is in the US letter layout. We do have templates to create documents.

       

      I have developed a script (Thanks to the forum) which will take care of the conversion of US letter to A4 and retain the same X, Y position of required frames as per template.

       

      Although, it is working as expected, I am trying to deliver this script to my team as error free and professionaly developed.

       

      Here are the things need to be done in this working script.

       

      1. The functions are not properly built. I just made them as functions for ease of access

      2. There is no error capturing mechanism. I dont know how to add the try and catch(e) properly. The user should not get any javacript error message, rather a alert message window can appear with proper alert message and exit

       

      I need your help on this. It took me a month to develop this script and I managed to make it as workable. However, with your help I can deliver this better and proffessionaly. Please help me.

       

      Thanks.

       

      Regards,

      Muthuraj. D

       

      Note: I am really sorry, I could not find the file attachment option in this message. I am pasting the entire script here. Sorry for the trouble.

       

       

       

       

      main();
      function main(){
                //Make certain that user interaction (display of dialogs, etc.) is turned on.
                app.scriptPreferences.userInteractionLevel = UserInteractionLevels.interactWithAll;
                var myObject;
      //~      var myDocument = app.activeDocument;
                    if(app.documents.length != 0){
                  var myDocument = app.activeDocument;
                  var PageSize = myDocument.documentPreferences.pageSize;
                      if(PageSize != "Letter"){
                      //pageSize = "US"
                      //pageOrientation = PageOrientation.portrait;
                          alert ("Not a US Letter size document. Please try again with US Letter (8.5 in X 11 in) document size", "Invalid document size")
                    }
                      else {
      
                          SaveACopy();
                          myDisplayDialog();
      
      
                      }
              }
                    else { //implies user clicked cancel
                  alert("No document(s) are open. Please open a document and try again.", "No document");
              }
      //myDialog.destroy();
      }
      
      
      
      function progress_bar (w, stop){
          var pbar = w.add ("progressbar", undefined, 1, stop);
          pbar.preferredSize = [300,20];
          w.show ();
          return pbar;
      }
      
      
      function myDisplayDialog(){
                var myDialog = app.dialogs.add({name:"Enter copyright information"});
                var col1 = myDialog.dialogColumns.add();
                var col2 = myDialog.dialogColumns.add();
          col1.staticTexts.add({staticLabel:"Month:"});
                col1.staticTexts.add({staticLabel:"Year:"});
          col1.staticTexts.add({staticLabel:"Rev. no.:"});
          var myList = [ "January", "February",  "March", "April", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ];
          var myMonth = col2.dropdowns.add({stringList:myList, selectedIndex:0, minWidth:100});//{minWidth:100});
          var myYear = col2.textEditboxes.add({editContents:"2013", minWidth:100}); 
                var MyRev = col2.textEditboxes.add({minWidth:100});
          var myResult = myDialog.show();
      
      
              if(myYear.editContents == "") //entry is ""
              {
              alert("Please enter some text into the contents field.");
              myResult;
              }
              else if(myResult == true) //user entered datas
              {
                  var RevMonth = (myList [myMonth.selectedIndex]);
                  var RevYear = myYear.editContents;
                  var RevNumber = MyRev.editContents;
                  var RevToReplace1 = ", " + RevMonth + " " + RevYear;
                  var RevToReplace2 = ", " + RevMonth + " " + RevYear +", Rev. " + RevNumber;
      
      
                      app.findGrepPreferences = NothingEnum.nothing;
                      app.changeGrepPreferences = NothingEnum.nothing;
      
      
                      // grep find/change
                      app.findGrepPreferences = app.changeGrepPreferences = null;     
                      app.findGrepPreferences.findWhat = ",\\s+[\\l\\u]+?\\s?\\d{4},?\\s*[\\l\\u]*\\.*\\s*\\d*";
                      app.findGrepPreferences.appliedFont = "Simplified"
                      app.findGrepPreferences.pointSize = 7;
                      app.findGrepPreferences.fontStyle = "Light";
                      //app.findGrepPreferences.appliedParagraphStyle = app.activeDocument.paragraphStyleGroups.item("Back page"). paragraphStyles.item("Legal_7/9");
      
                          if (RevNumber == ""){
                          app.changeGrepPreferences.changeTo = RevToReplace1;
                          app.changeGrepPreferences.appliedFont = "Simplified"
                          app.changeGrepPreferences.pointSize = 7;
                          app.changeGrepPreferences.fontStyle = "Light";
                          //app.changeGrepPreferences.appliedParagraphStyle = app.activeDocument.paragraphStyleGroups.item("Back page"). paragraphStyles.item("Legal_7/9");
                          app.activeDocument.changeGrep();
                              }
                          if (RevNumber !== ""){
      //~                     else  {
                          app.changeGrepPreferences.changeTo = RevToReplace2;
                          app.changeGrepPreferences.appliedFont = "Simplified"
                          app.changeGrepPreferences.pointSize = 7;
                          app.changeGrepPreferences.fontStyle = "Light";
                          //app.changeGrepPreferences.appliedParagraphStyle = app.activeDocument.paragraphStyleGroups.item("Back page"). paragraphStyles.item("Legal_7/9");
                          app.activeDocument.changeGrep();
                              }
                      app.findGrepPreferences = NothingEnum.nothing;
                      app.changeGrepPreferences = NothingEnum.nothing;
                      var myCounter = 1;
                      app.scriptPreferences.userInteractionLevel = UserInteractionLevels.NEVER_INTERACT;
      
      
                          var myProgressWin = new Window ( "window", "ENN Conversion" );
                          var myDocument = app.activeDocument;
                          var myPages = myDocument.pages;
                          var myProgressBar = myProgressWin.add ("progressbar", [12, 12, 350, 24], 0, myPages.length);
                          var myProgressTxt = myProgressWin.add("statictext", undefined, "Converting from ENW to ENN. . . . ");
                          myProgressTxt.bounds = [0, 0, 340, 20];
                          myProgressTxt.alignment = "left";
                          myProgressWin.show();
                          // Progress bar --------------------------------------------------------------------- --------------
                          myCounter++;
                          // Progress bar --------------------------------------------------------------------- --------------
                          myProgressBar.value = myCounter;
                          myProgressTxt.text = String("Processing pages");
                          // Progress bar --------------------------------------------------------------------- --------------
                          SpreadtoSingle();
                          UnlockAllLayers();
                          addGuides();
                          ChangeLayout();
                          RemoveGuides();
                          RepositionTextFrames();
                          RepositionCoverPageFrames();
                          RepositionLogo();
                          FitTableFrameWidth();
                          UpdateSoMEURL();
                          UpdatePubNumber();
                          UpdateMetadata();
      
      
      //~                     // user functions
      //~                     $.sleep (400);
      //~                     }
      //~                     progress.parent.close();
      
      
                          var myDocument = app.activeDocument;
                          myDocument.save();
      
      
                          // Progress bar --------------------------------------------------------------------- --------------
                          myProgressWin.close();
                          // Progress bar --------------------------------------------------------------------- --------------
                          alert("ENN Conversion (A4, US English) completed successfully!", "Completed");
              }
              else //implies user clicked cancel
              {
              myDialog.destroy();
              }
      }
      
      
      function SpreadtoSingle() {
          var myDocument=app.activeDocument;
          myDocument.documentPreferences.allowPageShuffle = true;
          myDocument.documentPreferences.facingPages = false;
          myDocument.spreads.everyItem().allowPageShuffle = true;
      }
      
      
      function UnlockAllLayers() {
      var myDocument=app.activeDocument;
          myDocument.layers.everyItem().locked = false;
      }  
      
      
      function addGuides() {
      var myDocument=app.activeDocument;
      myDocument.viewPreferences.horizontalMeasurementUnits = MeasurementUnits.POINTS;
      myDocument.viewPreferences.verticalMeasurementUnits = MeasurementUnits.POINTS;
      
      
          var myPages=myDocument.pages;
              for(p=1;p<myPages.length;p++) {
                  var firstGuide = myPages[p].guides.add({
                  orientation:HorizontalOrVertical.HORIZONTAL,
                  location:54
                  });
              }
      }
      
      
      function ChangeLayout() {
           var myDocument = app.activeDocument;
                                    with(myDocument.layoutAdjustmentPreferences.enableLayo utAdjustment = true){
                                              enableLayoutAdjustment = true;
                                              //snapZone =
                                              allowGraphicsToResize  = true;
                                              allowRulerGuidesToMove = true;
                                              ignoreRulerGuideAlignments = false;
                                              ignoreObjectOrLayerLocks = true;
                                              }
                                              with(myDocument.documentPreferences){
                                              pageSize = "A4"
                                              pageOrientation = PageOrientation.portrait;
                                              }
      }
      
      
      function RemoveGuides() {
          var myDocument=app.activeDocument;
              if(myDocument.spreads.everyItem().guides.length > 0){
                  myDocument.spreads.everyItem().guides.everyItem().remove();
                  }//end if
      }
      
      
      function RepositionTextFrames() {
          var myDocument=app.activeDocument;
          myDocument.viewPreferences.horizontalMeasurementUnits = MeasurementUnits.POINTS;
          myDocument.viewPreferences.verticalMeasurementUnits = MeasurementUnits.POINTS;
      
      
          var newposition1 = [216.425, 54] // new position, upper left corner
          var newposition2 = [36, 54] // new position, upper left corner
          var newSBposition1 = [213.425, 54] // new position, upper left corner
      
          var myOldX = 36;
          var myOldXMin = 216;
          var myOldXMax = 217;
          var myOldYMin = 55;
          var myOldYMax = 56;
      
          var mySBOldXMin = 213;
          var mySBOldXMax = 214;
          var mySBOldYMin = 69;
          var mySBOldYMax = 70;
          var mySBOldYMin1 = 55;
          var mySBOldYMax1 = 56;
          var mySBWidthMin = 345;
          var mySBWidthMax = 346;
          var mySB_sidebarWidthMin = 168;
          var mySB_sidebarWidthMax = 169;
      
      
          //UNLOCKING EVERY ITEM IN THE DOCUMENT TO ENABLE MOVE
          app.activeDocument.pageItems.everyItem().locked = false;
      
      
          var myPages=myDocument.pages;
              for(p=1;p<myPages.length;p++) {
                  var allFrames=myPages[p].allPageItems;
                  for (var i=0; i<allFrames.length; i++) {
                      var t=allFrames[i];  
                      var myFrame = t.geometricBounds;
                      var myNewY = Math.round(myFrame[0]);
                      var myNewX = Math.round(myFrame[1]);
                      var myFrameWidth = Math.round(myFrame[3]-myFrame[1]);
                      var myFrameHeight = Math.round(myFrame[2]-myFrame[0]);
      
      
                        if(myNewY >= myOldYMin && myNewY <= myOldYMax && myNewX >= myOldXMin && myNewX <= myOldXMax){
                          t.move(newposition1);
                          break;
                        }
                        else if ((t.constructor.name !== "TextFrame") && myNewY >= myOldYMin && myNewY <= myOldYMax && myNewX >= myOldX){
                           t.move(newposition2);
                          break;
                          }
                        else if ((t.constructor.name == "TextFrame") && (t.textFramePreferences.textColumnCount !== 2) && myNewY >= myOldYMin && myNewY <= myOldYMax && myNewX >= myOldX){
                           t.move(newposition2);
                          break;
                          }
                        else if (myNewY >= myOldYMin && myNewY <= myOldYMax && myNewX >= mySBOldXMin && myNewX <= mySBOldXMax && myFrameWidth >= mySB_sidebarWidthMin && myFrameWidth <= mySB_sidebarWidthMax){
                           t.move(newposition2);
                          // t.geometricBounds = [261.18,36,747,559.275590551];
                          break;
                          }
                        else if ((t.constructor.name == "TextFrame") && (t.textFramePreferences.textColumnCount == 2) && myNewY >= myOldYMin && myNewY <= myOldYMax && myNewX >= mySBOldXMin && myNewX <= mySBOldXMax){
                           t.move(newSBposition1);
                          break;
                          }
                  }
              }
      
      
          //RESET MEASUREMENT UNIT AS PICAS
          myDocument.viewPreferences.horizontalMeasurementUnits = MeasurementUnits.PICAS;
          myDocument.viewPreferences.verticalMeasurementUnits = MeasurementUnits.PICAS;
          }
      
      
      function RepositionCoverPageFrames() {
          var myDocument=app.activeDocument;
          myDocument.viewPreferences.horizontalMeasurementUnits = MeasurementUnits.POINTS;
          myDocument.viewPreferences.verticalMeasurementUnits = MeasurementUnits.POINTS;
      
      
          var CoverBGposition = [18, 18] // new position, upper left corner
          var CoverBriefTextposition = [36, 36] // new position, upper left corner
          var CoverBrochTextposition = [33, 36] // new position, upper left corner
          var CoverBWPTextposition = [40.997, 45] // new position, upper left corner
          var CoverLogoposition = [452.276, 698.89] // new position, upper left corner
          var CoverBroLogoposition = [451.276, 697.89] // new position, upper left corner
          var CoverBWPLogoposition = [442.718, 688.89] // new position, upper left corner
      
      
          var myCBGWidthmin = 558;
          var myCBGWidthmax = 576;
      
          var myBreifImageWidth = 540;
          var myBreifImageHeightmin = 208;
          var myBreifImageHeightmax = 209;
          var myBreifTitleWidthtmin = 345;
          var myBreifTitleWidthmax = 358;
      
          var myBrochImageHeight = 756;
          var myBrochImageHeightmin = 755;
          var myBrochImageHeightmax = 756;
          var myBrochTitleWidthmin = 450;
          var myBrochTitleWidthmax = 451;
      
      
          var myBWPTitleWidthmin = 444;
          var myBWPTitleWidthmax = 445;
      
      
          var myDSImageWidthmin = 523;
          var myDSImageWidthmax = 524;
          var myDSImageHeightmin = 437;
          var myDSImageHeightmax = 438;
          var myDSTitleWidthmin = 410;
          var myDSTitleWidthmax = 411;
      
      
          var mySGImageWidth = 576;
          var mySGImageHeight = 756;
      
      
          var myCTWidthmin = 444;
          var myCTWidthmax = 524;
      
      
          var CoverLogoWidthmin = 106;
          var CoverLogoWidthmax = 109;
      
      
          //UNLOCKING EVERY ITEM IN THE DOCUMENT TO ENABLE MOVE
          app.activeDocument.pageItems.everyItem().locked = false;
      
      
          //ARRANGING FRAMES ON FIRST PAGE
          var myCoverPage=myDocument.pages[0];
          var myCoverPageFrames = myCoverPage.allPageItems;
      
      
                  //CHANGE 10% TINT TO NONE
                  for (var j=0; j<myCoverPageFrames.length; j++) {
                              var f=myCoverPageFrames[j];
                              var myNone = app.activeDocument.swatches.item("None");
      
      
                              //Brochure image frame repositioning
                                if((f instanceof Rectangle) && (f.fillTint = 10)){
                                  f.fillColor==myNone;
                                  f.fillTint = 100;
                                  }
                  }
      
      
                  //FIXING COVER PAGE FRAMES
                  for (var j=0; j<myCoverPageFrames.length; j++) {
                              var f=myCoverPageFrames[j];
                              var myImages = myDocument.pages[0].allGraphics;
                              var myCoverFrame = f.geometricBounds;
                              var myLightGray = app.activeDocument.swatches.item("Light Gray");
                              var myBlue = app.activeDocument.swatches.item("Blue_2925 C_process");
                              var myNone = app.activeDocument.swatches.item("None");
                              var myCoverFrameWidth = Math.round(myCoverFrame[3]-myCoverFrame[1]);
                              var myCoverFrameHeight = Math.round(myCoverFrame[2]-myCoverFrame[0]);
      
      
                              //Brochure image frame repositioning
                                if((f instanceof Rectangle) && (f.fillColor==myNone) && myCoverFrameWidth >= myCBGWidthmin && myCoverFrameWidth <= myCBGWidthmax && myCoverFrameHeight ==myBrochImageHeight){
                                  f.geometricBounds = [18,18,823.89,577.2744];
                                  f.fit(FitOptions.FILL_PROPORTIONALLY);
                                  }
                              //Sales guide image frame repositioning constructor.name == "TextFrame"
                                else if((f.constructor.name == "TextFrame") && (f.fillColor==myLightGray) && myCoverFrameWidth == mySGImageWidth && myCoverFrameHeight ==mySGImageHeight){
                                  f.geometricBounds = [18,18,823.89,577.2744];
                                  //f.fit(FitOptions.FILL_PROPORTIONALLY);
                                  }
                              //Brief image frame repositioning
                                else if((f instanceof Rectangle) && (f.fillColor==myNone) && myCoverFrameWidth == myBreifImageWidth && myCoverFrameHeight >=myBreifImageHeightmin && myCoverFrameHeight <= myBreifImageHeightmax){
                                  f.geometricBounds = [205.74,36,414.72,559.275590551];
                                  //f.fit(FitOptions.FILL_PROPORTIONALLY);
                                  }
                              //BWP image frame repositioning
                                else if((f instanceof Rectangle) && (f.fillColor==myBlue) && myCoverFrameWidth >= myCBGWidthmin && myCoverFrameWidth <= myCBGWidthmax){
                                  f.geometricBounds = [27,27,814.889,568.275];
                                  }
                              //FamilyDatasheet image frame repositioning
                                else if(myCoverFrameHeight >= myDSImageHeightmin && myCoverFrameHeight <= myDSImageHeightmax){
                                  f.geometricBounds = [261.18,36,747,559.275590551];
                                  }
                              //Solution brief title frame repositioning
      //~                           else if (myCoverFrameWidth >= myBreifTitleWidthtmin && myCoverFrameWidth <= myBreifTitleWidthmax){
      //~                              f.move(CoverBriefTextposition);
      //~                             }
                              //Brochure title frame repositioning
                                else if (myCoverFrameWidth >= myBrochTitleWidthmin && myCoverFrameWidth <= myBrochTitleWidthmax){
                                   f.move(CoverBrochTextposition);
                                  }
                              //BWP title frame repositioning
                                else if (myCoverFrameWidth >= myBWPTitleWidthmin && myCoverFrameWidth <= myBWPTitleWidthmax){
                                   f.move(CoverBWPTextposition);
                                  }
                              //Data sheet title frame repositioning
                                else if (myCoverFrameWidth >= myDSTitleWidthmin && myCoverFrameWidth <= myDSTitleWidthmax){
                                   f.move(CoverBriefTextposition);
                                  }
                     }
      
      
              //CHANGE VIEW TO FIT PAGE TO WINDOW
              myWindow = app.documents[0].layoutWindows[0];
              myWindow.zoom(ZoomOptions.FIT_PAGE);
      
      
          //RESET MEASUREMENT UNIT AS PICAS
          myDocument.viewPreferences.horizontalMeasurementUnits = MeasurementUnits.PICAS;
          myDocument.viewPreferences.verticalMeasurementUnits = MeasurementUnits.PICAS;
      }
      
      
      function RepositionLogo() {
          //REPOSITION COVER PAGE LOGO BY ITS XY POSITION ==WORKING==
          var myDocument=app.activeDocument;
          myDocument.viewPreferences.horizontalMeasurementUnits = MeasurementUnits.POINTS;
          myDocument.viewPreferences.verticalMeasurementUnits = MeasurementUnits.POINTS;
      
      
          var BroLogoOld = [451.276, 697.89] // original position, upper left corner
          var BWPLogoOld = [444.981, 682.654] // original position, upper left corner
          var DSLogoOld = [451.276, 36] // original position, upper left corner
          var BriefLogoOld = [470.563, 36] // original position, upper left corner
      
      
          var BroLogoNew = [451.276, 697.89] // original position, upper left corner
          var BWPLogoNew = [442.718, 688.89] // original position, upper left corner
          var DSLogoNew = [451.276, 36] // original position, upper left corner
          var BriefLogoNew = [470.563, 36] // original position, upper left corner
      
      
          //UNLOCKING EVERY ITEM IN THE DOCUMENT TO ENABLE MOVE
          myDocument.pageItems.everyItem().locked = false;
      
      
          //ARRANGING FRAMES ON FIRST PAGE
          var myCoverPage=myDocument.pages[0];
          var myLastPage = myDocument.pages[-1]
          var myCoverPageFrames = myCoverPage.allPageItems;
      
      
          var myObjects = myCoverPage.pageItems.everyItem().getElements();
          for (var i=0; i<myObjects.length; i++){
              if (Math.round(myObjects[i].geometricBounds[1])==BroLogoOld[0]&&Math.rou nd(myObjects[i].geometricBounds[0])==BroLogoOld[1]){
                  myObjects[i].move(BroLogoNew);
              }
              else if (Math.round(myObjects[i].geometricBounds[1])==BWPLogoOld[0]&&Math.rou nd(myObjects[i].geometricBounds[0])==BWPLogoOld[1]){
                  myObjects[i].move(BWPLogoNew);
              }
              else if (Math.round(myObjects[i].geometricBounds[1])==DSLogoOld[0]&&Math.roun d(myObjects[i].geometricBounds[0])==DSLogoOld[1]){
                  myObjects[i].move(DSLogoNew);
              }
              else if (Math.round(myObjects[i].geometricBounds[1])==BriefLogoOld[0]&&Math.r ound(myObjects[i].geometricBounds[0])==BriefLogoOld[1]){
                  myObjects[i].move(BriefLogoNew);
              }
      
      
          }
      }
      
      
      function FitTableFrameWidth() {
           var myDocument = app.activeDocument;
          for (s=0; s<myDocument.stories.length; s++) {
                  for (t=0; t<myDocument.stories[s].tables.length; t++) {
                      var myTable = myDocument.stories.item(s).tables.item(t);
                      var myTableParent = myTable.parent;
                      var parentWidth = myTableParent.geometricBounds[3] - myTable.parent.geometricBounds[1];
                      var factor = parentWidth/myTable.width;
                      for (col=0; col<myTable.columns.length; col++) {
                          myTable.columns[col].width *= factor;
                          }
                  }
          }
      }
      
      
      function UpdateSoMEURL() {
          var myDestinationURL;
          var myDocument = app.activeDocument;
          var myLastPage = myDocument.pages[-1]
          var findWhat = "ENW";
          var changeTo = "ENN";
      
      
          if(myDocument.hyperlinkURLDestinations.length > 0){
              for(var myCounter = myDocument.hyperlinkURLDestinations.length -1; myCounter >=0; myCounter--){
                myDestinationURL = myDocument.hyperlinkURLDestinations.item(myCounter).destinationURL;
                if(myDestinationURL.search(findWhat) != -1){ //  && myDestinationURL.source instanceof HyperlinkPageItemSource
                 myDocument.hyperlinkURLDestinations.item(myCounter).destinationURL = myDestinationURL.replace(findWhat, changeTo);
                }
              }
          }
      }
      
      
      function UpdatePubNumber() {
          app.findGrepPreferences = NothingEnum.nothing;
          app.changeGrepPreferences = NothingEnum.nothing;
      
      
              // grep find/change
          app.findGrepPreferences = app.changeGrepPreferences = null;     
          app.findGrepPreferences.findWhat = "(\\d+\\u+\\d+-\\d+\\u{2})(\\u+)";
          app.findGrepPreferences.appliedFont = "Simplified"
          app.findGrepPreferences.pointSize = 7;
          app.findGrepPreferences.fontStyle = "Light";
          //app.findGrepPreferences.appliedParagraphStyle = app.activeDocument.paragraphStyleGroups.item("Back page"). paragraphStyles.item("Legal_7/9");
          app.changeGrepPreferences.changeTo = "$1N";
          app.changeGrepPreferences.appliedFont = "Simplified"
          app.changeGrepPreferences.pointSize = 7;
          app.changeGrepPreferences.fontStyle = "Light";
          //app.changeGrepPreferences.appliedParagraphStyle = app.activeDocument.paragraphStyleGroups.item("Back page"). paragraphStyles.item("Legal_7/9");
          app.activeDocument.changeGrep();
      }
      
      
      function UpdateMetadata() {
          var curKeywords = app.activeDocument.metadataPreferences.keywords;
          /*alert(curKeywords);*/
      
      
          var replacedKeywords = Array();
      
      
          for(var i = 0; i < curKeywords.length; i++){
              if(curKeywords[i] .indexOf("ENW") > 0)
                  curKeywords[i]  = curKeywords[i] .replace("ENW","ENN");
              replacedKeywords.push(curKeywords[i]);
          }
      
      
          /*alert(replacedKeywords);*/
          app.activeDocument.metadataPreferences.keywords = replacedKeywords;
      }
      
      
      function SaveACopy() {
          // grep find/change
          app.findGrepPreferences = app.changeGrepPreferences = null;     
          app.findGrepPreferences.findWhat = "(\\d+\\u+\\d+-\\d+\\u{2})(\\u+)";
          app.findGrepPreferences.appliedFont = "Simplified"
          app.findGrepPreferences.pointSize = 7;
          app.findGrepPreferences.fontStyle = "Light";
          //app.findGrepPreferences.appliedParagraphStyle = app.activeDocument.paragraphStyleGroups.item("Back page"). paragraphStyles.item("Legal_7/9");
      
      
          var myFindpubnumber = app.activeDocument.findGrep();
          var mySuffix = ".indd";
          var myPubnumber = myFindpubnumber[0].contents;
          var myPubnumber=myPubnumber.replace("ENW","ENN");
          var myDocument = app.activeDocument;
      
      
          var myFile = myDocument.fullName;
          var docPath = app.activeDocument.filePath;
          var ENNFolder = new Folder(docPath + "/" + myPubnumber);
          ENNFolder.exists||ENNFolder.create();
      
      
          var myNewFile = new File(ENNFolder +"/" + myPubnumber + ".indd");
          myFile.copy(myNewFile);
          myDocument.close (SaveOptions.NO)
          var ENNFile = ENNFolder.getFiles("*.indd");
      //    app.scriptPreferences.userInteractionLevel = UserInteractionLevels.NEVER_INTERACT;
          app.open(File(ENNFile), true);
      
      }
      
      
      function GetFileNameOnly(myFileName) {
           var myString = "";
           var myResult = myFileName.lastIndexOf(".");
           if (myResult == -1) {
                myString = myFileName;
           }
           else {
                myString = myFileName.substr(0, myResult);
           }
           return myString;
      }
      
      
        • 1. Re: Need critique for my script
          Vamitul Level 4

          Hello!

           

          First of all, CONGRATULATIONS!!

           

          Your coding style is way way better than mine, the functions and variables clearly named (mine are usualy a mess like myT, myS, pag, etc), the code is well commented.. like i said.. nice.

           

          For now, except for adding error handling, (for that, please see: http://www.javascriptkit.com/javatutors/trycatch.shtml), there is not much that needs to be done.

          One thing, instead of just calling main(), i would use doScript, so you can take advantage of a single undo point:

          instead of the first line, just use:

          app.doScript("main()",undefined,undefined,"Page Resizer");

           

           

          for your next scripts i suggest the following:

          1) use ScriptUI instead of indesign's dialogs. It's not much harder, and the extra power it's well worth the effort. See Peter's amazing guide: http://www.kahrel.plus.com/indesign/scriptui.html

          2) use a object oriented approach, especialy if the script is as large as this. Procedural programming is ok for a small, simple script, but as the size and complexity goes up you will find it's more easier to mainain and debug OOP code. However, the jump from procedural to object oriented is difficult if you are note used to OOP.

          1 person found this helpful
          • 2. Re: Need critique for my script
            Muthuraj Durairaj Level 1

            Hi Vamitul,

             

            Thanks a ton. You have made me feel proud. I will try to add your suggestions and try to make it better.

             

            Regards,

            Muthuraj. D

            • 3. Re: Need critique for my script
              jonht

              Hi Muthuraj,

               

              If you find yourself repeating code, you can reduce it by creating functions and pass in variables for the parts that are different.

              For example, in your code where you do several find/change operations using grep, you can do something like this:

               

              function findChangeUsingGrep (lookFor, changeTo, appliedFont, fontSize, fontStyle) {

                app.findGrepPreferences = NothingEnum.nothing;

                app.changeGrepPreferences = NothingEnum.nothing;

                app.findGrepPreferences.findWhat = lookFor;

                app.findGrepPreferences.appliedFont = changeTo;

                app.findGrepPreferences.pointSize = fontSize;

                app.findGrepPreferences.fontStyle = fontStyle;

                app.activeDocument.changeGrep();

              }

               

               

              Then call it with something like this:

               

              var lookFor = ",\\s+[\\l\\u]+?\\s?\\d{4},?\\s*[\\l\\u]*\\.*\\s*\\d*"

              if (RevNumber == "") {

                findChangeUsingGrep(lookFor, RevToReplace1, "Simplified", 7, "Light");

              }

              if (RevNumber !== "") {

                findChangeUsingGrep(lookFor, RevToReplace2, "Simplified", 7, "Light");

              }

               

              But like Vamitul said, well done!

               

              John