Unique file name export scripting help
I have searched and have not found the correct answer. I am banging my head with this one.
What I am trying to do is export individual pages as separate jpgs after a data merge. I need each file to have a unique name that is populated using a text frame with a data field labeled "FileName" and a style applied to it called FileName. What is happening is, I get the 3 unique files with the correct data for each. However, when it saves it is only pulling the "FileName" from page 1 for all 3 pages.
FileName.jpg
FileName2.jpg
FileName3.jpg
I need each one to have the unique FileName field for identification and distribution sorting. There will be a little over 5k files that I don't want to hand name. Below is my current script. Any help is greatly appreciated. Thank you.
var doc = app.activeDocument;
// Prompt user to select a folder to save the exported files
var mySelectedFolder = Folder.selectDialog("Select a Folder to Save Files");
if (mySelectedFolder != null) {
var fileName = getTextFromDoc(doc, "FileName"); // Get unique name for the document
if (fileName != null) {
var file = new File(mySelectedFolder + "/" + fileName + "_graphic.jpg");
// Set JPEG export preferences
app.jpegExportPreferences.exportResolution = 300; // Set resolution to 300 DPI
app.jpegExportPreferences.jpegQuality = JPEGOptionsQuality.HIGH; // Set quality to High
app.jpegExportPreferences.pageString = "1-" + doc.pages.length; // Export the whole document
// Export as a single JPEG
doc.exportFile(ExportFormat.JPG, file, false);
alert("Exported: " + fileName + "_graphic.jpg");
} else {
alert("No file name found in document.");
}
alert("Done Exporting Files!");
} else {
alert("No folder selected.");
}
// Function to extract text from the document's text frames
function getTextFromDoc(doc, styleName) {
var textFrames = doc.textFrames;
for (var j = 0; j < textFrames.length; j++) {
var textFrame = textFrames[j];
// Ensure the text frame contains text with the specified style
if (textFrame.paragraphs.length > 0) {
if (textFrame.paragraphs[0].appliedParagraphStyle.name == styleName) {
return textFrame.paragraphs[0].contents.replace(/^\s+|\s+$/g, ''); // Trim spaces
}
}
}
return null; // No matching text found
}
