Skip to main content
Participant
April 10, 2024
Question

Suffix as Datamerge field

  • April 10, 2024
  • 1 reply
  • 332 views

So im having a file of 345 different products.
Every product has its own "Vare nr" (product no.)  

 

Can I add the field "Vare nr" as the Suffix, somehow, when exporting the seperate pages, instead of renaming 345 files afterwards?

 

This topic has been closed for replies.

1 reply

m1b
Community Expert
Community Expert
April 12, 2024

Hi @KennethMM, I've written a script to help here. It uses the concept of a "filename template" to generate the pdf filenames which it populates from textFrames in the merged document. See how my attached demo documents are set up, especially demo-datamerge.indd. You can see that I made two text frames that don't print and are outside the page edge at the top (but they must overlap with the page or they won't be included in the datamerge).

 

By default, the script will export to a "PDF" folder in the same folder as the Indesign document.

 

In the script you will need to edit these two lines to match how you want the filename, and which pdf preset you want:

 

var fileNameTemplate = 'demo export {PAGENAME}-{BRAND}-{COLOR}.pdf',
    pdfPresetName = '[Press Quality]';

 

For example. your `fileNameTemplate` might be:

 

var fileNameTemplate = '{DOCNAME}_{NR}.pdf';

 

where you have a text frame on each page with contents of the <<nr>> datamerge variable. 

 

Here is the script. Let me know if it helps. Don't forget to look at the demo files attached below.

- Mark

 

/**
 * Export every page of document as pdf, using filename template
 * populated by variables gathered from each page.
 * @author m1b
 * @discussion https://community.adobe.com/t5/indesign-discussions/suffix-as-datamerge-field/m-p/14546645/thread-id/569711
 */
function main() {

    var fileNameTemplate = '{DOCNAME}--page {PAGENAME}-{BRAND}-{COLOR}.pdf',
        pdfPresetName = '[Press Quality]';

    if (0 === app.documents)
        return alert('Please open a document and try again.');

    var doc = app.activeDocument;

    if (!doc.saved)
        return alert('Please save document and try again.');

    // destination is 'PDF' folder in same folder as document
    var destinationFolder = Folder(doc.filePath + '/PDF');

    // create the destination folder, if missing
    if (!destinationFolder.exists)
        destinationFolder.create();

    if (!destinationFolder.exists)
        return alert('Did not create the destination folder "' + destinationFolder + '".');

    // export each page as pdf
    var result = exportEachPageAsPDF(doc, destinationFolder, pdfPresetName, fileNameTemplate);

    if (result)
        alert('Errors:\n' + result.join('\n'));
    else
        alert('Export success.');

    // reveal the destination folder
    destinationFolder.execute();

};

app.doScript(main, ScriptLanguage.JAVASCRIPT, undefined, UndoModes.ENTIRE_SCRIPT, 'Export Each Page As PDF');

/**
 * Export every page of `doc` as pdf to `folder`
 * using pdf preset `pdfExportPresetName` and
 * filename derived from `fileNameTemplate`.
 *
 * The file name template string can contain
 * tokens:
 *   {PAGENAME} = the page name, eg. "1", "2", etc.
 *   {*} = matches a text frame on the page
 *      named "*", where * is a name you choose.
 *
 * Example fileNameTemplate:
 *   "demo export {PAGENAME}-{BRAND}-{COLOR}.pdf"
 *
 * @author m1b
 * @version 2024-04-12
 * @param {Document} doc - an Indesign Document.
 * @param {Folder} folder - the destination folder.
 * @param {String} pdfExportPresetName - the pdf export preset name, eg. "[Press Quality].
 * @param {String} fileNameTemplate - the filename template string, eg. "My doc page {PAGENAME}".
 * @returns {?Array<String>} - any error messages.
 */
function exportEachPageAsPDF(doc, folder, pdfExportPresetName, fileNameTemplate) {

    var pdfExportPreset = app.pdfExportPresets.itemByName(pdfExportPresetName);

    if (!pdfExportPreset.isValid)
        return alert('Error\nPDF preset ' + pdfExportPresetName + ' was invalid.');

    var pageNames = doc.pages.everyItem().name,
        matchVarNames = /\{([^\}]+)\}/g,
        messages = [];

    for (var i = 0, f, filename, textFrame, len = pageNames.length; i < len; i++) {

        filename = fileNameTemplate;

        // get variable names from file name template
        var varNames = fileNameTemplate.match(matchVarNames) || [];

        varsLoop:
        for (var v = 0; v < varNames.length; v++) {

            // get text frame named for this var
            textFrame = doc.pages.itemByName(pageNames[i])
                .textFrames.itemByName(varNames[v].slice(1, -1));

            if (textFrame.isValid)
                // replace with contents of text frame
                filename = filename.replace(varNames[v], textFrame.contents);

            else if ('{PAGENAME}' === varNames[v])
                // replace with page name
                filename = filename.replace(varNames[v], pageNames[i]);

            else if ('{DOCNAME}' === varNames[v])
                // replace with doc name without extension
                filename = filename.replace(varNames[v], doc.name.replace(/\.[^\.]+$/, ''));

        }

        f = File(folder + '/' + filename);

        app.pdfExportPreferences.pageRange = pageNames[i];

        try {

            // export
            doc.exportFile(
                ExportFormat.PDF_TYPE,
                f,
                false,
                pdfExportPreset
            );

            if (!f.exists)
                messages.push('Did not save "' + decodeURI(f) + '".');

        } catch (error) {
            messages.push('Error saving "' + decodeURI(f) + '". (' + error.message + ')');
        }

    }

    if (messages.length > 0)
        return messages;

};

 

KennethMMAuthor
Participant
April 12, 2024

Wow, gotta go through that and try. Thanks man!