Copy link to clipboard
Copied
I’m working with a script in Adobe Illustrator to import CSV files and assign their values to variables in a document. The script loads the CSV files correctly, but when I try to apply the variables to an Illustrator document, I receive an error saying “Error: No document found” or “Error: The dataset file is invalid.”
I’ve verified that I always have a document open in Illustrator before attempting to apply the variables, but it seems like the script isn't recognizing the document properly.
Details:
The script loads the CSV files and shows the variables in the list.
The Illustrator document is always open.
The code uses the doc.importVariables() function to apply the variables to the document.
The specific error occurs when trying to apply the CSV data to the document, even though the CSV file loads correctly.
I’ve tried the following methods:
Restarting Illustrator.
Opening different Illustrator documents.
Checking that the variables are correctly assigned and there are no issues with the CSV file or data format.
What could be causing Illustrator to not recognize the document when trying to apply variables from a CSV file? How can I fix this issue to ensure the document is properly linked with the variables loaded from the CSV?
---------------------------------------------------------------------------------------------------------------
#target illustrator
#targetengine "BatchCSVEngine"
/*
BatchCSV_VarsLoader_Flotante.jsx
- Ventana flotante persistente con lista de múltiples CSV
- Vista previa de las primeras filas
- Al aplicar: elimina variables anteriores y carga solo las nuevas desde el CSV seleccionado
- Guardar XML debug en el escritorio
*/
// ---------- Helpers ----------
function trimStr(s){ return String(s || "").replace(/^\s+|\s+$/g,""); }
function xmlEscape(s){ return String(s || "").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/\"/g,""").replace(/'/g,"'"); }
// Parse CSV simple
function parseCSV(content){
var lines = content.replace(/\r/g,"").split("\n");
var rows = [];
for(var i=0; i<lines.length; i++){
var line = lines[i];
if(!line) continue;
var cur="", row=[], inQuotes=false;
for(var j=0; j<line.length; j++){
var ch = line.charAt(j), next = line.charAt(j+1);
if(ch=='"'){
if(inQuotes && next=='"'){ cur+='"'; j++; continue; }
inQuotes=!inQuotes; continue;
}
if(!inQuotes && ch==','){ row.push(cur); cur=""; continue; }
cur+=ch;
}
row.push(cur);
rows.push(row);
}
return rows;
}
// Build Illustrator XML (based on sample that works)
function buildXmlFromRows(rows){
if(!rows || rows.length < 1) return null;
var headers = rows[0];
for(var i=0; i<headers.length; i++) headers[i] = trimStr(headers[i]) || ("Var" + (i+1));
var xml = '';
xml += '<?xml version="1.0" encoding="UTF-8"?>\n';
xml += '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20001102//EN" "http://www.w3.org/TR/2000/CR-SVG-20001102/DTD/svg-20001102.dtd" [\n';
xml += '\t<!ENTITY ns_vars "http://ns.adobe.com/Variables/1.0/">\n';
xml += '\t<!ENTITY ns_flows "http://ns.adobe.com/Flows/1.0/">\n';
xml += ']>\n';
xml += '<svg>\n<variableSets xmlns="&ns_vars;">\n<variableSet locked="none" varSetName="binding1">\n';
xml += '<variables>\n';
for(var h=0; h<headers.length; h++){
xml += ' <variable varName="'+xmlEscape(headers[h])+'" trait="textcontent" category="&ns_flows;"/>\n';
}
xml += '</variables>\n';
xml += '<v:sampleDataSets xmlns:v="&ns_vars;">\n';
for(var r=1; r<rows.length; r++){
var row = rows[r]; if(!row) continue;
var allEmpty = true;
for(var c=0; c<row.length; c++){
if(trimStr(row[c]) !== ""){ allEmpty = false; break; }
}
if(allEmpty) continue;
xml += '<v:sampleDataSet dataSetName="Fila'+r+'">\n';
for(var c=0; c<headers.length; c++){
var val = (c < row.length) ? row[c] : "";
xml += '<'+headers[c]+'>\n<p>'+xmlEscape(trimStr(val))+'</p>\n</'+headers[c]+'>\n';
}
xml += '</v:sampleDataSet>\n';
}
xml += '</v:sampleDataSets>\n</variableSet></variableSets>\n</svg>';
return xml;
}
// ---------- UI & Logic ----------
if(typeof $.global.BatchCSV === "undefined") $.global.BatchCSV = { files:[], rowsCache:{} };
var W = new Window("palette","Batch CSV Vars Loader (Flotante)",undefined,{resizeable:true});
W.orientation="column"; W.alignChildren=["fill","top"]; W.preferredSize=[560,420];
var gTop = W.add("group"); gTop.orientation = "row";
var btnLoad = gTop.add("button", undefined, "📂 Cargar CSV(s)");
var btnRemove = gTop.add("button", undefined, "🗑 Eliminar");
var btnApply = gTop.add("button", undefined, "✅ Aplicar al documento");
var btnSave = gTop.add("button", undefined, "💾 Guardar XML debug");
var gMid = W.add("group"); gMid.orientation = "row"; gMid.alignChildren = ["fill", "fill"];
var listBox = gMid.add("listbox", undefined, [], { multiselect: false }); listBox.preferredSize = [260, 300];
var previewBox = gMid.add("edittext", undefined, "", { multiline: true, scrolling: true }); previewBox.preferredSize = [280, 300];
var status = W.add("statictext", undefined, "Estado: listo"); status.preferredSize.height = 20;
// Refresh UI
function refreshList(){
listBox.removeAll();
for(var i=0; i<$.global.BatchCSV.files.length; i++){
listBox.add("item", (i+1) + ". " + $.global.BatchCSV.files[i].name);
}
if(listBox.items.length > 0) listBox.selection = 0;
refreshPreview();
}
function refreshPreview(){
if(!listBox.selection){ previewBox.text=""; return; }
var f = $.global.BatchCSV.files[listBox.selection.index];
var rows = $.global.BatchCSV.rowsCache[f.fsName];
if(!rows){
try{
f.open("r");
var content = f.read();
f.close();
rows = parseCSV(content);
$.global.BatchCSV.rowsCache[f.fsName] = rows;
} catch(e){ rows = []; }
}
var out = "";
var max = Math.min(10, rows.length);
for(var r=0; r<max; r++){ out += rows[r].join(" | ") + "\n"; }
previewBox.text = out;
}
// Handlers
btnLoad.onClick = function(){
var sel = File.openDialog("Selecciona CSV(s)", "*.csv", true);
if(!sel) return;
var arr = (sel instanceof Array) ? sel : [sel];
for(var i = 0; i < arr.length; i++){
var f = arr[i];
var exists = false;
for(var j = 0; j < $.global.BatchCSV.files.length; j++){
if($.global.BatchCSV.files[j].fsName == f.fsName){ exists = true; break; }
}
if(!exists){
$.global.BatchCSV.files.push(f);
delete $.global.BatchCSV.rowsCache[f.fsName];
}
}
refreshList();
status.text = "Archivos cargados: " + $.global.BatchCSV.files.length;
};
btnRemove.onClick = function(){
if(!listBox.selection) return;
var idx = listBox.selection.index;
var f = $.global.BatchCSV.files[idx];
$.global.BatchCSV.files.splice(idx,1);
delete $.global.BatchCSV.rowsCache[f.fsName];
refreshList();
status.text = "Archivo eliminado.";
};
listBox.onChange = function(){ refreshPreview(); };
btnApply.onClick = function(){
if(!listBox.selection){ alert("Selecciona un CSV."); return; }
if(!app.documents.length){ alert("Abre un documento primero."); return; }
var doc = app.activeDocument;
if (!doc) {
alert("No hay un documento activo en Illustrator.");
status.text = "❌ No hay un documento activo.";
return;
}
var f = $.global.BatchCSV.files[listBox.selection.index];
try{
f.open("r");
var content = f.read();
f.close();
var rows = parseCSV(content);
var xml = buildXmlFromRows(rows);
var tmp = new File(Folder.desktop + "/APPLY_CSV_AI.xml");
tmp.open("w");
tmp.encoding = "UTF-8";
tmp.write(xml);
tmp.close();
app.executeMenuCommand("deselectall"); // Clave para evitar error
// Limpiar las variables existentes
while(doc.variables.length > 0) doc.variables[0].remove();
doc.importVariables(tmp);
tmp.remove(); // Eliminar archivo temporal
status.text = "✅ Importado: " + f.name;
alert("Importación completa: " + f.name + "\nRevisa el panel Variables.");
} catch(e){
alert("Error aplicando CSV: " + e);
status.text = "❌ Error: " + e;
}
};
btnSave.onClick = function(){
if(!listBox.selection){ alert("Selecciona un CSV."); return; }
var f = $.global.BatchCSV.files[listBox.selection.index];
try{
f.open("r");
var content = f.read();
f.close();
var rows = parseCSV(content);
var xml = buildXmlFromRows(rows);
var saveFile = File.saveDialog("Guardar XML como", "XML:*.xml");
if(saveFile){
saveFile.open("w");
saveFile.encoding = "UTF-8";
saveFile.write(xml);
saveFile.close();
alert("XML guardado: " + saveFile.fsName);
}
} catch(e){ alert("Error guardando XML: " + e); }
};
W.onResizing = W.onResize = function(){ this.layout.resize(); };
W.center(); W.show();
----------------------------------------------------------------
if you change the Window type to "dialog" the script works correctly, right?
windows of type Palette are not as straight forward as Dialogs. Palettes don't have access to Illustrator documents and viceversa. To make the Palette and Illustrator see each other you must send messages via BridgeTalk.
here's one sample of how the system works, let me know if you can apply the same concept to your script and post back if you have questions
Copy link to clipboard
Copied
if you change the Window type to "dialog" the script works correctly, right?
windows of type Palette are not as straight forward as Dialogs. Palettes don't have access to Illustrator documents and viceversa. To make the Palette and Illustrator see each other you must send messages via BridgeTalk.
here's one sample of how the system works, let me know if you can apply the same concept to your script and post back if you have questions
Copy link to clipboard
Copied
It worked just as you said. Thank you so much
Find more inspiration, events, and resources on the new Adobe Community
Explore Now