如何在不丢失已有段落样式的情况下向TextFrame的story追加内容?
问题描述
我想要编写一个针对InDesign的ExtendScript程序,创建TextFrame后逐个添加段落并应用不同样式(添加一段、应用样式,再添加另一段应用不同样式)。但每次向TextFrame的parentStory对象添加新段落时,InDesign会把最后使用的段落样式应用到所有已有段落。示例代码如下:
// Make a document with a single frame var doc = app.documents.add(); var frame = doc.pages[0].textFrames.add(); frame.geometricBounds = [0, 0, 20, 30]; // Make two paragraph styles var paraStyle1 = doc.paragraphStyles.add({name: "ParagraphStyle1"}); paraStyle1.pointSize = 20; var paraStyle2 = doc.paragraphStyles.add({name: "ParagraphStyle2"}); paraStyle2.pointSize = 8; // Add two lines to the frame var story = frame.parentStory; story.contents += "Line 1\rLine 2"; var para1 = frame.paragraphs[0]; var para2 = frame.paragraphs[1]; // Style the two paragraphs para1.appliedParagraphStyle = paraStyle1; para2.appliedParagraphStyle = paraStyle2; // At this point, the frame contains two paragraphs, each with its own style. // Now add a new paragraph to the story. // This has the effect of applying paraStyle2 to paragraphs 0 and 1 ! story.contents += "\rLine 3";
问题原因与解决方法
问题根源:直接修改
story.contents属性追加文本时,InDesign会把你最后一次应用的段落样式(这里是paraStyle2)设为当前文本流的默认样式,触发重新排版后,所有已有段落会被强制应用这个默认样式,导致之前设置的样式被覆盖。解决方法:放弃直接修改
story.contents,改用insertionPoints(插入点)来添加新内容,这种方式不会干扰已有的段落样式。修改添加新段落的代码如下:
// 改用插入点添加新段落,避免覆盖已有样式 var lastInsertionPoint = story.insertionPoints.item(story.insertionPoints.length - 1); lastInsertionPoint.contents = "\rLine 3"; // 可选:给新段落应用指定样式 var para3 = story.paragraphs.item(story.paragraphs.length - 1); para3.appliedParagraphStyle = paraStyle1; // 可替换为你需要的样式
用这种方式添加内容,已有的段落样式会被保留,新段落可以单独设置样式,不会出现批量覆盖的问题。
内容的提问来源于stack exchange,提问作者Greg Anderson
相关产品推荐
相关产品推荐

