Skip to main content
Participating Frequently
November 7, 2023
Question

Indesign Script JSX DataMerge ExtendScript

  • November 7, 2023
  • 3 replies
  • 984 views

I have 20 records.

 

I have these functions:
exportJPEGs();

exportPDFSpreads();

exportPDFInterior();

I want to iterate through every record while in preview. Then do these exports
There is not such thing as

        for (var i = 0; i <= 10; i++) {
            myDocument.dataMergeProperties.currentRecord = i;

            exportJPEGs();

            exportPDFSpreads();

            exportPDFInterior();

Or is there a currentRecord something

3 replies

Colin Flashman
Community Expert
Community Expert
November 8, 2023

I have a paid script on my colecandoo.com website that data merges to single records in several image formats:

 Would this be of use?

If the answer wasn't in my post, perhaps it might be on my blog at colecandoo!
m1b
Community Expert
Community Expert
November 8, 2023

Hi @t634hreww4tyu34f, I had the same idea as Robert. Have a look at this script and see if it makes sense. There are some odd things going on with datamerge, for example, we don't have very good access to the data source so instead of knowing how many records, I just keep going until it throws an error(!). Nothing is tested much, so use with caution!

 

Anyway, see if this helps.

- Mark

 

/**
 * Example of one approach to scripting data merge:
 *   - create new document for each record
 *   - function to return those documents in array
 *   - save or export or do what you want with them
 * @author m1b
 * @discussion https://community.adobe.com/t5/indesign-discussions/indesign-script-jsx-datamerge-extendscript/m-p/14218707
 */
function main() {

    var doc = app.documents.itemByName('datamerge test.indd');

    if (!doc.isValid) {
        alert('Document not found.');
        return;
    }

    // this will give us new, unsaved documents:
    var mergeDocs = getMergedDocs(doc, outputFolder);

    // just to show what we did:
    alert('We made ' + mergeDocs.length + ' merge documents.');

    if (mergeDocs.length == 0)
        return;

    // example of what to do with merged documents
    var outputFolder = Folder(doc.fullName.parent + '/Merged');

    if (!outputFolder.exists)
        outputFolder.create();

    for (var i = mergeDocs.length - 1, j = 0; i >= 0; i--, j++) {

        // save (NOTE: MAY OVERWRITE EXISTING)
        mergeDocs[i].save(File(outputFolder + '/' + doc.name.replace(/\.[^\.]+$/, '-' + (j + 1) + '.indd')));

        // *** PUT YOUR CODE HERE? ***

        // close
        mergeDocs[i].close();

    }

};

app.doScript(main, ScriptLanguage.JAVASCRIPT, undefined, UndoModes.ENTIRE_SCRIPT, 'Export Merge Documents');


/**
 * Given a document with datamerge set up,
 * returns array of merged documents.
 * @author m1b
 * @version 2023-11-08
 * @param {Document} doc - an Illustrator document with the data merge.
 * @param {Folder} [outputFolder] - folder to save merged docs in (default: undefined, do not save).
 * @returns {Array<Document>} - the merge documents.
 */
function getMergedDocs(doc, outputFolder) {

    // we need to know what docs are
    // here *before* the merging
    var docIDs = app.documents.everyItem().id;

    // datamerge objects
    var dm = doc.dataMergeProperties,
        dmo = doc.dataMergeOptions,
        dmp = dm.dataMergePreferences;

    if (dm.dataMergeFields.length == 0) {
        alert('No data merge fields.');
        return [];
    }

    dmo.createNewDocument = true;
    dmp.recordSelection = RecordSelection.ONE_RECORD;

    // loop over each record in data source
    var index = 1,
        keepGoingUntilError = true;

    try {

        while (keepGoingUntilError) {

            dmp.recordNumber = index++;

            // do the merge
            dm.mergeRecords();

        }

    } catch (error) { }

    // collect the merged documents
    var mergeDocs = app.documents.everyItem().getElements();

    // minus the existing documents
    for (var i = 0, len = mergeDocs.length; i < len; i++) {
        if (indexOf(mergeDocs[0].id, docIDs) === -1)
            mergeDocs.push(mergeDocs.shift());
        else
            mergeDocs.shift();
    }

    return mergeDocs;

};


/**
 * Returns index of obj in arr.
 * Returns -1 if not found.
 * @param {any} obj
 * @param {Array} arr
 * @returns {Number}
 */
function indexOf(obj, arr) {
    for (var i = 0; i < arr.length; i++)
        if (arr[i] === obj)
            return i;
    return -1;
};

 

Participating Frequently
November 8, 2023

I am trying to figure out a way to shift through the new files to do the functions
Somehow it stuck saying 



function exportJPEGs(doc, exportFolder) {
    var jpegPages = [2, 4];
    for (var i = 0; i < jpegPages.length; i++) {
        var pageIndex = jpegPages[i] - 1; // Zero-based index for pages
        var page = doc.pages.item(pageIndex);
        app.jpegExportPreferences.pageString = page.name;
        app.jpegExportPreferences.exportResolution = 300;
        app.jpegExportPreferences.jpegQuality = JPEGOptionsQuality.MAXIMUM;
        var fileName = getCustomFileName(doc, pageIndex);
        var exportFile = new File(exportFolder + "/" + fileName + ".jpg");
        doc.exportFile(ExportFormat.JPG, exportFile);
    }
}

// ....


function main() {

    var doc = app.documents.itemByName('layout.indd');

    if (!doc.isValid) {
        alert('Document not found.');
        return;
    }

    // this will give us new, unsaved documents:
    var mergeDocs = getMergedDocs(doc, outputFolder);

    // just to show what we did:
    alert('We made ' + mergeDocs.length + ' merge documents.');

    if (mergeDocs.length == 0)
        return;

    // example of what to do with merged documents
    var outputFolder = Folder(doc.fullName.parent + '/Merged');

    if (!outputFolder.exists)
        outputFolder.create();

        for (var i = mergeDocs.length - 1, j = 0; i >= 0; i--, j++) {

            // Define the new file name
            var newFileName = doc.name.replace(/\.[^\.]+$/, '-' + (j + 1) + '.indd');
            var newFile = File(outputFolder + '/' + newFileName);
        
            // Save the merged document with the new name
            mergeDocs[i].save(newFile);
        
            exportJPEGs(mergeDocs[i], exportFolder);
            exportPDFSpreads(mergeDocs[i], exportFolder);
            exportPDFInterior(mergeDocs[i], exportFolder);
        
            // Close the merged document without saving changes (as they are already saved)
            mergeDocs[i].close();
        }

};

 

m1b
Community Expert
Community Expert
November 8, 2023

You aren't seeing the correct error line because I was running it through app.doScript. Comment out the app.doscript line and just call main();

And then you can troubleshoot more easily. The app.doscript is good because it handles a single undo action, but you can turn it off until your finished troubleshooting.

- Mark

Robert at ID-Tasker
Legend
November 7, 2023

Generate document - as separate pages - do your thing on those pages.