So I've been working with my good friend ChatGpt to write some script for illustrator to streamline a very small part of my workflow on a specific project and in trying to get the artboard bounds/width I'm getting rounded numbers instead of the accurate decimals. I'm creating renders of walls using a ratio of 1 inch : 10 pixels because accuracy is very important. The purpose of this script is to "print" (create and place text) the width in inches of the active artboard. For example, if an artboard is 1032 pixels wide it's converted to inches by dividing by 10 and it should create text that says ' 103.2" '. The issue is that the value assigned to the artboardWidth variable is rounded and inaccurate, instead of 1032 being the pixel count of the artboard bounds, 1030 is returned. Here's the script:
//@target illustrator
preferences.setBooleanPreference('ShowExternalJSXWarning', false); // Fix drag and drop a .jsx file
function main() {
var doc = app.activeDocument;
var abIdx = doc.artboards.getActiveArtboardIndex();
var abBnds = doc.artboards[abIdx].artboardRect;
var artboardWidth = parseFloat((abBnds[2] - abBnds[0]).toFixed(4));
var textWidth = artboardWidth / 10;
// Debug: Log the raw textWidth value
$.writeln("Raw artboardWidth value: " + artboardWidth);
// Debug: Log the raw textWidth value
$.writeln("Raw textWidth value: " + textWidth);
// Convert textWidth to a string with 4 decimal places
var textWidthStr = textWidth.toFixed(4);
// Debug: Log the formatted textWidthStr value
$.writeln("Formatted textWidthStr value: " + textWidthStr);
// Add quotation mark to the end of the text
textWidthStr += '"';
// Create a new text frame
var textFrame = doc.textFrames.add();
textFrame.contents = textWidthStr;
// Set text properties
try {
var textRange = textFrame.textRange;
// Set text color
var cmykColor = new CMYKColor();
cmykColor.cyan = 90;
cmykColor.magenta = 30;
cmykColor.yellow = 95;
cmykColor.black = 30;
textRange.characterAttributes.fillColor = cmykColor;
textRange.characterAttributes.size = 80; // font size in points
// Center text horizontally and position it vertically
var abCenterX = (abBnds[2] + abBnds[0]) / 2;
var textFrameBounds = textFrame.geometricBounds;
var textWidthPixels = textFrameBounds[2] - textFrameBounds[0];
textFrame.left = abCenterX - (textWidthPixels / 2);
textFrame.top = abBnds[1] - 25; // Position 25 pixels from the top of the artboard
} catch (e) {
alert("Error: " + e.message);
}
}
try {
main();
} catch (e) {
alert("Error: " + e.message);
}