Indesign Script to alter page on data merge
Hello,
I'm looking for ways to increase the utility of data merge on indesign, and the project I've come up with is I'd like to set a different background color on each page of a merged document (lets say around 200 pages, all unique colors, kind of like a swatch booklet).
I have a spreadsheet and each row has a color column (hex or rgb, whatever works best).
I've been having chatgpt help me write some code, which it seems to have given a decent starting point, but of course comes up with errors. Those don't scare me, but I am having the hardest time finding any documentation to give insight on how to come up with a solution.
Couple of questions
- Is what I'm doing possible? (editing page of document as it's being merged, so at the end of the day each page has a different color, end of story).
- Where are the best resources/documentation for indesign scripts on data merges?
I'll post the chatgpt code for reference, but it doesn't work (error 55: object does not support the property or method 'dataMergeRecords'
// ChangeBackgroundColor.jsx
// Main function
function changeBackgroundColors() {
var doc = app.activeDocument;
var dataMerge = doc.dataMergeProperties;
var dataMergeRecords = dataMerge.dataMergeRecords;
// Ensure the data merge is enabled
if (!dataMerge.dataMergePreferences.dataSource) {
alert("No data merge file found. Please import a data merge file first.");
return;
}
// Loop through each data merge record
for (var i = 0; i < dataMergeRecords.length; i++) {
var record = dataMergeRecords[i];
// Get the value of the background color field from the data merge
var colorValue = record.getField("BackgroundColor");
// Convert color value to RGB/CMYK
var color = convertToColor(colorValue);
// Create a new rectangle for the background
var page = doc.pages[i];
var backgroundRect = page.rectangles.add({
geometricBounds: [0, 0, doc.documentPreferences.pageHeight, doc.documentPreferences.pageWidth],
fillColor: color
});
// Send the rectangle to the back
backgroundRect.sendToBack();
}
}
// Function to convert color value to RGB/CMYK Color
function convertToColor(value) {
// Assuming value is in hex format for this example
var color = app.activeDocument.colors.itemByName(value);
if (!color.isValid) {
// Create new color if it doesn't exist
color = app.activeDocument.colors.add();
color.name = value;
color.space = ColorSpace.RGB;
color.colorValue = hexToRgb(value);
}
return color;
}
// Function to convert hex color to RGB array
function hexToRgb(hex) {
var bigint = parseInt(hex.replace('#', ''), 16);
var r = (bigint >> 16) & 255;
var g = (bigint >> 😎 & 255;
var b = bigint & 255;
return [r, g, b];
}
// Run the main function
changeBackgroundColors();
