Exit
  • Global community
    • Language:
      • Deutsch
      • English
      • Español
      • Français
      • Português
  • 日本語コミュニティ
  • 한국 커뮤니티
8

applying paragraph style to photo captions

Community Beginner ,
Sep 27, 2023 Sep 27, 2023

Greetings to you! Help me fix the error in the script. He should create captions to photos, apply the paragraph style selected in the dialog box and indent from the photo. The error most likely lies in reading the selected paragraph style from the drop-down list, because everything works correctly without this part of the code.

 

Here is the code itself (there are a lot of words in Russian, do not be afraid):

function main() {
// Проверяем, открыт ли документ InDesign
if (app.documents.length > 0) {
var myDialog = app.dialogs.add({name:"Настройка отступа", canCancel:true});
var document = app.activeDocument;
var currentPage = app.activeWindow.activePage;
var paragraphStyles = document.paragraphStyles.everyItem().name;
with(myDialog){
 
// Создаем колонку таблицы (контейнер для всех элементов)
with(dialogColumns.add()){
// Создаем колонку для выбора стиля абзаца
with(borderPanels.add()){
with(dialogColumns.add()){
staticTexts.add({staticLabel: "Стиль абзаца:"});
}
with(dialogColumns.add()){
var selectedStyle = dropdowns.add({stringList: app.activeDocument.paragraphStyleGroups.item(0).paragraphStyles.everyItem().name, selectedIndex: 0});
}}
 
with(dialogColumns.add()){
 
// Создаем поле для значения отступа и указываем значение по умолчанию
with(borderPanels.add()){
with(dialogColumns.add()){
staticTexts.add({staticLabel:"Отступ:"})};
with(dialogColumns.add()){
var offsetN = realEditboxes.add({editValue:20});
}}
}}
// Выводим диалог с кнопками ОК и Cancel на экран
var myDisplay = myDialog.show();
if(myDisplay){
 
var paragraphStyle = document.paragraphStyleGroups.item(0).paragraphStyles.itemByName(selectedStyle);
var offset;
offset = offsetN.editValue;
 
  var myDocument = app.activeDocument;
  var myPage = myDocument.layoutWindows[0].activePage;
  // Получаем все графические элементы на странице
  var allGraphics = myPage.allGraphics;
  var x = 4.5
  // Перебираем все графические элементы
for (var i = 0; i < allGraphics.length; i++) {
    var graphic = allGraphics[i];
 
    // Проверяем, заблокирован ли текущий слой, на котором находится графический элемент 
    if (graphic.itemLayer.locked) {
        continue; // Если слой заблокирован, пропускаем его и переходим к следующему
    }
    
    // Проверяем, заблокирован ли текущий элемент
    if (graphic.locked) {
        continue; // Если элемент заблокирован, пропускаем его и переходим к следующему
    }
 
    // Создаем текстовый блок для подписи
    var captionFrame = myPage.textFrames.add (app.documents[0].layers.item('Подписи'));
 
    // Получаем название файла изображения
    var fileName = graphic.itemLink.name;
 
    // Помещаем подпись ниже изображения
    captionFrame.geometricBounds = [
        graphic.parent.geometricBounds[2] + offset +x, // Верхний край подписи (смещение на 3 пункта)
        graphic.parent.geometricBounds[1], // Левый край подписи
        graphic.parent.geometricBounds[2] + offset +20, // Нижний край подписи (смещение по вертикали)
        graphic.parent.geometricBounds[3] // Правый край подписи
    ];
 
    // Устанавливаем содержимое текстового кадра равным названию файла
    captionFrame.contents = fileName;
 
    // Выравниваем текст по центру
    captionFrame.texts[0].justification = Justification.CENTER_ALIGN;
 
  }
}
}
}
}
app.doScript(main, ScriptLanguage.JAVASCRIPT, undefined, UndoModes.ENTIRE_SCRIPT, 'Add Caption To Images 2');
TOPICS
Bug , Scripting
407
Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines

