I'm new to AI and scripting. I have a template I'm starting with. Inside this template, there is a TextFrame (called CITIES_1). Inside here is template text like:
CITY 1 123 Address Rd. MyCity, MyState MyZip
CITY 2 567 Address Rd. MyCity2, MyState2 MyZip2
The CITY 1 header is Helvetica Neue LT Std / 75 Bold The rest of the info is Helvetica Neue LT Std / 55 Roman
I'm trying to dynamically change this content to city information I have in a file.
I've tried changing the TextFrame.contents but it uses the first font family/style for the whole thing. Any idea on how to change the data while keeping the same "formatting"?
TIA!
var helBold = app.textFonts.getByName("HelveticaNeueLTStd-Bd");
var helRoman = app.textFonts.getByName("HelveticaNeueLTStd-Roman");
var bold = myDoc.characterStyles.add({ name: "HelveticaNeueLTStd-Roman" });
var roman = myDoc.characterStyles.add({ name: "HelveticaNeueLTStd-Roman" });
var currTF = templateLayer.textFrames.getByName("CITIES_1");
currTF.contents = "MYCITY\r123 MyAddress Dr.\rMyCity, ST 12345\r555.555.5555\r";
bold.applyTo(currTF.words[1]);
From your code I suppose you have a city name on every second row (starts from the first row):
MYCITY
123 MyAddress Dr.
MyCity, ST 12345
555.555.5555
And you want to apply some style on every first word of each second row. Something like this:
MYCITY
123 MyAddress Dr.
MyCity, ST 12345
555.555.5555
It can be done with this code:
var doc = app.activeDocument;
// pick the text frame and fill it with the text
var curTF = doc.pageItems.getByName('CITIES_1');
curTF.contents = 'MYCITY\r123 MyAddress Dr.\rMyCity, ST 12345\r555.555.5555';
// make two styles
var roman = make_style('roman', 'ArialMT', 10);
var bold = make_style('bold', 'Arial-BoldMT', 14);
// apply style 'roman' on the text
roman.applyTo(curTF.textRange, true);
// loop through the text and apply the style 'bold'
// on the first word of every second paragraph
var paragraphs = curTF.textRange.paragraphs;
for (var i = 0; i < paragraphs.length; i += 2) {
bold.applyTo(paragraphs[i].words[0], true);
}
function make_style(style_name, font_name, size) {
var doc = app.activeDocument;
try { var style = doc.characterStyles.add(style_name) }
catch(e) { var style = doc.characterStyles.getByName(style_name) }
style.characterAttributes.size = size;
style.characterAttributes.textFont = textFonts.getByName(font_name);
return style;
}
Output: