0 Replies Latest reply on Feb 7, 2014 6:49 AM by kajzica

    hel with modifying cs5/6 script...create anchored frames from text

    kajzica Level 1

      hello

      I have one great time saver script for cs5 for create anchored frames from text tagged with/or charachter style/paragraph style. This work in cs6 but have some "bugs" for me. Script need to be compatible with InDesign CS6.

       

      1. script in original (look bellow) create text frame which is fitted to lenght of the text. I make change and change 466 line:

      AnchoredTextFrame.fit(FitOptions.FRAME_TO_CONTENT);


      now frame is wide as I write in check box, good. But frame not resize to lenght of the text so I add after above lines 466-470:

          var FO = FitOptions.FRAME_TO_CONTENT,

          tfs = ([]).concat.apply([], app.activeDocument.stories.everyItem().textContainers),

          t, i = tfs.length;

      while( i-- ) (t=tfs[i]).overflows && ( t.locked || t.fit(FO) );


      now all is ok but is here better way to make this to work? Simply, i want to spec text frame width in dialog box, frame will resize only verticaly in direction to amount text in frame. I dont want any overset text.

       

      2. One "bug". For some reason script alter paragraph style of other text which is not subject to be cutted in anchored frame.

      How to resolve this?

       

       

      _________________________

       

      #targetengine "session"

       

       

      /*

                Automating anchored object creation

                Version: 2

       

          Script by Thomas Silkjær

         

                http://indesigning.net/

      Модификация Б. Кащеев, www.adobeindesign.ru

      Скрипт предназначен для создания привязанных фреймов из текста, отформатированного

      каким-либо абзацным или символьным стилем. Эти стили задаются пользователем в диалоговом

      окне скрита. Там же необходимо задать объектный стиль для привязанного фрейма, в котором

      пользователь должен заранее задать оформление и параметры привязки. Далее необходимо

      указать ширину привязанного фрейма, а его высота будет рассчитана автоматически исходя из

      объема текста. При вводе дробных значений ширины привязанного фрейма в качестве

      разделителя целой и дробной части следует использовать не запятую, а точку, следуя западным

      стандартам разработчиков программы  Adobe InDesign. Первоначально идея и скрипт по созданию

      привязанных фреймов принадлежит Thomas Silkjær для версии ID CS4. C появлением версий CS5

      и CS5.5 скрипт перестал в них выполняться, да и в версии CS4 не всегда корректно работал.

      Анализируя недочеты скрипта в данной его версии были исправлены ошибки и внесены

      функциональные дополнения исходя из понимания задачи автором модификации. Добавлена

      возможность выбора стилей, если они они находятся в группах (папках), возможность выбора

      единиц измерения из выпадающего списка, изменены GREP-выражения для поиска текста,

      область действия скрипта ограничена материалом (Story), а не документом.

      */

      var myMeasureUnits = ["Milimeters","Centimeters","Points","Inches", "Picas", "Ciceros"];

      var selectUnits;

      var pStyleIndex = null;

      var cStyleIndex = null;

      var oStyleIndex = null;

      var myH, myW;

      function main()

      {

          app.scriptPreferences.userInteractionLevel = UserInteractionLevels.interactWithAll;

                if (app.documents.length == 0)

                {

                          alert ("Document is not open. Open document first");

                          return;

                }

          var myParaStyleList = myGetParagraphStyleNames();

          var myCharStyleList = myGetCharacterStyleNames();

          var myObjStyleList = myGetObjStyleNames();

       

       

          if(app.selection.length && app.selection[0].hasOwnProperty("baseline"))

          {

              var myStory = app.selection[0].parentStory;

              var myWin = myDialog(myParaStyleList, myCharStyleList, myObjStyleList);

             

              if ( myWin.show()  == 1 )

              {

                  var myDocument = app.activeDocument

                  with (myDocument.viewPreferences){

                      // Сохраняем старые единицы измерения в переменных myOldXUnits, myOldYUnits

                      var myOldXUnits = horizontalMeasurementUnits;

                      var myOldYUnits = verticalMeasurementUnits;

                      // Устанавливаем новые единицы измерения

                      switch(selectUnits)

                      {

                          case 0:                   

                              horizontalMeasurementUnits = MeasurementUnits.millimeters;

                              verticalMeasurementUnits = MeasurementUnits.millimeters;

                              break;

                          case 1:

                              horizontalMeasurementUnits = MeasurementUnits.centimeters;

                              verticalMeasurementUnits = MeasurementUnits.centimeters;

                              break;

                          case 2:

                              horizontalMeasurementUnits = MeasurementUnits.points;

                              verticalMeasurementUnits = MeasurementUnits.points;

                              break;                  

                          case 3:

                              horizontalMeasurementUnits = MeasurementUnits.inches;

                              verticalMeasurementUnits = MeasurementUnits.inches;

                              break;

                          case 4:

                              horizontalMeasurementUnits = MeasurementUnits.picas;

                              verticalMeasurementUnits = MeasurementUnits.picas;

                              break;

                          case 5:

                              horizontalMeasurementUnits = MeasurementUnits.ciceros;

                              verticalMeasurementUnits = MeasurementUnits.ciceros;

                              break;

                          default: break;

                      } // switch

                  }

                 

                  if(cStyleIndex == null)

                  {/*поиск по стилю абзаца*/

                     

                      var pStyle = getParagraphStyleByName(myParaStyleList[pStyleIndex]);

                      resetGREPfindChange();

                      app.findGrepPreferences.appliedParagraphStyle = pStyle;

                      app.findGrepPreferences.findWhat = NothingEnum.nothing;

                     

                  }

                  else //

                  {

                      // поиск по стилю символов

                      var cStyle = getCharacterStyleByName(myCharStyleList[cStyleIndex]);

                      resetGREPfindChange();

                      app.findGrepPreferences.appliedCharacterStyle = cStyle;

                      //app.findGrepPreferences.findWhat = ".+";

                      app.findGrepPreferences.findWhat = NothingEnum.nothing;

                  }

                  var foundItems = myStory.findGrep();

                  if(!foundItems.length) {

                      alert("Found the text to be placed in a linked frames"); exit();

                  }

                  //alert(foundItems.length);

                  //alert (foundItems[0].contents)

                  //alert (foundItems[1].contents)

                  var oStyle = getObjectStyleByName(myObjStyleList[oStyleIndex]);

                  for(var i = foundItems.length-1; i >=0; i--)

                  {

                      //alert (foundItems[i].contents)

                      createAnchoredFrame(foundItems[i], oStyle);

                  }

                  with (myDocument.viewPreferences){

                      try{

                          horizontalMeasurementUnits = myOldXUnits;

                          verticalMeasurementUnits = myOldYUnits;

                      }

                      catch(myError){

                          alert("Unable to return to the original unit");

                      }

                  }

             

              } //if ( myWin.show()

          } //if(app.selection.length && app.selection[0].hasOwnProperty("baseline"))

          else

          {

              alert("Place the cursor in the text and run the script again")

          }

      } // main

      function myGetParagraphStyleNames()

      // Получаем список стилей абзацев

      {

                var curGroup;

                var curGroupName;

                var curNameInGroup;

                var myParagraphStyleNames = app.activeDocument.paragraphStyles.everyItem().name;

                myParagraphStyleNames.shift(); // удаление стиля No Paragraph Style

                var paraGroups = app.activeDocument.paragraphStyleGroups;

                var paraGroupsLen = paraGroups.length;

                for(var i = 0; i < paraGroupsLen; i++) {

                          curGroup = paraGroups[i];

                          curGroupName = paraGroups[i].name;

                          curGroupStyleNames = curGroup.paragraphStyles.everyItem().name

                          for (j=0; j< curGroupStyleNames.length; j++)

                          {

                                    curNameInGroup = curGroupName +":"+ curGroupStyleNames[j];

                                    myParagraphStyleNames.push(curNameInGroup);

                          }

                }

                return myParagraphStyleNames;

      }

      function myGetCharacterStyleNames()

      // Получаем список символьных стилей

      {

                var curGroup;

                var curGroupName;

                var curNameInGroup;

                var myCharacterStyleNames = app.activeDocument.characterStyles.everyItem().name;

                myCharacterStyleNames.shift(); // удаление стиля None

                var charGroups = app.activeDocument.characterStyleGroups;

                var charStyleGroupLen = charGroups.length;

                for(var i=0; i < charStyleGroupLen; i++)

                {

                          curGroup = charGroups[i];

                          curGroupName = charGroups[i].name;

                          curGroupStyleNames = curGroup.characterStyles.everyItem().name;

                          for (j=0; j< curGroupStyleNames.length; j++)

                          {

                                    curNameInGroup = curGroupName +":"+ curGroupStyleNames[j];

                                    myCharacterStyleNames.push(curNameInGroup);

                          }

                } //for

                return myCharacterStyleNames;

      } // fnc

       

       

      function myGetObjStyleNames()

      {

          var curGroup;

                var curGroupName;

                var curNameInGroup;

                var myObjStyleNames = app.activeDocument.objectStyles.everyItem().name;

          myObjStyleNames.shift();

          var objGroups = app.activeDocument.objectStyleGroups;

          var objStyleGroupLen = objGroups.length;

          for(var i=0; i < objStyleGroupLen; i++)

                {

                          curGroup = objGroups[i];

                          curGroupName = objGroups[i].name;

                          curGroupStyleNames = curGroup.objectStyles.everyItem().name;

                          for (var j=0; j< curGroupStyleNames.length; j++)

                          {

                                    curNameInGroup = curGroupName +":"+ curGroupStyleNames[j];

                                    myObjStyleNames.push(curNameInGroup);

                          }

                } //for

         

          return myObjStyleNames;

      } // fnc

       

       

      function myDialog(myParaStyleList, myCharStyleList, myObjStyleList)

      {

       

       

          var myDialog = new Window('dialog', 'Create anchored text frames');

          this.windowRef = myDialog;

                myDialog.orientation = "column";

          myDialog.alignChildren = ['fill', 'fill'];

          // добавляем панель 1 с элементами управления

          myDialog.Pnl1 = myDialog.add("panel", undefined, "Move the text in linked frames");

                myDialog.Pnl1.orientation = "column";

          myDialog.Pnl1.alignChildren = "left";

         

          myDialog.Pnl1.pstyle = myDialog.Pnl1.add('checkbox', undefined, "Text with the paragraph style");

          myDialog.Pnl1.pstyle.value = false;

          myDialog.Pnl1.dropdownParaStyle = myDialog.Pnl1.add("dropdownlist", undefined, myParaStyleList);

          myDialog.Pnl1.dropdownParaStyle.title = "Select the paragraph style ";

          myDialog.Pnl1.dropdownParaStyle.minimumSize = [250,20];

          myDialog.Pnl1.dropdownParaStyle.enabled = false;

          myDialog.Pnl1.dropdownParaStyle.selection = 0;

         

          if(myCharStyleList.length)

          {

              myDialog.Pnl1.сstyle = myDialog.Pnl1.add('checkbox', undefined, "Text with character style");

              myDialog.Pnl1.сstyle.value = false;

              myDialog.Pnl1.dropdownCharStyle = myDialog.Pnl1.add("dropdownlist", undefined, myCharStyleList );

              myDialog.Pnl1.dropdownCharStyle.title = "Select the character style ";

              myDialog.Pnl1.dropdownCharStyle.minimumSize = [250,20];

              myDialog.Pnl1.dropdownCharStyle.enabled = false;

              myDialog.Pnl1.dropdownCharStyle.selection = 0;

             

              myDialog.Pnl1.pstyle.onClick = function()

              {

                  if(this.value) {

                      myDialog.Pnl1.dropdownParaStyle.enabled = true;

                      myDialog.Pnl1.dropdownCharStyle.enabled = false;

                      myDialog.Pnl1.сstyle.value = false;

                      }

                  else

                  {

                      myDialog.Pnl1.dropdownParaStyle.enabled = false;

                      myDialog.Pnl1.dropdownCharStyle.enabled = true ;

                      myDialog.Pnl1.сstyle.value = true;

                  }

              }// fnc

              myDialog.Pnl1.сstyle.onClick = function()

              {

                  if(this.value)

                  {

                      myDialog.Pnl1.dropdownCharStyle.enabled = true;

                      myDialog.Pnl1.dropdownParaStyle.enabled = false;

                      myDialog.Pnl1.pstyle.value = false;

                  }

                  else

                  {

                      myDialog.Pnl1.dropdownCharStyle.enabled = false;

                      myDialog.Pnl1.dropdownParaStyle.enabled = true ;

                      myDialog.Pnl1.pstyle.value = true;

                  }

                 

              }// fnc

          }//  if(myCharStyleList.length)

          else

          {

              myDialog.Pnl1.pstyle.onClick = function()

              {

                  if(this.value)

                  {

                      myDialog.Pnl1.dropdownParaStyle.enabled = true;

                  }

                  else

                  {

                      myDialog.Pnl1.dropdownParaStyle.enabled = false;

                  }

              }

          }

      //  Вторая панель

          myDialog.Pnl2 = myDialog.add("panel", undefined, "Parameters of the text frame");

                myDialog.Pnl2.orientation = "column";

          myDialog.Pnl2.alignChildren = "left"; 

         

          myDialog.Pnl2.dropdownObjStyle = myDialog.Pnl2.add("dropdownlist", undefined, myObjStyleList );

          myDialog.Pnl2.dropdownObjStyle.title = "Select an object style ";

          myDialog.Pnl2.dropdownObjStyle.minimumSize = [250,20];

          myDialog.Pnl2.dropdownObjStyle.enabled = true;

          myDialog.Pnl2.dropdownObjStyle.selection = 0;

         

          myDialog.Pnl2.Group1 = myDialog.Pnl2.add( "group" );

          myDialog.Pnl2.Group1.stxt1 = myDialog.Pnl2.Group1.add("statictext", undefined, "The width of the text frame");

          myDialog.Pnl2.Group1.etxt = myDialog.Pnl2.Group1.add("edittext", undefined, "40");

          myDialog.Pnl2.Group1.etxt.characters = 10;

          myDialog.Pnl2.Group1.dropdownMeasurementUnits = myDialog.Pnl2.Group1.add("dropdownlist", undefined, myMeasureUnits );

          myDialog.Pnl2.Group1.dropdownMeasurementUnits.maximumSize = [80,20];

          myDialog.Pnl2.Group1.dropdownMeasurementUnits.selection = 0;

          //myDialog.Pnl2.Group1.stxt2 = myDialog.Pnl2.Group1.add("statictext", undefined, "mm ");

         

          /*myDialog.Pnl2.Group2 = myDialog.Pnl2.add( "group" );

          myDialog.Pnl2.Group2.stxt1 = myDialog.Pnl2.Group2.add("statictext", undefined, "Высота привязанного фрейма  ");

          myDialog.Pnl2.Group2.etxt = myDialog.Pnl2.Group2.add("edittext", undefined, "30");

          myDialog.Pnl2.Group2.etxt.characters = 10;

          //myDialog.Pnl2.Group2.stxt2 = myDialog.Pnl2.Group2.add("statictext", undefined, "mm ");*/

          myDialog.Pnl2.stxt1 = myDialog.Pnl2.add("statictext", undefined, "Attention! When you enter fractional values as");

          myDialog.Pnl2.stxt2 = myDialog.Pnl2.add("statictext", undefined, "the decimal part, should be used");

          myDialog.Pnl2.stxt3 = myDialog.Pnl2.add("statictext", undefined, "point, not comma.");

          myDialog.Pnl2.stxt1.graphics.foregroundColor = myDialog.Pnl2.stxt1.graphics.newPen (myDialog.Pnl2.stxt1.graphics.PenType.SOLID_COLOR, [1, 0, 0, 1], 1);

          myDialog.Pnl2.stxt2.graphics.foregroundColor = myDialog.Pnl2.stxt2.graphics.newPen (myDialog.Pnl2.stxt2.graphics.PenType.SOLID_COLOR, [1, 0, 0, 1], 1);

          myDialog.Pnl2.stxt3.graphics.foregroundColor = myDialog.Pnl2.stxt3.graphics.newPen (myDialog.Pnl2.stxt3.graphics.PenType.SOLID_COLOR, [1, 0, 0, 1], 1);

       

       

         

          // --------- кнопки --------------

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

          myGroup.orientation = 'row';

          myGroup.alignChildren = ['fill', 'fill']; 

          myGroup.okButton = myGroup.add( "button", undefined, "OK" );

          myGroup.okButton.onClick = function()

          {

              if(myCharStyleList.length) // есть символьные стили в документе

              {

                  if(!myDialog.Pnl1.pstyle.value && !myDialog.Pnl1.сstyle.value)

                  {

                      alert("You must select a paragraph style or character style");

                      return ;

                  }

                  if(myDialog.Pnl1.pstyle.value) { pStyleIndex= myDialog.Pnl1.dropdownParaStyle.selection.index; cStyleIndex = null;}

                  else {cStyleIndex = myDialog.Pnl1.dropdownCharStyle.selection.index; pStyleIndex=null; }

              }

              else // нет символьных стилей

              {

                  if(!myDialog.Pnl1.pstyle.value)

                  {

                      alert("You must select a paragraph style");

                      return;

                  }

                  pStyleIndex = myDialog.Pnl1.dropdownParaStyle.selection.index;

                  cStyleIndex = null;

              } //  else // нет символьных стилей

             oStyleIndex = myDialog.Pnl2.dropdownObjStyle.selection.index;

             if(myDialog.Pnl2.Group1.etxt.text =="")

             {

                 alert("Enter the width of the text frame");

                 return;

             }

              else

              {

                  myW = myDialog.Pnl2.Group1.etxt.text;

                  myH = myW;

              }

              /*if(myDialog.Pnl2.Group2.etxt.text == "")

              {

                  alert("Введите высоту привязанного фрейма");

                  return;

              }

              else

              {

                  myH = myDialog.Pnl2.Group2.etxt.text;

             }*/

             selectUnits = myDialog.Pnl2.Group1.dropdownMeasurementUnits.selection.index;

              myDialog= this.window.close( 1 );

          }

          myGroup.cancelButton = myGroup.add( "button", undefined, "Cancel" );

          myGroup.cancelButton.onClick = function() { myDialog = this.window.close( 0 ); }

         

          myDialog.Pnl3 = myDialog.add("panel", undefined, "");

          myDialog.Pnl2.alignChildren = "left";

          myDialog.Pnl3.stxt = myDialog.Pnl3.add("statictext", undefined, "(с) Thomas Silkjær        (с) Борис Кащеев, www.adobeindesign.ru ");

         

         

          return myDialog;   

      } // fnc

       

       

      function getParagraphStyleByName(myStyleName)

      {

                var DocParaStyles = app.activeDocument.paragraphStyles;

                var DocParaGroups = app.activeDocument.paragraphStyleGroups;

                myStyleName = ""+myStyleName;

                var pos = myStyleName.indexOf(":")

                if(pos == -1)

                {

                // стиль не в группе

                var myStyle = DocParaStyles.item(myStyleName);

                          return myStyle;

                } //if

                else

                {

                          var myGroupAndStyleNames = myStyleName.split(":")

                          var myGroupName = myGroupAndStyleNames[0];

                          var myStyleName = myGroupAndStyleNames[1];

                          var myGroup =DocParaGroups.item(myGroupName);

                          return myGroup.paragraphStyles.item(myStyleName);

       

       

                }

      } // fnc

       

       

      function getCharacterStyleByName(myStyleName)

      {

                var DocChStyles = app.activeDocument.characterStyles;

                var DocCharGroups = app.activeDocument.characterStyleGroups;

                // Есть ли в имени полученного символьного стиля двоеточие? (двоеточие разделяет название группы стилей и название стиля)

                myStyleName = String (myStyleName);

                var pos = myStyleName.indexOf(":");

                if(pos == -1)

                {

                // стиль не в группе

                          return DocChStyles.item(myStyleName)

                } //if...

                else

                {// Стиль в какой-то группе

                          var myGroupAndStyleNames = myStyleName.split(":")

                          var myGroupName = myGroupAndStyleNames[0];

                          var myStyleName = myGroupAndStyleNames[1];

                          var myGroup = DocCharGroups.item(myGroupName);

                          return myGroup.characterStyles.itemByName(myStyleName);

                } // else

      } // fnc()+

       

       

      function getObjectStyleByName(myStyleName)

      {

          var DocObjStyles = app.activeDocument.objectStyles;

          var DocCObjGroups = app.activeDocument.objectStyleGroups;

          myStyleName = String (myStyleName);

          var pos = myStyleName.indexOf(":");

          if(pos == -1)

                {

                // стиль не в группе

                          return DocObjStyles.item(myStyleName);

                } //if...

          var myGroupAndStyleNames = myStyleName.split(":");

          var myGroupName = myGroupAndStyleNames[0];

          var myStyleName = myGroupAndStyleNames[1];

          var myGroup = DocObjGroups.item(myGroupName);

                          return myGroup.objectStyles.itemByName(myStyleName);

      } //fnc

       

       

      function resetGREPfindChange()

      {

          app.changeGrepPreferences = NothingEnum.nothing;

          app.findGrepPreferences = NothingEnum.nothing;

          app.findChangeGrepOptions.includeFootnotes = false;

          app.findChangeGrepOptions.includeHiddenLayers = false;

          app.findChangeGrepOptions.includeLockedLayersForFind = false;

          app.findChangeGrepOptions.includeLockedStoriesForFind = false;

          app.findChangeGrepOptions.includeMasterPages = false;

       

       

      }

       

       

      function createAnchoredFrame(myText, myObjStyle)

      {

       

       

          var myGeometricBounds = [];

          var myInsertionPoint = myText.insertionPoints[0];

          myInsertionPoint.select;

          var AnchoredTextFrame = myInsertionPoint.textFrames.add();

          myGeometricBounds = AnchoredTextFrame.geometricBounds;

          //alert(parseFloat(myH) + " " + parseFloat(myW))

          myGeometricBounds[2] = myGeometricBounds[0] + parseFloat(myH);

          myGeometricBounds[3] = myGeometricBounds[1] + parseFloat(myW);

          AnchoredTextFrame.geometricBounds = myGeometricBounds;

          AnchoredTextFrame.anchoredObjectSettings.anchoredPosition = AnchorPosition.anchored;

       

       

          myText.move(LocationOptions.before, AnchoredTextFrame.texts[0]);

          AnchoredTextFrame.appliedObjectStyle = myObjStyle;

          AnchoredTextFrame.fit(FitOptions.CONTENT_TO_FRAME);

          var FO = FitOptions.FRAME_TO_CONTENT,

          tfs = ([]).concat.apply([], app.activeDocument.stories.everyItem().textContainers),

          t, i = tfs.length;

      while( i-- ) (t=tfs[i]).overflows && ( t.locked || t.fit(FO) );

      } //fnc

       

       

      main();