correct answers 1 Correct answer

Community Expert , Sep 27, 2023 Sep 27, 2023

Hi vistarmedia@gmail.com , Here’s an example for getting a paragraph style from a dropdown:

 

 

makeDialog();

var psSel;
function makeDialog(){
    var theDialog = app.dialogs.add({name:"Dialog Components", canCancel:true});
    with(theDialog){
        with(dialogColumns.add()){
                with(dialogColumns.add()){
                    staticTexts.add({staticLabel:"Paragraph Styles:"});
                }
                with(dialogColumns.add()){
                    psSel = dropdowns.add(
...
Translate
Community Expert ,
Sep 27, 2023 Sep 27, 2023

Hi vistarmedia@gmail.com , Here’s an example for getting a paragraph style from a dropdown:

 

 

makeDialog();

var psSel;
function makeDialog(){
    var theDialog = app.dialogs.add({name:"Dialog Components", canCancel:true});
    with(theDialog){
        with(dialogColumns.add()){
                with(dialogColumns.add()){
                    staticTexts.add({staticLabel:"Paragraph Styles:"});
                }
                with(dialogColumns.add()){
                    psSel = dropdowns.add({stringList:getArrayNames(app.activeDocument.allParagraphStyles), selectedIndex:0, minWidth:80});
                } 
        }
        if(theDialog.show() == true){
            psSel = app.activeDocument.allParagraphStyles[psSel.selectedIndex];
            main();
            theDialog.destroy();
        }
    }
}

function main(){
    alert("\rChosen Paragraph Style: " + psSel.name);
}

/**
* Returns a list of style names from the provided array of styles. 
* Note does not work with a collection allParagraphStyles is an array paragraphStyles is a collection
* @ param the object array 
* @ return array of names 
*/
function getArrayNames(arr){
    var a = new Array;
    for(var i = 0; i < arr.length; i++){
        a.push(arr[i].name);
    }
    return a
}

 

 

 

Screen Shot 24.png

Screen Shot 25.png

Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Beginner ,
Sep 27, 2023 Sep 27, 2023

Thank you very much! for some reason, InDesign was giving an error referring to this code snippet with a drop-down list. Specifically on getArrayNames.

 vistarmediagmailcom_0-1695825097057.png

Then I replaced this line with this one (I have paragraph styles nested in a group):

var selectedStyle = dropdowns.add({stringList: app.activeDocument.paragraphStyleGroups.item(0).paragraphStyles.everyItem().name, selectedIndex: 0});

 

And then everything worked as it should!

Thanks again! You solved a problem I've been working on for almost a week in an instant)

 

Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Sep 27, 2023 Sep 27, 2023
LATEST

Just note in case you don’t know—you can get all of the document’s paragraph style, grouped or not, via the .allParagraphStyles property. It returns an array, not a collection, which is why I included the getArrayNames function in my code—you would have to add the same function to your script. Your code would get an array of paragraph styles in the document’s first group, but not from other groups.

 

For example with this style setup:

 

Screen Shot 26.png

 

 

//Returns Group 1 styles ID Default,body

$.writeln(app.activeDocument.paragraphStyleGroups.item(0).paragraphStyles.everyItem().name)

 

 

While this gets all of the styles:

 

$.writeln(getArrayNames(app.activeDocument.allParagraphStyles))
//returns [No Paragraph Style],[Basic Paragraph],Caption Text,Foot,Text,Logo,SubLogo,ID Default,body

/**
* Returns a list of style names from the provided array of styles. 
* Note does not work with a collection allParagraphStyles is an array paragraphStyles is a collection
* @ param the object array 
* @ return array of names 
*/
function getArrayNames(arr){
    var a = new Array;
    for(var i = 0; i < arr.length; i++){
        a.push(arr[i].name);
    }
    return a
}

 

 

 

Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines