Google Apps Script allows you to programmatically create and modify Google Docs, as well as customize the user interface with new menus, dialog boxes, and sidebars.
The basics
Apps Script can interact with Google Docs in two broad ways: any script can create or modify a document if the script's user has appropriate permissions for the document, and a script can also be bound to a document, which gives the script special abilities to alter the user interface or respond when the document is opened. To create a container-bound script from within Google Docs, click Extensions > Apps Script.
In either case, it's simple to interact with a Google Docs document through Apps Script's Document Service, as the following example demonstrates.
function createDoc() { var doc = DocumentApp.create('Sample Document'); var documentTab = doc.getTab('t.0').asDocumentTab(); var body = documentTab.getBody(); var rowsData = [['Plants', 'Animals'], ['Ficus', 'Goat'], ['Basil', 'Cat'], ['Moss', 'Frog']]; body.insertParagraph(0, doc.getName()) .setHeading(DocumentApp.ParagraphHeading.HEADING1); table = body.appendTable(rowsData); table.getRow(0).editAsText().setBold(true); }
The script above creates a new document in the user's Google Drive, then
retrieves the tab with ID t.0
(the default first tab), inserts a paragraph
that contains the same text as the document's name, styles that paragraph as a
heading, and appends a table based on the values in a two-dimensional array. The
script could just as easily make these changes to an existing document by
replacing the call to DocumentApp.create()
with DocumentApp.openById()
or openByUrl()
.
For scripts created inside a document (container-bound), use
DocumentApp.getActiveDocument()
and Document.getActiveTab()
.
Structure of a document
From Apps Script's perspective, a Google Docs document is structured
much like an HTML document—that is, a document is composed of one or more
Tab
objects, each of which contain
elements (like a Paragraph
or
Table
) that often contain other
elements. Most scripts that modify a Google Docs document begin with a call to
getTab()
and
asDocumentTab()
followed by getBody()
,
because the Body
is a core element
that contains all other elements in a tab except for the
HeaderSection
,
FooterSection
, and any
Footnotes
.
However, there are rules about which types of elements can contain other types. Furthermore, the Document Service in Apps Script can only insert certain types of elements into other elements. The tree below shows which elements can be contained by a certain type of element.
Elements shown in bold can be inserted; non-bold elements can only be manipulated in place.
- Document
- Tab
- DocumentTab
- Body
- HeaderSection
- ListItem
- HorizontalRule
- InlineDrawing
- InlineImage
- Text
- UnsupportedElement (page number, etc.)
- Paragraph
- HorizontalRule
- InlineDrawing
- InlineImage
- Text
- UnsupportedElement (page number, etc.)
- Table
- ListItem
- FooterSection
- ListItem
- HorizontalRule
- InlineDrawing
- InlineImage
- Text
- UnsupportedElement (page number, etc.)
- Paragraph
- HorizontalRule
- InlineDrawing
- InlineImage
- Text
- UnsupportedElement (page number, etc.)
- Table
- ListItem
- FootnoteSection
- DocumentTab
- Tab
Replacing text
Apps Script is often used to replace text in Google Docs. Let's say you have a spreadsheet full of client information and you want to generate a personalized Google Docs for each client. (This type of operation is often called a mail merge.)
There are many ways to replace text, but the simplest is the
replaceText()
method shown in the example below. replaceText
supports most
of JavaScript's regular expression features. The first function below
adds several lines of placeholder text to a Google Docs; in the real world, you
would be more likely to type the placeholders into the document yourself. The
second function replaces the placeholders with properties defined in the
client
object.
Note that both of these functions use the
getActiveDocument()
and
getActiveTab()
methods, which only apply to scripts created inside a Google Docs document;
in a stand-alone script, use
DocumentApp.create()
,
openById()
,
or openByUrl()
,
combined with Document.getTab()
,
instead.
Add some placeholders
function createPlaceholders() { var body = DocumentApp.getActiveDocument().getActiveTab().asDocumentTab().getBody(); body.appendParagraph('{name}'); body.appendParagraph('{address}'); body.appendParagraph('{city} {state} {zip}'); }
Replace the placeholders
function searchAndReplace() { var body = DocumentApp.getActiveDocument().getActiveTab().asDocumentTab().getBody(); var client = { name: 'Joe Script-Guru', address: '100 Script Rd', city: 'Scriptville', state: 'GA', zip: 94043 }; body.replaceText('{name}', client.name); body.replaceText('{address}', client.address); body.replaceText('{city}', client.city); body.replaceText('{state}', client.state); body.replaceText('{zip}', client.zip); }
Custom menus and user interfaces
You can customize Google Docs by adding menus, dialog boxes, and sidebars. Keep in mind, however, that a script can only interact with the UI for the current instance of an open document, and only if the script is bound to the document.
See how to add custom menus and dialogs to your Google Docs. To learn more about creating custom interfaces for a dialog or sidebar, see the guide to HTML Service. If you're planning to publish your custom interface as part of an add-on, follow the style guide for consistency with the style and layout of the Google Docs editor.
Add-ons for Google Docs
Add-ons run inside Google Docs and can be installed from the Google Docs add-on store. If you've developed a script for Google Docs and want to share it with the world, Apps Script lets you publish your script as an add-on so other users can install it from the add-on store.
To see how you can create an add-on for Google Docs, see quickstart for building Docs add-ons.
Triggers
Scripts that are bound to a Google
Doc can use a simple trigger to respond
to the document's onOpen
event, which
occurs whenever a user who has edit access to the document opens it in Google Docs.
To set up the trigger, just write a function called onOpen()
. For an example
of this trigger, see Custom menus in Google Workspace.
Although the simple trigger is useful for adding menus, it cannot use any Apps
Script services that require authorization.