Skip to content

Instantly share code, notes, and snippets.

@tanaikech
Created June 17, 2023 01:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tanaikech/dec8cf3755e3c2cf294655c605fd6840 to your computer and use it in GitHub Desktop.
Save tanaikech/dec8cf3755e3c2cf294655c605fd6840 to your computer and use it in GitHub Desktop.
Inserting Paragraphs with Checkboxes in Google Documents using Google Apps Script

Inserting Paragraphs with Checkboxes in Google Documents using Google Apps Script

This is a sample script for inserting the paragraphs with the checkboxes in Google Documents using Google Apps Script.

In the current stage, Google Documents can create paragraphs with checkboxes as the paragraph bullet. But, unfortunately, this cannot be created by the Google Document service (DocumentApp). Fortunately, it seems that this got to be able to be achieved by Google Docs API. In this post, I would like to introduce a sample script for this.

Sample script

When you test this script, please copy and paste the following script to the script editor of Google Documents. And, please enable Google Docs API at Advanced Google services.

function myFunction() {
  const sampleTexts = [
    "sample text 1",
    "sample text 2",
    "sample text 3",
    "sample text 4",
    "sample text 5",
  ];

  const doc = DocumentApp.getActiveDocument();
  const documentId = doc.getId();
  const body = doc.getBody();
  const idx = sampleTexts.map(
    (text) => body.getChildIndex(body.appendParagraph(text)) + 1
  );
  doc.saveAndClose();
  const content = Docs.Documents.get(documentId).body.content;
  const requests = idx.map((id) => ({
    createParagraphBullets: {
      bulletPreset: "BULLET_CHECKBOX",
      range: {
        startIndex: content[id].startIndex,
        endIndex: content[id].endIndex,
      },
    },
  }));
  Docs.Documents.batchUpdate({ requests }, documentId);
}

Testing

When this script is run, the situation shown in the top image can be obtained. As a test, I manually checked the checkboxes of "sample text 1", "sample text 3", and "sample text 5" after this script was run.

Note

Unfortunately, in the current stage, it seems that the inserted checkbox cannot be retrieved by the API. When the checkbox is retrieved by Google Docs API, the glyph type is still GLYPH_TYPE_UNSPECIFIED. And also, the inserted checkboxes cannot be checked and unchecked by the API.

I believe that this will be implemented in the future update.

References

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment