Colebot
Colebot

Reputation: 81

Change background color of Google Doc with Google Apps Script

I want to change the page color of my entire document using Google Apps Script. I do not want to change the highlight color of a paragraph. I want to do the equivalent of going to File > Page Setup > Page color.

Upvotes: 1

Views: 1241

Answers (1)

Tanaike
Tanaike

Reputation: 201388

I believe your goal as follows.

  • You want to change the background color of Google Document.
  • You want to achieve this using Google Apps Script.

I thought that in this case, there are 2 patterns.

Pattern 1:

In this pattern, Document service (DocumentApp) is used. The sample script is as follows.

Sample script:

Please copy and paste the following script to the script editor of Google Document and run the function myFunction. In this sample, the background of Document is set as the red color.

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

Pattern 2:

In this pattern, Google Docs API is used. The sample script is as follows.

Sample script:

Please copy and paste the following script to the script editor of Google Document, and please enable Docs API at Advanced Google services. And, run the function myFunction. In this sample, the background of Document is set as the red color.

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);
}

Result:

When above 2 patterns are used, the following result is obtained.

From:

enter image description here

To:

enter image description here

References:

Upvotes: 3

Related Questions