skip to Main Content

First of all, I would like to say that I have no idea about programming; I have simply been developing a script for InDesign using AI, and I have reached a point where I cannot continue. What I am looking for is for the script to go through the entire document to return an Excel file where the codes of the articles are located, as well as the page number where they are found. The problem is that in the resulting CSV file, the page number behaves correctly in documents with fewer than 10 pages, enumerating correctly. However, starting from page 10, it simply writes 1 for the pages from 10 to 19 and 2 for those from 20 to 29, and so on.

var now = new Date();
var hours = ("0" + now.getHours()).slice(-2); // Formato HH
var minutes = ("0" + now.getMinutes()).slice(-2); // Formato MM
var day = ("0" + now.getDate()).slice(-2); // Formato DD
var month = ("0" + (now.getMonth() + 1)).slice(-2); // Formato MM (mes)

// Crear el nombre del archivo CSV con la fecha y hora
var fileName = hours + minutes + "_" + day + month + ".csv";
var file = new File("~/Documentos/" + fileName);

try {
    file.open("w"); // Abrir el archivo en modo escritura
    file.writeln("Código,Página"); // Escribir el encabezado con la nueva columna

    // Comprobación de que hay un documento abierto
    if (app.documents.length > 0) {
        var doc = app.activeDocument;
        var totalCodigos = 0; // Variable para contar los códigos encontrados

        // Función para procesar elementos de texto
        function processTextFrames(textFrames, pageNumber) {
            for (var j = 0; j < textFrames.length; j++) {
                var textFrame = textFrames[j];

                // Recorrer todas las tablas en el marco de texto
                for (var k = 0; k < textFrame.tables.length; k++) {
                    var table = textFrame.tables[k];

                    // Acceder a la primera columna
                    var firstColumnCells = table.columns[0].cells;

                    // Recorrer cada celda en la primera columna
                    for (var l = 0; l < firstColumnCells.length; l++) {
                        var cellContent = firstColumnCells[l].contents;

                        // Buscar secuencias de 8 dígitos
                        var matches = cellContent.match(/bd{8}b/g);

                        if (matches) {
                            totalCodigos += matches.length; // Contar los códigos encontrados

                            for (var m = 0; m < matches.length; m++) {
                                // Escribir el código y el número de página en columnas separadas
                                file.writeln(matches[m] + "," + pageNumber);
                            }
                        }
                    }
                }

                // Buscar códigos en cajas de texto
                var textContent = textFrame.contents;
                var codigoMatches = textContent.match(/Cód:s*(d{8})/g);

                if (codigoMatches) {
                    totalCodigos += codigoMatches.length; // Contar los códigos encontrados

                    for (var n = 0; n < codigoMatches.length; n++) {
                        var codigo = codigoMatches[n].match(/d{8}/)[0]; // Extraer solo el código
                        // Escribir el código y el número de página en columnas separadas
                        file.writeln(codigo + "," + pageNumber);
                    }
                }
            }
        }

        // Función recursiva para procesar grupos
        function processGroups(groups, pageNumber) {
            for (var g = 0; g < groups.length; g++) {
                var group = groups[g];
                processTextFrames(group.textFrames, pageNumber); // Procesar marcos de texto dentro del grupo
                processGroups(group.groups, pageNumber); // Llamar a la función recursiva para grupos anidados
            }
        }

        // Recorrer todas las páginas del documento
        for (var i = 0; i < doc.pages.length; i++) {
            var page = doc.pages[i];

            // Procesar los marcos de texto en la página
            processTextFrames(page.textFrames, page.name);

            // Procesar grupos en la página
            processGroups(page.groups, page.name); // Procesar grupos en la página
        }

        // Mensaje final de confirmación
        if (totalCodigos > 0) {
            alert("Os códigos dos artigos foron exportados correctamente a " + file.fullName + ". Total de códigos: " + totalCodigos);
        } else {
            alert("Non se atoparon códigos de 8 díxitos no documento.");
        }
    } else {
        alert("Non hai documentos abertos en InDesign.");
    }
} catch (e) {
    alert("Ocurriu un erro: " + e.message);
} finally {
    file.close(); // Cerrar el archivo CSV
}

2

Answers


  1. Chosen as BEST ANSWER

    Thank you all for the help and collaboration. In the end, I managed to solve the problem in the following way: I created a pageMap mapping. Then, instead of using page.name or documentOffset, the script directly accesses pageMap[i] to get the corresponding page number. I want to repeat that I have no programming knowledge; everything was solved using artificial intelligence since this code is for personal use. If I had needed it, I would have contacted a professional. Best regards, and once again, thank you very much.


  2. The code looks fine. I’d try to change the variable page.name with the counter i+1. It could be enough if your documents have the simply numeration of the pages (1, 2, 3, etc).

    Instead of this:

    processTextFrames(page.textFrames, page.name);
    processGroups(page.groups, page.name);
    

    You can try this:

    processTextFrames(page.textFrames, i+1);
    processGroups(page.groups, i+1);
    

    Just in case, as far as I can see you probably don’t even need to loop through all the text frames on every page. You can get all the matches with just one step and loop through the matches and get page numbers from every match. Something like this:

    var now      = new Date();
    var hours    = ("0" + now.getHours()).slice(-2);
    var minutes  = ("0" + now.getMinutes()).slice(-2);
    var day      = ("0" + now.getDate()).slice(-2);
    var month    = ("0" + (now.getMonth() + 1)).slice(-2);
    var fileName = hours + minutes + "_" + day + month + ".csv";
    var file     = new File("~/Documentos/" + fileName);
    file.open("w");
    file.writeln("Código,Página");
    
    // get all the matches whitin active document
    app.findGrepPreferences = NothingEnum.NOTHING;
    app.findGrepPreferences.findWhat = "(?i)Cód:\s*\d{8}"; // GREP = /Cód:s*d{8}/g
    var matches = app.activeDocument.findGrep();
    
    // loop trough the matches
    var codigo, pageName;
    for (var i=0; i<matches.length; i++) {
        codigo = matches[i].contents.slice(-8);    // last 8 letters
        pageName = matches[i].parentTextFrames[0].parentPage.name; // page number
        // file.writeln(codigo + "," + pageName);  // <-- the proper way
        file.writeln(codigo + "," + (i+1));        // <-- for the simply numeration 1,2,3...
    }
    
    file.close();
    file.execute(); // open the CSV file
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search