InDesign脚本更改行的第一个字母的样式



我正在为InDesign编写一个脚本,以找到每一段每一行的第一个字符,如果它是元音,则将其更改为另一种颜色。由于这是我在InDesign脚本方面的第一次工作,我下载了Adobe的脚本指南,并成功地完成了以下工作:

createCharacterStyle();
main();

function main() {
// I don't check if a document is open for now
var myDocument = app.documents.item(0);
var myStory = myDocument.stories.item(0);
var noOfParas = myStory.paragraphs.length;
for ( var theParaCounter = 0 ; theParaCounter < noOfParas ; theParaCounter++) {
var currentParaLinesCount = myStory.paragraphs.item(theParaCounter).lines.length;
for (var theLineCounter = 0 ; theLineCounter < currentParaLinesCount - 1 ; theLineCounter++ ) {
var theCurrentLine = myStory.paragraphs.item(theParaCounter).lines.item(theLineCounter).contents;
var theFirstChar = theCurrentLine.charAt(0);
if ( theFirstChar == 'a' || theFirstChar == 'e' || theFirstChar == 'i' || 
theFirstChar == 'o' || theFirstChar == 'u') {
theFirstChar.appliedCharacterStyle = 'Highlighted';
}
}
}
}

function createCharacterStyle() {
var myDocument = app.documents.item(0);
// Create the highlight color
try {
myColor = myDocument.colors.item('Red');
myName = myColor.name;
}
catch ( myError ) {
myColor = myDocument.colors.add({name:'Red', model:ColorModel.process, colorValue:[0,100,100,0]});
}
// Create a new Character Style
try {
myCharStyle = myDocument.characterStyles.item('Highlighted');
myName = myCharStyle.name;
}
catch ( myError ) {
myCharStyle = myDocument.characterStyles.add({name:'Highlighted'});
}
myCharStyle.fillColor = myColor;
myCharStyle.underline = true;
}

一开始我创建了字符样式(红色下划线(,然后在线条中循环。循环工作,并找到第一个字符。问题是该样式从未被应用。任何帮助都将不胜感激。谢谢

作为一个快速修复程序,您可以替换以下行:

theFirstChar.appliedCharacterStyle = 'Highlighted';

带有:

myStory.paragraphs[theParaCounter].lines[theLineCounter].characters[0].appliedCharacterStyle = 'Highlighted';

问题是代码中的theFirstChar只是一个字符串,一个文本。它没有属性appliedCharacterStyle。如果你想在对象character上应用字符样式,你必须从故事/段落/行中获取对象stories[0].paragraphs[counter].lines[counter].character[0]

注意:paragraphs.item(theParaCounter)paragraphs[theParaCounter]相同,lines.item(theLineCounter)lines[theLineCounter]相同。


此外,条件可以缩短:

if ('aeiou'.indexOf(theFirstChar.toLowerCase()) > -1) {

而不是:

if ( theFirstChar == 'a' || theFirstChar == 'e' || theFirstChar == 'i' || 
theFirstChar == 'o' || theFirstChar == 'u') {

.toLowerCase()使条件不区分大小写。如果你需要的话。


main()功能可以归结为:

function main() {
var doc = app.activeDocument;
var story = doc.stories[0];
var paragraphs = story.paragraphs.everyItem().getElements();
while (paragraphs.length) {
var lines = paragraphs.shift().lines.everyItem().getElements();
while (lines.length) {
var character = lines.shift().characters[0];
if ('aeiou'.indexOf(character.contents.toLowerCase()) < 0) continue;
character.appliedCharacterStyle = 'Highlighted';
}
} 
}

相关内容

最新更新