Quantcast
Channel: Adobe Community : All Content - InDesign Scripting
Viewing all 8771 articles
Browse latest View live

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

$
0
0

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();


socket connection not returning/reading response

$
0
0

Env: Indesign CS 5.5 and Indesign CS 6; Mac OS 10.8.4

 

I have a strange issue with reading the response from the server that just started after a client upgraded from a previous OS to Mac OS 10.8.4. However, this particular script has worked on other 10.8.4 machines so I believe it is another issue.

 

Here is the code in question:

var rtnData = "";
conn = new Socket; if (File.fs == "Windows") var isMac=0;          else var isMac=1; 
var myRequest = "GET "+vSubDir+"/get_Pathnames.asp?ismac="+isMac+" HTTP/1.0\n\n"if (debug) $.writeln(myRequest);    if (conn.open (vHost)) {                        conn.write (myRequest);       // send a HTTP request        rtnData = conn.read(999999);  // and read the server’s reply                conn.close();}

vHost=I.P address of server

vSubDir=subdirectory to the file

 

 

So some of the tests I ran already:

conn.open(vHost) returns true.

When I go to vHost+vSubDir+"/get_Pathnames.asp?ismac="+isMac+" directly in the browser I receive the response I expect.

 

 

Essentially Indesign is connecting to the server but not reading the response that I know exists. Has anyone else experienced this issue or something similiar? I can't recreate it anywhere but the client's machine.

Move URLs in Text to End of Story Or Link Text. Also: Tables

$
0
0

Hello everyone

 

I'm currently working on a script that translates Textile Markup into formatted InDesign-Text. This worked fine for the most part, seeing as it's not really hard to do by FindChangeByList. Some things are a bit trickier than other things, though. Namely URLs in the text. In Textile, all URLs are like so. Let's say I'd like to link to Google. So I'd type this: "Google":http://www.google.com This would produce Google. I can isolate the word and delete the URL by [\\\"](.+?)[\\\"]:\\?\\S+ and then replacing by $1. So far so good.

 

However!

 

It would be awesome, if the URLs were still in the text. So I'd either like to have it like so: Google or that the word Google (or any $1, really) stands in the text and then the link is added to the end of the text as a kind of "Sources"-paragraph-thing. How can this be done? Can I do it by FindChangeByList? Because that would be cool, seeing as then I'd only need to run one script.

 

And here's a general question: How can I translate Textile-Tables into Formatted InDesign-Tables?

 

For reference, this would be a table with one header row.

 

|_. name |_. age |_. sex |

| joan | 24 | f |

| archie | 29 | m |

| bella | 45 | f |

 

Can this be done?

 

Thank you very much for your help!

Trapping cursor coordinates in Javascript

$
0
0

Hello Everyone:

 

   I am attempting to trap cursor coordinates but I do not know how to make that happen.  Here is the short algorithm I hope to implement:

 

click object to select.

click new location for object to move to

move object to new location.

 

I think I know how to do the first, but I have no idea how to make Javascript report the coordinates of the mouse cursor when I click on the new location.

 

Please share with me any thoughts/documentation/snippets that might help.  I will greatly appreciate it.

 

TIA.

 

John

Calculation

$
0
0

var a= 0001;

alert(a+1);

 

 

The Result is 2, but I want to make it to 002, How?

Hyperlink to a >title< within an ID doc?

$
0
0

Hi everyone,

 

I am using CS5 with Windows 7.

 

I created a Table of Contents in an ID doc, which shows bookmarks for each title.  All fine and good.  From this, I made a .pdf and all links work.  However,....

 

When I click on one of the T of C items, the hyperlink goes to the entire page, not where the the specific title is.  This is okay on an iPad, thanks to its large screen, but when I tested the links on an iPhone, the hyperlink goes to the top of the page, rather than to the title in the middle of the page.  The reader can easily get confused.  The smaller screen needs to take the reader to the title.

 

What I've done in the past, with MS FrontPage, is to select the title to be the bookmark, and then I created other text to be the button to click on that goes to the bookmark.

 

Is there a similar way to do this in ID?

 

Thank you for your help.

doc.AllGraphics crash in C#.

$
0
0

InDesign.Document doc = (InDesign.Document)app.Open(PathToInDesignFile, true); // works fine

InDesign.Graphics allGraphics = (InDesign.Graphics)doc.AllGraphics; // crashes with an exception

 

That's the exception:

Unable to cast COM object of type 'System.__ComObject' to interface type 'InDesign.Graphics'.

This operation failed because the QueryInterface call on the COM component for the interface with IID '{C85A4AB§-9492-...}' failed due to the following error:

No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).

 

How to solve this problem?

Script to Relink images after adding something to the name

$
0
0

Hi Guys

 

I have a 88 book project and all of them have the same names in all images - i have a "Image01-p01" to  "Image250-p275" (for example). I need to create (through a File Renamer) some diference in it by adding for example "CarpTCMmM5" to the name and having in the end "CarpTCMmM5Image01-p01" and keeping all other words and numering like it was.

 

So is there any miracle way to be able to relink all links??? (like with Relink to Folder or Reling to file extension)

 

thanks

 

Rui


[CS6][JS][Win]Append page number of citation

$
0
0

Hi guys,

 

I hope you can help me with this one, I have a Bibliography page structured like this:

 

DARWIN Charles Erasmus 7529 (1759–1799) Lorem ipsum dolor sit amet,

   consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore

   et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud

   exercitation ullamco laboris nisi ut aliquip ex ea commodo.

 

Then I need to search for the body of the book for pages where Darwin were cited then append it to the end of the paragraph which will look like this:

 

DARWIN Charles Erasmus 7529 (1759–1799) Lorem ipsum dolor sit amet,

   consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore

   et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud

   exercitation ullamco laboris nisi ut aliquip ex ea commodo. [23 35 102 204]

 

Please take note that the citation on the body of the book may come in different format like, CE Darwin, C.E. Darwin, or Darwin, CE.

 

I would really appreciate your help.

 

-CharlesD

FindChangeByList for CS6 Server?

$
0
0

Dear all,

 

can anybody please help me?

I am quite new to CS6 server and tried to use the well-known "FindChangeByList.jsx" on a generated document, but it doesn't work...

I did some changes to the script as described in the Scripting User Guide for the server version, but I am not sure if this was right as two or three chnages didn't make sense to me...

 

1. Replace the main() function with the following:

 

function main(){
if(app.documents.length > 0){
//Provide a story object or a document object.
myFindChangeByList(app.documents.item(0), false);
}
}

 

2.     Delete the myDisplayDialog function.

 

3.     Change the line:

 

 

var myFindChangeFile = "/c/FindChangeSupport/FindChangeList.txt"; 

 

to (you will have to fill in a valid file path for your system):

 

set myFindChangeFile to "yukino:FindChangeSupport:FindChangeList.txt"

--> Is this right?? This looked like AppleScript to me.
To me it made more sense to change it to

 

    var myFindChangeFile = "FindChangeSupport/FindChangeList.txt"; 

 

Doesn't a relative path work if the .txt file is in the specified subfolder?

Which would be the right syntax for Windows path like "\\myserver\somefolder\myscriptfolder\FindChangeSupport\FindChangeList.txt"?

 

4.     Delete the myFindChangeFile function.

--> I didn't find this function, I deleted the myFindFile function

 

5.     Delete the myGetScriptPath function.

 

 

On CS6 desktop version I use the unchanged script version which works well and replaces the things defined in the txt file.

 

 

 

After my changes my complete script looks like this, but nothing is replaced...

 

//FindChangeByList.jsx
//An InDesign CS4 JavaScript
/*  
@@@BUILDINFO@@@ "FindChangeByList.jsx" 2.0.0.0 10-January-2008
*/
//Loads a series of tab-delimited strings from a text file, then performs a series
//of find/change operations based on the strings read from the file.
//
//The data file is tab-delimited, with carriage returns separating records.
//
//The format of each record in the file is:
//findType<tab>findProperties<tab>changeProperties<tab>findChangeOptions<tab>description
//
//Where:
//<tab> is a tab character
//findType is "text", "grep", or "glyph" (this sets the type of find/change operation to use).
//findProperties is a properties record (as text) of the find preferences.
//changeProperties is a properties record (as text) of the change preferences.
//findChangeOptions is a properties record (as text) of the find/change options.
//description is a description of the find/change operation
//
//Very simple example:
//text    {findWhat:"--"}    {changeTo:"^_"}    {includeFootnotes:true, includeMasterPages:true, includeHiddenLayers:true, wholeWord:false}    Find all double dashes and replace with an em dash.
//
//More complex example:
//text    {findWhat:"^9^9.^9^9"}    {appliedCharacterStyle:"price"}    {include footnotes:true, include master pages:true, include hidden layers:true, whole word:false}    Find $10.00 to $99.99 and apply the character style "price".
//
//All InDesign search metacharacters are allowed in the "findWhat" and "changeTo" properties for findTextPreferences and changeTextPreferences.
//
//If you enter backslashes in the findWhat property of the findGrepPreferences object, they must be "escaped"
//as shown in the example below:
//
//{findWhat:"\\s+"}
//
//For more on InDesign scripting, go to http://www.adobe.com/products/indesign/scripting/index.html
//or visit the InDesign Scripting User to User forum at http://www.adobeforums.com
//
main();
function main(){
if(app.documents.length > 0){
//Provide a story object or a document object.
myFindChangeByList(app.documents.item(0), false);
}
function myFindChangeByList(myObject){    var myScriptFileName, myFindChangeFile, myFindChangeFileName, myScriptFile, myResult;    var myFindChangeArray, myFindPreferences, myChangePreferences, myFindLimit, myStory;    var myStartCharacter, myEndCharacter;    var myFindChangeFile = "FindChangeSupport/FindChangeList.txt";    if(myFindChangeFile != null){        myFindChangeFile = File(myFindChangeFile);        var myResult = myFindChangeFile.open("r", undefined, undefined);        if(myResult == true){            //Loop through the find/change operations.            do{                myLine = myFindChangeFile.readln();                //Ignore comment lines and blank lines.                if((myLine.substring(0,4)=="text")||(myLine.substring(0,4)=="grep")||(myLine.substring(0,5)=="glyph")){                    myFindChangeArray = myLine.split("\t");                    //The first field in the line is the findType string.                    myFindType = myFindChangeArray[0];                    //The second field in the line is the FindPreferences string.                    myFindPreferences = myFindChangeArray[1];                    //The second field in the line is the ChangePreferences string.                    myChangePreferences = myFindChangeArray[2];                    //The fourth field is the range--used only by text find/change.                    myFindChangeOptions = myFindChangeArray[3];                    switch(myFindType){                        case "text":                            myFindText(myObject, myFindPreferences, myChangePreferences, myFindChangeOptions);                            break;                        case "grep":                            myFindGrep(myObject, myFindPreferences, myChangePreferences, myFindChangeOptions);                            break;                        case "glyph":                            myFindGlyph(myObject, myFindPreferences, myChangePreferences, myFindChangeOptions);                            break;                    }                }            } while(myFindChangeFile.eof == false);            myFindChangeFile.close();        }    }
}
function myFindText(myObject, myFindPreferences, myChangePreferences, myFindChangeOptions){    //Reset the find/change preferences before each search.    app.changeTextPreferences = NothingEnum.nothing;    app.findTextPreferences = NothingEnum.nothing;    var myString = "app.findTextPreferences.properties = "+ myFindPreferences + ";";    myString += "app.changeTextPreferences.properties = " + myChangePreferences + ";";    myString += "app.findChangeTextOptions.properties = " + myFindChangeOptions + ";";    app.doScript(myString, ScriptLanguage.javascript);    myFoundItems = myObject.changeText();    //Reset the find/change preferences after each search.    app.changeTextPreferences = NothingEnum.nothing;    app.findTextPreferences = NothingEnum.nothing;
}
function myFindGrep(myObject, myFindPreferences, myChangePreferences, myFindChangeOptions){    //Reset the find/change grep preferences before each search.    app.changeGrepPreferences = NothingEnum.nothing;    app.findGrepPreferences = NothingEnum.nothing;    var myString = "app.findGrepPreferences.properties = "+ myFindPreferences + ";";    myString += "app.changeGrepPreferences.properties = " + myChangePreferences + ";";    myString += "app.findChangeGrepOptions.properties = " + myFindChangeOptions + ";";    app.doScript(myString, ScriptLanguage.javascript);    var myFoundItems = myObject.changeGrep();    //Reset the find/change grep preferences after each search.    app.changeGrepPreferences = NothingEnum.nothing;    app.findGrepPreferences = NothingEnum.nothing;
}
function myFindGlyph(myObject, myFindPreferences, myChangePreferences, myFindChangeOptions){    //Reset the find/change glyph preferences before each search.    app.changeGlyphPreferences = NothingEnum.nothing;    app.findGlyphPreferences = NothingEnum.nothing;    var myString = "app.findGlyphPreferences.properties = "+ myFindPreferences + ";";    myString += "app.changeGlyphPreferences.properties = " + myChangePreferences + ";";    myString += "app.findChangeGlyphOptions.properties = " + myFindChangeOptions + ";";    app.doScript(myString, ScriptLanguage.javascript);    var myFoundItems = myObject.changeGlyph();    //Reset the find/change glyph preferences after each search.    app.changeGlyphPreferences = NothingEnum.nothing;    app.findGlyphPreferences = NothingEnum.nothing;
}

find a text frame on the page with script label

$
0
0

hello to all

 

 

I need to create a script to

find a text frame on the page with script label "xxx"

and read its contents into a variable.

 

 

The content of the text frame is a number.

 

 

thanks

Floating Palette (InDesign CC Mac)

$
0
0

Hello fellow Javascripters!

 

   I am attempting to get a floating palette to work but though the script seems to work without an error, the floating palette never appears.  Here's the script (Note it is based off of the SnpCreateSlider.jsx example):

 

main();

 

var gAddButton;

var gRemoveButton;

var gMoveButton;

var gJustifyButton;

 

var gRowCt;

var gColCt;

 

function HachUI()

{

     this.windowRef = null;

}

 

HachUI.prototype.run = function()

{

    var ButtonPalette = new Window("palette", "Button Mover", [ 10,10, 500,500]);

    this.windowRef = ButtonPalette;

   

   //ButtonPalette.frameLocation = [10, 500];

   

    ButtonPalette.RowPanel = ButtonPalette.add('panel', undefined, "Specify row and column values");

    ButtonPalette.RowPanel.add('statictext', [5,10,25, 100], "# rows: ");

    var RowText = ButtonPalette.RowPanel.add('edittext', [5,105,25,145], "25") ;  // Row data

   

    ButtonPalette.RowPanel.add('statictext', [5,150,25, 175], "# cols: ");

    var ColText = ButtonPalette.RowPanel.add('edittext', [5,180,25,220],  "10");  //  column data

   

    ButtonPalette.ButtonPanel = ButtonPalette.add('panel', undefined, "Choices");

   

    ButtonPalette.ButtonPanel.gAddButton       = ButtonPalette.ButtonPanel.add("button", [5,10,25,40],"A");  //  for add object blocks

    ButtonPalette.ButtonPanel.gRemoveButton = ButtonPalette.ButtonPanel.add("button", [5,10,25,40],"R");  //  for remove object blocks

    ButtonPalette.ButtonPanel.gRemoveButton.enabled = false;

   

    ButtonPalette.ButtonPanel.gMoveButton     = ButtonPalette.ButtonPanel.add("button", [5,10,25,40],"M");  //  For "move button"

    ButtonPalette.ButtonPanel.gMoveButton.enabled = false;

   

    ButtonPalette.ButtonPanel.gJustifyButton    = ButtonPalette.ButtonPanel.add("button", [5,10,25,40],"J");  // for Justify button

    ButtonPalette.ButtonPanel.gJustifyButton.enabled = false;

   

    //  Handlers

    //  First Edit Text fields.

    ButtonPalette.ButtonPanel.RowText.onClick = function()

    {

        gRowCt = RowText.text.valueOf();

    }

 

   

    ButtonPalette.ButtonPanel.ColText.onClick = function()

    {

        gRowCt = ColText.text.valueOf();

    }

 

    //  Now the buttons.

    ButtonPalette.ButtonPanel.gAddButton.onClick = function()

    {

        gAddButton.enabled = false;

        gRemoveButton = true;

       

        AddBlocks(gRowCt, gColCt);

    }

 

    ButtonPalette.ButtonPanel.gRemoveButton.onClick = function()

    {

        gAddButton.enabled = true;

        gRemoveButton.eenabled = false;

        RemoveBlocks();

    }

   

    ButtonPalette.ButtonPanel.gMoveButton.onClick = function()

    {

        if(app.selection.length != 2)

           alert("Select the button and then the block...in that order.");

        else

           MoveTheButton();

    }

 

    ButtonPalette.ButtonPanel.gJustifyButton.onClick = function()

    {

          alert("Not yet implemented.");

    }

 

    ButtonPalette.show();

   

}

 

function RemoveBlocks()

{

   //  Do interesting stuff...

 

}

 

function RemoveColor()

{

   //  Do interesting stuff...

}

 

function AddBlocks(nrow, ncol)

{

   //  Do interesting stuff...
   

}

function RemoveSquares()

{

   //  Do interesting stuff...

}

 

function AddWorkingColor()

{

    //  Do interesting stuff...

}

function AddSquares(nrow, ncol)

{

   //  Do interesting stuff...   

}

 

function main()

{

   

    if(this.windowRef != null)

       new HachUI().run();

}

 

I cut a lot of the code in the standalone functions to reduce the size of the posting.  I will be happy to share it with anyone who would like to see it.

 

R,

John

Scale all frames in document | AppleScript

$
0
0

Hi, I'm hoping someone can help with this, I'm admittedly a bit green, but working at it. Thank you in advance...

 

 

I've dynamically placed multiple images into multiple script-labeled-frames (and all using the same script label—for automation purposes) in the front indesign document.

 

I now need to scale all of the frames in the document to the same percentage value, is this as easy as it sounds? I can't seem to put it together.

 

 

Cheers

Jay

Script to delete alternate layout

$
0
0

I am writing a script that puts ID documents into the correct folder and naming structure to be batch imported into a folio. The documents have two alternate layouts, the original "Print" layout and an "I" layout for ipad. I want the script to delete the "Print" layout pages before processing the document. This is effectively the first section of the document. If I try to target it as below, I receive an error that says cannot delete the doc's default section.

 

 

var allSections = myDoc.sections;   var numSections = allSections.length;      if (numSections > 1){       allSections[0].remove();       }

 

How do I correctly target this section, and what is the correct syntax for targeting it by it's altenate layout name, "Print"

 

Many thanks,

Tim

mathtype to indesign

$
0
0

Hi I have a word file with over 500 formulas that have already been published in mathtype I can I export the formulas as. Eps but replaces the link text by <eqnXXX>.

 

 

I would like to get your help with script in indesign to replace the respective texts. Eps.

 

 

Thank you very much.

 

 

 

 

Hola tengo un archivo en word con mas de 500 formulas que ya se han editado en mathtype puedo exportar las formulas como .eps pero rremplaza el link por el texto <eqnXXX>.

 

Quisiera obtener su ayuda con el script en indesign para reemplazar los textos con los respectivos .eps.

 

Muchas gracias.


[AS] Import cell range into InDesign CC

$
0
0

I have recently upgraded to InDesign CC and Office 2011 for Mac and a script that I wrote for CS5 and Office 2004 no longer works. Specifically, the instructions to place a specified cell range from Excel is being ignored. The entire spreadsheet is being placed, with disastrous results. If I re-save the xlsx file to the legacy format xls, the script works as desired.

Here's the snippet of code that used to work:

 

tell application "Adobe InDesign CC"

       

        set properties of excel import preferences to {range name:importRange, table formatting:excel unformatted table}

--importRange is a string based on the actual content of the spreadsheet, such as "A5:E128" The script doesn't work, even if I hard-code the range into the properties of the import preferences.

....

 

tell page 1

                set myPlace to place alias (filePath as string) autoflowing yes without showing options

--filePath is the path to the Excel file. It places, but doesn't respect the import range specified above

...

 

Interestingly, if I change the above to _with_ showing options, that also gets ingored. It doesn't open the import options dialog.

 

Is there different verbiage I should be using for specifying import options for Excel files that are saved as xlsx? I couldn't find the AS scripting guide and sample scripts for CC as there was for CS5.

 

Any help would be much appreciated.

Detecting a layer by name

$
0
0

The following code is part of a larger script. I'm trying to detect if the layer "Canons Grid" exists. If it doesn't then create a new layer with that name. This code fails everytime, even if the layer doesn't exist. What am i doing wrong?

 

 

 

var doc = app.activeDocument;
var canonLayer;            try{                  canonLayer = doc.layers.itemByName("Canons Grid");            }            catch(e)            {                  canonLayer = doc.layers.add({name: "Canons Grid"});            }  

A script for adapting text to frame

$
0
0

Hi all,

 

We are using InDesignCC for creating PDF files online.

This hapens with XML output. And on demand our customers can put variabel fields in en can generate a pdf to view the results.

 

Online it looks something like this:

example.png

This is the problem:

A textbox in InDesign have a fixed length. But the customers can give in a large text for this field. Larger than the tekstbox it self.

Now, default, InDesign sets the given text on to 2 lines.

Is there a script to be attached on a textbox that horizontaly scales the text to fit the textbox?

 

I hope someone can help.

 

thx

Tables

$
0
0

I need a shrink wrap column width for the whole table columns (Resize selected columns to width of selected cells' contents).

 

I need also a script how to copy the format of a formatted column to an unformatted column.

Thanks

Change the characterstyle in all textframes

$
0
0

Hello all,

 

i have a problem in my javascript script. I want a script that check all textframes in the document and it have to check the characterstyle from each char.

If there is a "-" in the text, the characterstyle will switch to normal. The problem is that i did not find the text in the textframe with the javascript. I´m new in the business.

I think my approach is wrong, but i can´t find an another one.  

 

My code :

 

var doc = app.activeDocument;

var tf = doc.textFrames.anyItem();

var paras = tf.paragraphs.everyItem().getElements();

var applied_style = doc.characterStyles.itemByName('Cent');

 

 

var paras_with_style = [];

for (var i=0,l=paras.length; i<l; i++) {

   var para = paras[i];

   if (para.appliedCharacterStyle == applied_style) {

      var contenttext = para.contents;

            if (contenttext == "-") {

                    para.changeTextPreferences.position = Position.normal;

            }

  else {

                    para.changeTextPreferences.position = Position.superscript;

            }

   }

}

 

Thanks for your help

 

Greets Alex

Viewing all 8771 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>