setHeadingAttributes在Documents w / GAS中重新定义标题样式

时间:2017-10-04 15:39:46

标签: google-apps-script google-docs-api

我希望重新定义文档的标题样式。我的理解是getHeadingAttributes和setHeadingAttributes会让我这样做

https://developers.google.com/apps-script/reference/document/body#setheadingattributesparagraphheading-attributes

这就是我测试这个的方法 -

function main() { 
  var doc = DocumentApp.getActiveDocument();
  var body = doc.getBody();    

  styledef=body.getHeadingAttributes(DocumentApp.ParagraphHeading.HEADING1); 

  Logger.log("Before: \n" + JSON.stringify(styledef) ); 

  styledef[DocumentApp.Attribute.UNDERLINE] = true;
  styledef[DocumentApp.Attribute.BACKGROUND_COLOR] = '#ffff00';

  body.setHeadingAttributes(DocumentApp.ParagraphHeading.HEADING1, styledef);

  styledef=body.getHeadingAttributes(DocumentApp.ParagraphHeading.HEADING1);

  Logger.log("After: \n" + JSON.stringify(styledef)); 

}

此Body的标题属性已修改,如Logger输出所示:

    [17-10-04 09:20:53:379 MDT] Before: 
    {"FONT_SIZE":18,"ITALIC":false,"HORIZONTAL_ALIGNMENT":{},"INDENT_END":0,"INDENT_START":0,"LINE_SPACING":1,"UNDERLINE":false,"BACKGROUND_COLOR":null,"INDENT_FIRST_LINE":0,"SPACING_BEFORE":12,"SPACING_AFTER":0,"STRIKETHROUGH":false,"FOREGROUND_COLOR":"#000000","BOLD":true,"FONT_FAMILY":"Arial","VERTICAL_ALIGNMENT":{}}

    [17-10-04 09:20:53:382 MDT] After: 
    {"FONT_SIZE":18,"ITALIC":false,"HORIZONTAL_ALIGNMENT":{},"INDENT_END":0,"INDENT_START":0,"LINE_SPACING":1,"UNDERLINE":true,"BACKGROUND_COLOR":"#ffff00","INDENT_FIRST_LINE":0,"SPACING_BEFORE":12,"SPACING_AFTER":0,"STRIKETHROUGH":false,"FOREGROUND_COLOR":"#000000","BOLD":true,"FONT_FAMILY":"Arial","VERTICAL_ALIGNMENT":{}}

UNDERLINE changed from false to true

BACKGROUND_COLOR changed from null to #ffff00

但是在我的文档中,此脚本受到约束,标题1的样式对于带有该标题的现有段落没有改变。标题为标题1的新段落也不是我试图做出的改变。

顺便提一下,当我在NORMAL而不是HEADING1上运行相同的功能时,更改立即可见:每个标题(正常,标题,副标题,标题1等)都应用了下划线和背景颜色。

我觉得我从根本上误解了这些方法的目的(getHeadingAttributes,setHeadingAttributes)。如果不是这些方法,我想找到为文档重新定义标题样式的正确方法。你能为我指出正确的方向吗?

非常感谢,

1 个答案:

答案 0 :(得分:0)

还没有参与其中的大部分活动,但请查看Enum ParagraphHeading,因为它似乎与您的目标非常接近。

使用ParagraphHeading枚举配置ParagraphElement的标题样式。

 var body = DocumentApp.getActiveDocument().getBody();

 // Append a paragraph, with heading 1.
 var par1 = body.appendParagraph("Title");
 par1.setHeading(DocumentApp.ParagraphHeading.HEADING1);

 // Append a paragraph, with heading 2.
 var par2 = body.appendParagraph("SubTitle");
 par2.setHeading(DocumentApp.ParagraphHeading.HEADING2);

 // Append a paragraph, with normal heading.
 var par3 = body.appendParagraph("Text");
 par3.setHeading(DocumentApp.ParagraphHeading.NORMAL);