Repositioning text in a document
Any ideas why this script isn't working as desired? I'm trying to write a simple script that moves any text boxes / objects (grouping them first if there's multiple) to an exact x and y position on the page.
So if the current position of the text box is .5 inches and 1.5 inches, and I want to just move all of the text boxes down and inch so its new position is .5 inches and 2.5 inches, why is this moving the text box to a weird position when I type in .5 and 2.5 into the dialog box?
// @targetengine "session"
function repositionTextFrames() {
// Check if there's an active document
if (app.documents.length === 0) {
alert("Please open a document first.");
return;
}
var myDoc = app.activeDocument;
// Create dialog box
var myDialog = new Window("dialog", "Reposition Text Frames");
myDialog.orientation = "column";
// Create input groups
var coordGroup = myDialog.add("group");
coordGroup.orientation = "row";
// X coordinate input
coordGroup.add("statictext", undefined, "X Position (inches):");
var xInput = coordGroup.add("edittext", undefined, "0");
xInput.characters = 6;
// Y coordinate input
coordGroup.add("statictext", undefined, "Y Position (inches):");
var yInput = coordGroup.add("edittext", undefined, "0");
yInput.characters = 6;
// Add buttons
var buttonGroup = myDialog.add("group");
buttonGroup.orientation = "row";
var okButton = buttonGroup.add("button", undefined, "OK");
var cancelButton = buttonGroup.add("button", undefined, "Cancel");
// Show dialog
if (myDialog.show() == 1) {
// Convert inches to points (1 inch = 72 points)
var xPos = parseFloat(xInput.text) * 72;
var yPos = parseFloat(yInput.text) * 72;
// Process each page
for (var i = 0; i < myDoc.pages.length; i++) {
var currentPage = myDoc.pages[i];
var textFrames = [];
// Collect all text frames on the page
for (var j = 0; j < currentPage.textFrames.length; j++) {
textFrames.push(currentPage.textFrames[j]);
}
// Skip if no text frames found
if (textFrames.length === 0) continue;
// Group text frames if multiple exist
var textGroup;
if (textFrames.length > 1) {
textGroup = currentPage.groups.add(textFrames);
} else {
textGroup = textFrames[0];
}
try {
// Get the current position of the text group
var bounds = textGroup.geometricBounds;
// Calculate the target position relative to the page margins
var targetX = currentPage.marginPreferences.left + xPos;
var targetY = currentPage.marginPreferences.top + yPos;
// Calculate the amount we need to move the text group
var deltaX = targetX - bounds[1];
var deltaY = targetY - bounds[0];
// Move the text group
textGroup.move(undefined, [deltaX, deltaY]);
} catch (e) {
alert("Error repositioning text on page " + (i + 1) + ": " + e);
}
}
alert("Text repositioning complete!");
}
}
// Run the script
repositionTextFrames();