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

Batch Exporter (Based on alternative layouts) and Script Processor

New Here ,
Jul 16, 2024 Jul 16, 2024

Copy link to clipboard

Copied

Hi Everyone,

 

I've been playing with GPT to make a script that could address a lot of the tedium and time wasting going on when I'm having to save large amounts of material.

It's farily basic but if anyone has somes idea to improve functionality I'm happy to look at it, for now though I didn't want to make it too complicated.

 

Main functions are to:

  • Save PDF's based on a selected PDF Preset (so make that first, obviosuly). 
  • Save JPEGS, 72ppi, RGB. You can change those in the script, but I'm considering adding some options fot that int he interface later on. 
  • Run a selected script. These can be a little iffy if the script your applying has it's own dialogs. Still haven't found a great way to stop issue on that end. 
  • Apply these functions to either the current document, or all documents that are opened (lots of big documents can take a while to process, but better then doing it all manually)
  • Also a checkbox to save and close documents as a clear sign that everyhting is finished. 

 

Note that if you have alternative layouts, the JPEG and PDF exporting is designed to seperate everything into those layouts, making it easy to export lot of varients without ahving to go through the tedium of saving each one thorugh the export interface, or splitting the PDF. JPEGs will go into their own folders to keep things clean. 

 

It it's broken for you let me know, and feel free to make any changes you'd like and to pass it on. I'd appreciate if you'd send me a copy though as I'm always looking to improve it. 

 

#targetengine "session"

// Get the path of the current script file
var scriptFile = File($.fileName);

// Determine the parent folder of the script file
var scriptsFolderPath = scriptFile.parent.fsName;

// Define the log file path based on the script file location
var logFilePath = scriptFile.parent.fsName + "/SupaDupaLog.txt";

// Function to log messages to a file
function writeLog(message) {
    var logFile = new File(logFilePath);
    logFile.open("a");
    logFile.writeln(new Date().toLocaleString() + " - " + message);
    logFile.close();
}

// Function to execute a script on a document
function executeScript(scriptFile, document) {
    try {
        var targetDocument = document || app.activeDocument;
        writeLog("Starting script execution: " + scriptFile.name + " on document: " + targetDocument.name);

        // Execute the script with the target document as the target
        app.activeDocument = targetDocument;
        app.doScript(scriptFile, ScriptLanguage.JAVASCRIPT);

        writeLog("Script execution successful on document: " + targetDocument.name);
        return true;
    } catch (executionError) {
        // Log any errors that occurred during script execution
        writeLog("Error executing script: " + executionError.toString() + " on document: " + targetDocument.name);
        return false;
    }
}

// Function to save and close specific documents
function saveAndCloseDocuments(documents) {
    for (var i = documents.length - 1; i >= 0; i--) {
        var document = documents[i];

        // Save the document
        try {
            if (document.saved) {
                document.save();
            } else {
                document.save(File());
            }
        } catch (saveError) {
            alert("Error saving document: " + document.name + "\nError: " + saveError);
        }

        // Close the document
        try {
            document.close(SaveOptions.YES);
        } catch (closeError) {
            alert("Error closing document: " + document.name + "\nError: " + closeError);
        }
    }

    writeLog("Documents saved and closed.");
}

// Function to export the active document as PDF with preset
function exportAsPDF(document, presetName) {
    var preset = app.pdfExportPresets.itemByName(presetName);

    if (!preset) {
        alert("ERROR: The specified PDF preset '" + presetName + "' does not exist.");
        return;
    }

    var pagesCount = document.pages.length;
    var alternativeLayout = document.sections.everyItem().alternateLayout;
    var filePath = document.fullName.fsName;
    var fileNameWithPath = filePath.replace(/\.indd$/, ""); // remove indesign .indd extension

    // Exporter
    try {
        if (alternativeLayout.length === 1) {
            // No Alt Layout: Export PDF
            var exportPath = new File(fileNameWithPath + ".pdf");
            document.exportFile(ExportFormat.PDF_TYPE, exportPath, false, preset);
        } else {
            // Alt Layout: Export PDF for each alternative layout
            for (var alt = 0; alt < alternativeLayout.length; alt++) {
                app.pdfExportPreferences.pageRange = alternativeLayout[alt];
                var exportPath = new File(fileNameWithPath + "_" + alternativeLayout[alt] + ".pdf");
                document.exportFile(ExportFormat.PDF_TYPE, exportPath, false, preset);
            }
        }
    } catch (e) {
        alert("Error during PDF export: " + e);
    }
}

