Page Summary
-
The advanced Docs service in Apps Script allows you to use the Google Docs API to read, edit, and format Google Docs content.
-
This advanced service provides additional features beyond the built-in Apps Script Docs service but is an advanced service that requires enabling before use.
-
Sample code is provided for common tasks such as creating a document, finding and replacing text, inserting and styling text, and reading content from a document.
-
A best practice when using the advanced Docs service is to combine multiple update requests into a single
batchUpdatecall for efficiency.
Script to read, edit, and format content in Google Docs with additional features.
The advanced Docs service lets you use the Google Docs API in Google Apps Script. Much like Apps Script's built-in Docs service, this API lets scripts read, edit, and format content in Google Docs. In most cases the built-in service is easier to use, but this advanced service provides a few extra features.
This is an advanced service that you must enable before use. Follow the quickstart for step-by-step instructions on how to get started.
Reference
For detailed information on this service, see the reference documentation for the Docs API. Like all advanced services in Apps Script, the advanced Docs service uses the same objects, methods, and parameters as the public API. For more information, see How method signatures are determined.
To report issues and find other support, see the Docs API support guide.
Sample code
The following sample code uses version 1 of the API.
Create document
This sample creates a new document.
Find and replace text
This sample finds and replaces pairs of text across all tabs in a document. This can be useful when replacing placeholders in a copy of a template document with values from a database.
Insert and style text
This sample inserts new text at the start of the first tab in the document and
styles it with a specific font and size. Note that when possible you should
batch together multiple operations into a single batchUpdate call for
efficiency.
Read first paragraph
This sample logs the text of the first paragraph of the first tab in the document. Because of the structured nature of paragraphs in the Docs API, this involves combining the text of multiple sub-elements.
Best Practices
Batch Updates
When using the advanced Docs service, combine multiple requests
in an array rather than calling batchUpdate in a loop.
Don't — Call batchUpdate in a loop.
var textToReplace = ['foo', 'bar'];
for (var i = 0; i < textToReplace.length; i++) {
Docs.Documents.batchUpdate({
requests: [{
replaceAllText: ...
}]
}, docId);
}
Do — Call batchUpdate with an array of
updates.
var requests = [];
var textToReplace = ['foo', 'bar'];
for (var i = 0; i < textToReplace.length; i++) {
requests.push({ replaceAllText: ... });
}
Docs.Documents.batchUpdate({
requests: requests
}, docId);