Advanced Docs Service

  • 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 singlebatchUpdate call for efficiency.

The advanced Docs service allows you to use theGoogle Docs API in Apps Script. Much like Apps Script'sbuilt-in Docs service,this API allows scripts to read, edit, and format content in Google Docs. Inmost cases the built-in service is easier to use, but this advanced serviceprovides a few extra features.

Note: This is an advanced service that you mustenable before use. Followthequickstart for step-by-stepinstructions on how to get started.

Reference

For detailed information on this service, see thereference documentation for the Docs API.Like all advanced services in Apps Script, the advanced Docs service uses thesame objects, methods, and parameters as the public API. For more information, seeHow method signatures are determined.

To report issues and find other support, see theDocs API support guide.

Sample code

The sample code below usesversion 1 of the API.

Create document

This sample creates a new document.

advanced/docs.gs
/** * Create a new document. * @see https://developers.google.com/docs/api/reference/rest/v1/documents/create * @return {string} documentId */functioncreateDocument(){// Create document with titleconstdocument=Docs.Documents.create({title:"My New Document"});console.log(`Created document with ID:${document.documentId}`);returndocument.documentId;}

Find and replace text

This sample finds and replaces pairs of text across all tabs in a document. Thiscan be useful when replacing placeholders in a copy of a template document withvalues from a database.

advanced/docs.gs
/** * Performs "replace all". * @param {string} documentId The document to perform the replace text operations on. * @param {Object} findTextToReplacementMap A map from the "find text" to the "replace text". * @return {Object} replies * @see https://developers.google.com/docs/api/reference/rest/v1/documents/batchUpdate */functionfindAndReplace(documentId,findTextToReplacementMap){constrequests=[];for(constfindTextinfindTextToReplacementMap){constreplaceText=findTextToReplacementMap[findText];// Replace all text across all tabs.constreplaceAllTextRequest={replaceAllText:{containsText:{text:findText,matchCase:true,},replaceText:replaceText,},};// Replace all text across specific tabs.const_replaceAllTextWithTabsCriteria={replaceAllText:{...replaceAllTextRequest.replaceAllText,tabsCriteria:{tabIds:[TAB_ID_1,TAB_ID_2,TAB_ID_3],},},};requests.push(replaceAllTextRequest);}constresponse=Docs.Documents.batchUpdate({requests:requests},documentId,);constreplies=response.replies;for(const[index]ofreplies.entries()){constnumReplacements=replies[index].replaceAllText.occurrencesChanged||0;console.log("Request %s performed %s replacements.",index,numReplacements,);}returnreplies;}

Insert and style text

This sample inserts new text at the start of the first tab in the document andstyles it with a specific font and size. Note that when possible you shouldbatch together multiple operations into a singlebatchUpdate call forefficiency.

advanced/docs.gs
/** * Insert text at the beginning of the first tab in the document and then style * the inserted text. * @param {string} documentId The document the text is inserted into. * @param {string} text The text to insert into the document. * @return {Object} replies * @see https://developers.google.com/docs/api/reference/rest/v1/documents/batchUpdate */functioninsertAndStyleText(documentId,text){constrequests=[{insertText:{location:{index:1,// A tab can be specified using its ID. When omitted, the request is// applied to the first tab.// tabId: TAB_ID},text:text,},},{updateTextStyle:{range:{startIndex:1,endIndex:text.length+1,},textStyle:{fontSize:{magnitude:12,unit:"PT",},weightedFontFamily:{fontFamily:"Calibri",},},fields:"weightedFontFamily, fontSize",},},];constresponse=Docs.Documents.batchUpdate({requests:requests},documentId,);returnresponse.replies;}

Read first paragraph

This sample logs the text of the first paragraph of the first tab in thedocument. Because of the structured nature of paragraphs in theDocs API, this involves combining the text of multiple sub-elements.

advanced/docs.gs
/** * Read the first paragraph of the first tab in a document. * @param {string} documentId The ID of the document to read. * @return {Object} paragraphText * @see https://developers.google.com/docs/api/reference/rest/v1/documents/get */functionreadFirstParagraph(documentId){// Get the document using document IDconstdocument=Docs.Documents.get(documentId,{includeTabsContent:true,});constfirstTab=document.tabs[0];constbodyElements=firstTab.documentTab.body.content;for(leti=0;i <bodyElements.length;i++){conststructuralElement=bodyElements[i];// Print the first paragraph text present in documentif(structuralElement.paragraph){constparagraphElements=structuralElement.paragraph.elements;letparagraphText="";for(letj=0;j <paragraphElements.length;j++){constparagraphElement=paragraphElements[j];if(paragraphElement.textRun!==null){paragraphText+=paragraphElement.textRun.content;}}console.log(paragraphText);returnparagraphText;}}}

Best Practices

Batch Updates

When using the advanced Docs service, combine multiple requests in an arrayrather than callingbatchUpdate in a loop.

Don't — CallbatchUpdate in a loop.

vartextToReplace=['foo','bar'];for(vari=0;i <textToReplace.length;i++){Docs.Documents.batchUpdate({requests:[{replaceAllText:...}]},docId);}

Do — CallbatchUpdate with an array ofupdates.

varrequests=[];vartextToReplace=['foo','bar'];for(vari=0;i <textToReplace.length;i++){requests.push({replaceAllText:...});}Docs.Documents.batchUpdate({requests:requests},docId);

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-12-11 UTC.