// Function to export the active document as JPEG
function exportAsJPEG(document) {
    // Check if the document has been saved
    if (!document.saved) {
        var saveFile = File.saveDialog("Save the document before exporting");
        if (saveFile != null) {
            document.save(saveFile);
        } else {
            alert("The document was not saved. Export canceled.");
            return;
        }
    }

    var pagesCount = document.pages.length;
    var alternativeLayout = document.sections.everyItem().alternateLayout;
    var filePath = document.fullName.fsName;
    var fileName = document.name.replace(/\.indd$/i, ""); // remove indesign .indd extension
    var folderPath = document.filePath;

    // Exporter
    try {
        // No Alt Layout: Export JPEG
        if (alternativeLayout.length === 1) {
            var jpegFolderPath = new Folder(folderPath + "/JPEG");
            if (!jpegFolderPath.exists) {
                jpegFolderPath.create();
            }
            var jpegExportPath = new File(jpegFolderPath.fsName + "/" + fileName + ".jpg");

            with (app.jpegExportPreferences) {
                exportResolution = 72;
                jpegColorSpace = JpegColorSpaceEnum.RGB;
            }

            document.exportFile(ExportFormat.JPG, jpegExportPath);
        } else {
            // Alt Layout: Export JPEG for each alternative layout
            for (var alt = 0; alt < alternativeLayout.length; alt++) {
                var jpegFolderPath = new Folder(folderPath + "/" + fileName + "_JPEG" + "/" + alternativeLayout[alt]);
                if (!jpegFolderPath.exists) {
                    jpegFolderPath.create();
                }
                var jpegExportPath = new File(jpegFolderPath.fsName + "/" + fileName + "_" + alternativeLayout[alt] + ".jpg");

                with (app.jpegExportPreferences) {
                    exportResolution = 72;
                    jpegColorSpace = JpegColorSpaceEnum.RGB;
                    pageString = alternativeLayout[alt]; // Page(s) to export, must be a string
                }

                document.exportFile(ExportFormat.JPG, jpegExportPath);
            }
        }
    } catch (e) {
        alert("Error during JPEG export: " + e);
    }
}

// Function to create and display the palette
function createSupaDupaPalette() {
    var palette = new Window("palette", "Script Runner");
    palette.orientation = "column";
    palette.alignChildren = "fill";

    var actionGroup = palette.add("group");
    actionGroup.orientation = "column";
    actionGroup.alignChildren = "fill";

    var documentOptionsGroup = actionGroup.add("group");
    documentOptionsGroup.orientation = "row";
    var currentDocumentRadio = documentOptionsGroup.add("radiobutton", undefined, "Current Document");
    var allDocumentsRadio = documentOptionsGroup.add("radiobutton", undefined, "All Open Documents");
    currentDocumentRadio.value = true; // Default to current document

    var exportJPEGCheckbox = actionGroup.add("checkbox", undefined, "Export JPEG");

    var exportPDFCheckbox = actionGroup.add("checkbox", undefined, "Export PDF");
    var pdfPresetPanel = actionGroup.add("panel");
    pdfPresetPanel.visible = false; // Initially hidden

    var pdfPresetGroup = pdfPresetPanel.add("group");
    var pdfPresetLabel = pdfPresetGroup.add("statictext", undefined, "PDF Preset:");
    var pdfPresetDropdown = pdfPresetGroup.add("dropdownlist");
    pdfPresetDropdown.size = [200, 25];

    var customScriptCheckbox = actionGroup.add("checkbox", undefined, "Custom Script");

    var scriptListPanel = actionGroup.add("panel");
    scriptListPanel.alignment = "fill";
    scriptListPanel.visible = false; // Initially hidden

    var scriptDropdown = scriptListPanel.add("dropdownlist");
    scriptDropdown.size = [300, 25]; // Set size of the dropdownlist

    var saveAndCloseCheckbox = actionGroup.add("checkbox", undefined, "Save and Close Documents After Actions");

    var runButton = palette.add("button", undefined, "Run Selected Actions");
    var closeButton = palette.add("button", undefined, "Close");

    // Populate PDF presets dropdown
    function populatePDFPresets() {
        var pdfPresets = app.pdfExportPresets.everyItem().name;
        for (var i = 0; i < pdfPresets.length; i++) {
            pdfPresetDropdown.add("item", pdfPresets[i]);
        }
        pdfPresetDropdown.selection = 0; // Default selection
    }

    // Function to populate the script dropdown
    function populateScriptDropdown() {
        var scriptsFolder = new Folder(scriptsFolderPath);
        var scriptFiles = scriptsFolder.getFiles("*.jsx");
    
        if (scriptFiles.length === 0) {
            writeLog("No .jsx files found in the Scripts Panel folder.");
            alert("No .jsx files found in the Scripts Panel folder.");
            palette.close();
            return;
        }
    
        // Clear existing items
        scriptDropdown.removeAll();
    
        // Get current script file path
        var currentScriptPath = File($.fileName).fsName;
    
        // Populate dropdown excluding the current script
        for (var i = 0; i < scriptFiles.length; i++) {
            var scriptFilePath = scriptFiles[i].fsName;
            if (scriptFilePath !== currentScriptPath) {
                scriptDropdown.add("item", scriptFiles[i].name);
            }
        }
    }
    

    // Function to handle Custom Script checkbox change
    customScriptCheckbox.onClick = function () {
        scriptListPanel.visible = customScriptCheckbox.value;

        // Populate script dropdown only when the panel becomes visible
        if (scriptListPanel.visible) {
            populateScriptDropdown();
        } else {
            // Clear the script dropdown when panel is hidden
            scriptDropdown.removeAll();
        }
    };

    // Function to handle PDF Export checkbox change
    exportPDFCheckbox.onClick = function () {
        pdfPresetPanel.visible = exportPDFCheckbox.value;

        // Populate PDF presets dropdown only when the panel becomes visible
        if (pdfPresetPanel.visible) {
            populatePDFPresets();
        } else {
            // Clear the PDF presets dropdown when panel is hidden
            pdfPresetDropdown.removeAll();
        }
    };

    // Function to handle the Run Selected Actions button click
    runButton.onClick = function () {
        var selectedPDFPreset = pdfPresetDropdown.selection.index >= 0 ? pdfPresetDropdown.selection.text : null;

        // Determine which documents to target
        var targetDocuments = [];
        if (currentDocumentRadio.value) {
            if (app.activeDocument) {
                targetDocuments.push(app.activeDocument);
            } else {
                writeLog("No active document found.");
                alert("No active document found to apply the actions.");
                return;
            }
        } else if (allDocumentsRadio.value) {
            if (app.documents.length > 0) {
                targetDocuments = app.documents;
            } else {
                writeLog("No open documents found.");
                alert("No open documents to apply the actions.");
                return;
            }
        }

        // Apply actions based on checkboxes
        for (var i = 0; i < targetDocuments.length; i++) {
            var document = targetDocuments[i];
            if (exportPDFCheckbox.value && selectedPDFPreset) {
                exportAsPDF(document, selectedPDFPreset);
            }
            if (exportJPEGCheckbox.value) {
                exportAsJPEG(document);
            }
            if (customScriptCheckbox.value) {
                var selectedIndex = scriptDropdown.selection.index;
                if (selectedIndex !== -1) {
                    var selectedScriptName = scriptDropdown.items[selectedIndex].text;
                    var selectedScriptFile = new File(scriptsFolderPath + "/" + selectedScriptName);
                    executeScript(selectedScriptFile, document);
                }
            }
        }

        // Close the documents that were actively processed
        if (saveAndCloseCheckbox.value) {
            saveAndCloseDocuments(targetDocuments);
        }

        // Close the palette
        palette.close();
    };

    // Function to handle the Close button click
    closeButton.onClick = function () {
        palette.close();
    };

    // Populate the PDF presets dropdown initially (if the panel is visible by default)
    if (exportPDFCheckbox.value) {
        populatePDFPresets();
    }

    // Populate the script dropdown initially (if the panel is visible by default)
    if (customScriptCheckbox.value) {
        populateScriptDropdown();
    }

    // Show the palette
    palette.show();
}

// Call the main function to create and display the palette
createSupaDupaPalette();

 

Love to hear some feedback!

 

Cheers, 

Rob

TOPICS
Import and export , Scripting

Views

144

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 ,
Jul 16, 2024 Jul 16, 2024

Copy link to clipboard

Copied

You're re-inventing the wheel: this one does all you mention you want to do:

https://creativepro.com/files/kahrel/indesign/batch_convert.html

 

P.

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
New Here ,
Jul 17, 2024 Jul 17, 2024

Copy link to clipboard

Copied

Hi Peter,  Thanks for the message. 

 

I did use this script previously but was unable to find a way for it to export everything into seperate folders/files based on the documents alternative layouts without loading another export script into it. I might have another look at it, but I found I had to load in my own small export scripts to get it to handle the PDF and JPEG exporting how I needed it. 

 

Rob

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 ,
Jul 17, 2024 Jul 17, 2024

Copy link to clipboard

Copied

LATEST

True, my script doesn't deal with alternate layouts.

 

 

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