使用 Apps 脚本以编程方式更改 Google Docs 的默认段落标题

Change default paragraph headings programmatically for Google Docs with Apps Script

我一直在寻找这个功能有一段时间了。 基本上,我想更改标题、副标题、标题 1 等的默认段落样式。

我知道可以使用 Google 文档界面 (https://support.google.com/docs/answer/116338?hl=en),但据我所知不能以编程方式使用 Apps 脚本。

有人找到解决方案了吗?如果没有,我们可以将其作为功能请求提交给 Google Apps 脚本团队吗?这将是对现有 Apps 脚本文档的一个很好的补充 API 用于品牌推广。

现在可以使用 setHeadingAttributes 方法。比如我这里重新定义了一级标题和二级标题的样式。

  myHeading1 = {};
  myHeading1[DocumentApp.Attribute.FONT_SIZE] = 24;
  myHeading1[DocumentApp.Attribute.FONT_FAMILY] = "Georgia";

  myHeading2 = {};
  myHeading2[DocumentApp.Attribute.FONT_SIZE] = 16;
  myHeading2[DocumentApp.Attribute.FONT_FAMILY] = "Verdana";
  myHeading2[DocumentApp.Attribute.FOREGROUND_COLOR] = "#555555";

  var body = DocumentApp.getActiveDocument().getBody();
  body.setHeadingAttributes(DocumentApp.ParagraphHeading.HEADING1, myHeading1);
  body.setHeadingAttributes(DocumentApp.ParagraphHeading.HEADING2, myHeading2);

似乎无法将属性重置为默认值,因此如果您认为需要重置,请使用 getHeadingAttributes 获取原始属性并将它们存储在文档属性中。

请注意,更改标题属性不会立即影响现有标题:除非有人触及其标题级别(即从标题级别 drop-down 中选择内容,甚至与目前的)。要将更改追溯应用到现有段落,请参阅 this answer