script to place 1pt key lines inside a document at specified positions
- June 20, 2024
- 2 replies
- 514 views
I'm trying to make a script that will insert a 1pt thick keyline at a user specified distance form the outside of all corners of the artboard, either 1" or 2 " long. I've been trying using chatgpt but it just can't get the keyline inside the artboard. I tried using just one keyline, but would need it on all 4 corners of the document, as per the attached simplified proof. I don't know if it would make any difference or not, but some of these documents will be using the larger artboard (ofetn theyre around 600" w x 100" h)
The last code before I got too frustrated is:
// Function to convert inches to Illustrator points (72 points per inch)
function inchesToPoints(inches) {
return inches * 72;
}
// Function to create a 1pt black keyline inside the visible area of the artboard
function createKeyline(positionInInches, heightInInches) {
var doc = app.activeDocument;
var activeArtboard = doc.artboards[doc.artboards.getActiveArtboardIndex()];
var artboardRect = activeArtboard.artboardRect; // Artboard bounds
// Convert position and height to points
var positionInPoints = inchesToPoints(positionInInches);
var heightInPoints = inchesToPoints(heightInInches);
// Calculate positions for the keyline
var xPosition = artboardRect[0] + positionInPoints; // X position for the vertical line
var topPosition = artboardRect[1] + 1; // Top position inside artboard
var bottomPosition = topPosition + heightInPoints; // Bottom position
// Ensure the xPosition stays within the artboard bounds
if (xPosition < artboardRect[0]) {
xPosition = artboardRect[0];
} else if (xPosition > artboardRect[2]) {
xPosition = artboardRect[2];
}
// Create a new path item for the keyline
var keylinePath = doc.pathItems.add();
keylinePath.setEntirePath([
[xPosition, topPosition],
[xPosition, bottomPosition]
]);
// Style the keyline (black stroke, 1pt width)
keylinePath.stroked = true;
keylinePath.strokeWidth = 1; // 1pt stroke width
keylinePath.strokeColor = doc.swatches.getByName("Black").color;
}
// Prompt user for position and height
function promptForKeylineDetails() {
var position = parseFloat(prompt("Enter position in inches from left or right:", "1.0"));
var height = parseFloat(prompt("Enter height of the keyline in inches (1 or 2):", "1.0"));
// Check if valid input
if (!isNaN(position) && !isNaN(height) && (height === 1 || height === 2)) {
createKeyline(position, height);
} else {
alert("Invalid input. Please enter valid numbers (position in inches and height as 1 or 2 inches).");
}
}
// Run the script
promptForKeylineDetails();
