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

Javascript code to create preview in dialog box Adobe Illustrator

Explorer ,
Aug 10, 2023 Aug 10, 2023

Copy link to clipboard

Copied

I have code to create copies of an object on the layer. The code also includes a dialog box for entering information. I need to adapt a code to generate a preview of the copies when the checkbox is checked. I've seen some scripts with this function, but I couldn't adapt it for myself. Does anyone have any ideas?

TOPICS
Scripting

Views

1.4K

Translate

Translate

Report

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

Advocate , Aug 11, 2023 Aug 11, 2023

Une approche rapide, non affinée...

 

 

// JavaScript Document
//Criar caixa de diálogo
var Undo = false;
    if (app.selection.length === 1 && app.selection[0].typename === "GroupItem") {
      var grupoSelecionado = app.selection[0];
      createDialog();
    }
    else {
      alert("Selecione um único grupo na Camada 1.");
    }
// -------
function createColumnGroup(parent, name) {
  var group = parent.add("group", undefined, { name: name });
      group.orientation = "column";
      group.alig
...

Votes

Translate

Translate
Adobe
Community Expert ,
Aug 10, 2023 Aug 10, 2023

Copy link to clipboard

Copied

Can you share samples of the script where you see the functionalty you want. Then it would be easier to integrate it with your code(share that as well).

-Manan

Votes

Translate

Translate

Report

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
Explorer ,
Aug 11, 2023 Aug 11, 2023

Copy link to clipboard

Copied

This is the complete code. It is for specific use, so your clipboard needs to be at least 1.50m wide. As you can see, in the dialog box I already inserted the "Visualize" checkbox, but I couldn't implement the code for the visualization of the copies that the main code performs. I've seen preview commands in other scripts, so I imagine it's possible through codes.

//Criar caixa de diálogo

function createColumnGroup(parent, name) {
var group = parent.add("group", undefined, { name: name });
group.orientation = "column";
group.alignChildren = ["left", "top"];
group.spacing = 10;
group.margins = 0;
return group;
}

function createEditText(parent, config) {
var editText = parent.add('edittext {properties: {name: "edittext"}}');
editText.preferredSize.width = config.preferredWidth;
editText.alignment = config.alignment;
return editText;
}

function createDialog() {
var dialog = new Window("dialog", "Multiplicar e distribuir");
var mainGroup = createColumnGroup(dialog, "mainGroup");

var quantidadeGroup = createColumnGroup(mainGroup, "quantidadeGroup");
var espacamentoGroup = createColumnGroup(mainGroup, "espacamentoGroup");

var sharedConfig = {
preferredWidth: 100,
alignment: ["left", "center"],
};

var quantidadeLabel = quantidadeGroup.add("statictext", undefined, undefined, { name: "quantidadeLabel" });
quantidadeLabel.text = "Quantidade:";

var quantidadeEditText = createEditText(quantidadeGroup, sharedConfig);

var espacamentoLabel = espacamentoGroup.add("statictext", undefined, undefined, { name: "espacamentoLabel" });
espacamentoLabel.text = "Espaçamento:";

var espacamentoEditText = createEditText(espacamentoGroup, sharedConfig);

var visualizarCheckbox = mainGroup.add("checkbox", undefined, undefined, { name: "visualizarCheckbox" });
visualizarCheckbox.text = "Visualizar";
visualizarCheckbox.preferredSize.width = 80;
visualizarCheckbox.preferredSize.height = 20;

var buttonGroup = dialog.add("group", undefined, { name: "buttonGroup" });
buttonGroup.orientation = "row";
buttonGroup.alignChildren = ["center", "center"];
buttonGroup.spacing = 10;
buttonGroup.margins = 0;
buttonGroup.alignment = ["center", "top"];

var okButton = buttonGroup.add("button", undefined, undefined, { name: "okButton" });
okButton.text = "OK";

var cancelButton = buttonGroup.add("button", undefined, undefined, { name: "cancelButton" });
cancelButton.text = "Cancel";

okButton.onClick = function () {

// Código principal
// Verifica se o grupo está selecionado
if (app.selection.length === 1 && app.selection[0].typename === "GroupItem") {
var grupoSelecionado = app.selection[0];
var distanciaHorizontal = parseFloat(espacamentoEditText.text.replace(".", "").replace(",", ".")) * 28.3465;

// Armazena a altura do grupo selecionado
var alturaGrupoInicial = grupoSelecionado.height;

// Define a posição do grupo selecionado em relação à prancheta
var prancheta = app.activeDocument.artboards[0];
var posX = prancheta.artboardRect[0] + 4.5 * 28.3465;
var posY = prancheta.artboardRect[1] - 0.5 * 28.3465;
grupoSelecionado.position = [posX, posY];

var quantidadeCopias = parseInt(quantidadeEditText.text);

if (isNaN(quantidadeCopias) || quantidadeCopias < 1) {
alert("Quantidade inválida. O valor deve ser um número inteiro maior que zero.");
} else {
var posXAtual = posX + grupoSelecionado.width + distanciaHorizontal;
var posYAtual = posY;

for (var i = 1; i < quantidadeCopias; i++) {
var novaCopia = grupoSelecionado.duplicate();
novaCopia.position = [posXAtual, posYAtual];
posXAtual += grupoSelecionado.width + distanciaHorizontal;

if (posXAtual + grupoSelecionado.width > 129 * 28.3465) {
posXAtual = posX;
posYAtual -= alturaGrupoInicial + distanciaHorizontal;
}
}
}
} else {
alert("Selecione um único grupo na Camada 1.");
}

dialog.close();
};

cancelButton.onClick = function () {
dialog.close();
};

dialog.show();
}

createDialog();

Votes

Translate

Translate

Report

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 ,
Aug 11, 2023 Aug 11, 2023

Copy link to clipboard

Copied

I have moved your post to the Illustrator forum so that you get better help. I think I am not getting your ask properly. Creation of dialog and all is fine but what do you mean by preview is confusing me. Hopefully someone better versed with Illustrator will chime in.

-Manan

Votes

Translate

Translate

Report

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
Explorer ,
Aug 11, 2023 Aug 11, 2023

Copy link to clipboard

Copied

I need a preview before it clicks "ok" when checking the checkbox. But I appreciate your effort.

Votes

Translate

Translate

Report

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
Advocate ,
Aug 11, 2023 Aug 11, 2023

Copy link to clipboard

Copied

Une approche rapide, non affinée...

 

 

// JavaScript Document
//Criar caixa de diálogo
var Undo = false;
    if (app.selection.length === 1 && app.selection[0].typename === "GroupItem") {
      var grupoSelecionado = app.selection[0];
      createDialog();
    }
    else {
      alert("Selecione um único grupo na Camada 1.");
    }
// -------
function createColumnGroup(parent, name) {
  var group = parent.add("group", undefined, { name: name });
      group.orientation = "column";
      group.alignChildren = ["left", "top"];
      group.spacing = 10;
      group.margins = 0;
  return group;
}
// -------
function createEditText(parent, config) {
  var editText = parent.add('edittext {properties: {name: "edittext"}}');
      editText.preferredSize.width = config.preferredWidth;
      editText.alignment = config.alignment;
  return editText;
}
// -------
function createDialog() {
  var dialog = new Window("dialog", "Multiplicar e distribuir");
  var mainGroup = createColumnGroup(dialog, "mainGroup");

  var quantidadeGroup = createColumnGroup(mainGroup, "quantidadeGroup");
  var espacamentoGroup = createColumnGroup(mainGroup, "espacamentoGroup");
  var sharedConfig = {
      preferredWidth: 100,
      alignment: ["left", "center"],
};

var quantidadeLabel = quantidadeGroup.add("statictext", undefined, undefined, { name: "quantidadeLabel" });
    quantidadeLabel.text = "Quantidade:";


var quantidadeEditText = createEditText(quantidadeGroup, sharedConfig);
     quantidadeEditText.text = 3;
var espacamentoLabel = espacamentoGroup.add("statictext", undefined, undefined, { name: "espacamentoLabel" });
    espacamentoLabel.text = "Espaçamento:";

var espacamentoEditText = createEditText(espacamentoGroup, sharedConfig);
    espacamentoEditText.text = 1;
var visualizarCheckbox = mainGroup.add("checkbox", undefined, undefined, { name: "visualizarCheckbox" });
    visualizarCheckbox.text = "Visualizar";
    visualizarCheckbox.preferredSize.width = 80;
    visualizarCheckbox.preferredSize.height = 20;

var buttonGroup = dialog.add("group", undefined, { name: "buttonGroup" });
    buttonGroup.orientation = "row";
    buttonGroup.alignChildren = ["center", "center"];
    buttonGroup.spacing = 10;
    buttonGroup.margins = 0;
    buttonGroup.alignment = ["center", "top"];

var okButton = buttonGroup.add("button", undefined, undefined, { name: "okButton" });
    okButton.text = "OK";

var cancelButton = buttonGroup.add("button", undefined, undefined, { name: "cancelButton" });
    cancelButton.text = "Cancel";

    okButton.onClick = function () {
        if (Undo == false) {
          var q = quantidadeEditText.text;
          var k = espacamentoEditText.text;  alert(q+"  "+k)
              traitement(q,k);
        }
    dialog.close();
    };
    visualizarCheckbox.onClick = function() {
      if (visualizarCheckbox.value == true) {
        var q = quantidadeEditText.text;
        var k = espacamentoEditText.text;  //alert(q+"  "+k)
          traitement(q,k);
          app.redraw();
          Undo = true;
      }
      if (visualizarCheckbox.value == false) {
          app.executeMenuCommand("undo");
          app.redraw();
          Undo = false;
      }
    }
  cancelButton.onClick = function () {
    if (Undo) {
      app.executeMenuCommand("undo");
      app.redraw();
    }
    dialog.close();
  };
  dialog.show();
}
// -------
function traitement(q,k) {
  // Código principal
  // Verifica se o grupo está selecionado
    var distanciaHorizontal = parseFloat(k.replace(".", "").replace(",", ".")) * 28.3465;
  // Armazena a altura do grupo selecionado
    var alturaGrupoInicial = grupoSelecionado.height;
    var quantidadeCopias = parseInt(q);

    if (isNaN(quantidadeCopias) || quantidadeCopias < 1) {
    alert("Quantidade inválida. O valor deve ser um número inteiro maior que zero.");
    return;
    }
    else {
    // Define a posição do grupo selecionado em relação à prancheta
    var prancheta = app.activeDocument.artboards[0];
    var posX = prancheta.artboardRect[0] + 4.5 * 28.3465;
    var posY = prancheta.artboardRect[1] - 0.5 * 28.3465;
        grupoSelecionado.position = [posX, posY];
    var posXAtual = posX + grupoSelecionado.width + distanciaHorizontal;
    var posYAtual = posY;

      for (var i = 1; i < quantidadeCopias; i++) {
        var novaCopia = grupoSelecionado.duplicate();
            novaCopia.position = [posXAtual, posYAtual];
            posXAtual += grupoSelecionado.width + distanciaHorizontal;

        if (posXAtual + grupoSelecionado.width > 129 * 28.3465) {
          posXAtual = posX;
          posYAtual -= alturaGrupoInicial + distanciaHorizontal;
        }
      }
    }
}

 

 

de elleere

Votes

Translate

Translate

Report

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
Explorer ,
Aug 11, 2023 Aug 11, 2023

Copy link to clipboard

Copied

Damn! This is fantastic. Worked perfectly. I was having a lot of trouble doing this. Helped me a lot. Now a doubt and a curiosity. The question: could the preview be updated just by typing "TAB" in the quantity and spacing? I noticed that it only updates if I uncheck and recheck the checkbox. Curiosity: in what sense could it be more refined? Thank you very much.

Votes

Translate

Translate

Report

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
Advocate ,
Aug 12, 2023 Aug 12, 2023

Copy link to clipboard

Copied

Bonjour,

Décocher vous permet de modifier les valeurs quantité et espacement.

OK pour valider.

René

PS On peut toujours faire mieux, je n'ai pas le temps pour cela...

La question: l’aperçu pourrait-il être mis à jour simplement en tapant « TAB » dans la quantité et l’espacement.

Réponse: certainement.

Votes

Translate

Translate

Report

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
Advocate ,
Aug 22, 2023 Aug 22, 2023

Copy link to clipboard

Copied

Bonjour Marcos,

Une solution qui semble fonctionner comme tu l'entends.

René.

// JavaScript Document
// dialog 21 reduced.js
// Sat, 12 August 2023 20:09:03 GMT
// Of lANDRY René - elleere.
// At the suggestion of Marcos Adriano
// INIT -----------------------
  var title = "Multiplicar e distribuir";
  var monUnit = "cm"; // cm mm in pt ou px
  var q = 30; // cantidad   // regPref1
  var g = 0;  // canal/gouttière  // regPref2 (Assinar - Autorizado)
  // Posición izquierda y superior del primer elemento (x,y)
  var posUnit = "mm"; // cm mm in pt ou px
  var X0 = 30;  // posUnit
  var Y0 = -15; // posUnit
  // Margem direita
  var XD = 20;  // posUnit
  // Largura da implantação horizontal
  var wAb = true;  // se true a largura da prancheta ativa
  var wCt = 1290; // se wAb == false // posUnit
  // Dimensões do objeto selecionado
  var geom = false; // visible-bounds flase senão geometric-bounds true
 //----------------------------
  var unit = new UnitValue(1 + monUnit).as('pt');
  var unitPos = new UnitValue(1 + posUnit).as('pt');
  var regPref1 = /^[\d]{1,5}$/; // del 1 a 5 Figuras
  var regPref2 = /^[0-9.-]{1,15}$/; // del 1 a 15 Figuras
  var sel;  // Objeto selecionado
// -------
function main() {
    if (selection.length > 0) {
      var sel = selection[0]; // Objeto selecionado
          app.selection = null; // alert(sel)
          createDialog(sel);
    }
    else {
      alert("Selecione pelo menos um objeto!.");
    }
}
// -------
 if (app.documents.length > 0) {main();}
 else {alert("Um documento deve ser aberto e um objeto selecionado!");}
// -------
function createDialog(sel) {
  var res = "dialog { \
      txt: '', \
      orientation: 'column', alignChildren: 'left', \
      properties:{ closeButton: false }\
        addr1: Group { orientation: 'row', \
          s: StaticText { text:'cantidad:' ,characters: 15 }, \
          e: EditText { preferredSize: [80, 20]}, \
        } \
        addr2: Group { orientation: 'row', \
          s: StaticText { text:'' ,characters: 15 }, \
          e: EditText { preferredSize: [80, 20] }, \
        } \
        v: Group { orientation: 'row', \
          s: StaticText { text:'Visualiz', characters:15 }, \
          vckbox: Checkbox { text: ' - Click Test -' } \
        } \
        btnPnl: Group { orientation: 'row', \
          okBtn: Button { text:'OK', properties:{ name:'ok' } }, \
          cancelBtn: Button { text:'ESC', properties:{name:'cancel' } } \
        } \
  } \
  ";
  var w = new Window (res);
      w.location = [100,300];
      w.text = title;
  var e = w.addr1.e; e.text = q;
      e.active = true;
  var b = w.addr2.e; b.text = g;
      w.addr2.s.text = "Calha em " + monUnit+ ":";
  var vb = w.v.vckbox;
  var mode = false;
  var er = false; //
         e.onChange = function () {
           if ( e.text*1 != q) {
              er = init(); mode = true;
            }
          if (vb.value && !er) {
            refrech(sel);
            traitement(sel,X0,Y0,XD,q,g,unit,unitPos,geom,wAb,wCt);
            redraw();
            e.active = true;
          }

        } //
        b.onChange = function () {
           if (  b.text*1 != g) {
              er = init(); mode = true;
            }
          if (vb.value && !er) {
            refrech(sel);
            traitement(sel,X0,Y0,XD,q,g,unit,unitPos,geom,wAb,wCt);
            redraw();
            e.active = true;
          }
        } //
        vb.onClick = function() {
          if ( vb.value ) {
            er = init();
              if ( !er ) {traitement(sel,X0,Y0,XD,q,g,unit,unitPos,geom,wAb,wCt);}
            redraw();
            e.active = true;
          }
          else  {
            refrech(sel);
            er = init();
            e.active = true;
          }
        } //
        w.btnPnl.okBtn.onClick = function () {
          mode = false;
          if ( e.text*1 != q ||  b.text*1 != g ) {
            er = init(); mode = true;
          }
          if (!er) {
            if ( !vb.value ) {traitement(sel,X0,Y0,XD,q,g,unit,unitPos,geom,wAb,wCt);}
            else if ( mode ) {
              refrech(sel);
              traitement(sel,X0,Y0,XD,q,g,unit,unitPos,geom,wAb,wCt);
            }
          }
          w.close();
        } //
        w.btnPnl.cancelBtn.onClick = function() {
            if ( vb.value == true ) {
              refrech(sel);
              sel.selected = true;
            }
          w.close();
        } //
        function init() {
          var er = false;
                if (saisie(e.text,regPref1) && e.text != '0' ) {q = e.text*1;}
                else {beep(); er = true;}
                if (saisie(b.text,regPref2) ) {g = b.text*1;}
                else {beep(); er = true;}
              return er;
        } //
        function refrech(sel) {
          app.executeMenuCommand("undo");
          redraw(); sel.selected = false;
        }
w.show();
}
// -------
function prop(Bounds) {return [Bounds[2]-Bounds[0],Bounds[1]-Bounds[3]];}
// -------
function saisie(chaine,reg) {
   if (reg.test(chaine)) return true; return false;
}
// -------
function traitement(obj,X0,Y0,XD,q,g,unit,unitPos,geo,wAb,fixe) {
  // Define a posição do objtet[0] selecionado em relação à prancheta
      g *= unit;
  var doc = app.activeDocument,
      vBs = !geo  ? obj.visibleBounds : obj.geometricBounds,
      propi = prop(vBs),
      W = propi[0],
      H = propi[1],
      difw = (W - obj.width)/2, //pt
      dec = W + g,
      idx = doc.artboards.getActiveArtboardIndex(),
      ab = doc.artboards[idx],
      rect = ab.artboardRect,
      posX = rect[0] + X0 * unitPos + difw,
      posY = rect[1] + Y0 * unitPos - difw,
      posXAtual = posX,
      posYAtual = posY,
      wCont = wAb ? rect[2] : rect[0] + fixe;
      grd = doc.groupItems.add();

        for (var i = 0; i < q; i++) {
          if ( (posXAtual + W - difw) > (wCont - XD*unitPos)) {
            posXAtual = posX;
            posYAtual -= H + g;
          }
          var novaCopia = obj.duplicate(grd);
              novaCopia.position = [posXAtual,posYAtual];
              posXAtual += dec;
        }
}
// -------

 

Votes

Translate

Translate

Report

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
Explorer ,
Aug 22, 2023 Aug 22, 2023

Copy link to clipboard

Copied

Thank you for your commitment. The previous code served well. I'm still trying to improve it. That last one sent didn't work.

Votes

Translate

Translate

Report

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
Advocate ,
Aug 23, 2023 Aug 23, 2023

Copy link to clipboard

Copied

J'ai testé le dernier script sur Illustrator CS6, il fonctionne.

Quel est le problème pour vous, il se passe quoi ? (la boîte de dialogue s'affiche en haut à gauche [100,300] ?)

René.

renl80416020_0-1692776247486.png

renl80416020_0-1692776569183.png

renl80416020_2-1692777030986.png

Votes

Translate

Translate

Report

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
Explorer ,
Aug 23, 2023 Aug 23, 2023

Copy link to clipboard

Copied

The dialog appears normally, but the preview doesn't work and neither does the distribution when I click "Ok". Nothing happens.

Votes

Translate

Translate

Report

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
Guide ,
Aug 11, 2023 Aug 11, 2023

Copy link to clipboard

Copied

Do you mean something like this? 

var path1;
var w = new Window("dialog");
var checkbox = w.add("checkbox");
checkbox.onClick = function() {
    if (checkbox.value == true) {
        main();
        app.redraw();
    }
    if (checkbox.value == false) {
        path1.remove();
        app.redraw();
    }
}
var button = w.add("button", undefined, "Done");
button.onClick = function() {
    w.close();
}
w.show();

// example
function main () {
    var doc = app.activeDocument;
    path1 = doc.pathItems.rectangle(
        - doc.height / 4, doc.width / 4, doc.width / 2, doc.height / 2
    );
}

 

 

Votes

Translate

Translate

Report

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
Explorer ,
Aug 23, 2023 Aug 23, 2023

Copy link to clipboard

Copied

I believe so, but as I am a layman, I would not know how to adapt it to my code. But thanks for the help

Votes

Translate

Translate

Report

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
Advocate ,
Aug 23, 2023 Aug 23, 2023

Copy link to clipboard

Copied

LATEST

Merci pour la réponse timide mais positive...

René

Votes

Translate

Translate

Report

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