使用 Google Apps 脚本更改 Google Doc 的背景颜色

Change background color of Google Doc with Google Apps Script

我想使用 Google Apps 脚本更改整个文档的页面颜色。我不想更改段落的突出显示颜色。我想做相当于去 File > Page Setup > Page color.

我相信你的目标如下。

  • 您想更改 Google 文档的背景颜色。
  • 您想使用 Google Apps 脚本实现此目的。

我认为在这种情况下,有 2 种模式。

模式一:

在这个模式中,使用了文档服务(DocumentApp)。示例脚本如下

示例脚本:

请将以下脚本复制并粘贴到 Google 文档和 运行 函数 myFunction 的脚本编辑器中。本例中Document的背景设置为红色。

function myFunction() {
  const obj = {[DocumentApp.Attribute.BACKGROUND_COLOR]: "#ff0000"};
  DocumentApp.getActiveDocument().getBody().setAttributes(obj);
}

模式二:

在此模式中,使用了 Google 文档 API。示例脚本如下

示例脚本:

请将以下脚本复制并粘贴到 Google 文档和 please enable Docs API at Advanced Google services 的脚本编辑器中。并且,运行 函数 myFunction。本例中Document的背景设置为红色。

function myFunction() {
  const documentId = DocumentApp.getActiveDocument().getId();
  const resource = { requests: [{ updateDocumentStyle: { documentStyle: { background: { color: { color: { rgbColor: { red: 1, green: 0, blue: 0 } } } } }, fields: "background" } }] };
  Docs.Documents.batchUpdate(resource, documentId);
}

结果:

当使用以上2种模式时,得到如下结果。

发件人:

收件人:

参考文献: