Stay organized with collections
Save and categorize content based on your preferences.
The advanced Docs service allows you to use the
Google Docs API in Apps Script. Much like Apps Script's
built-in Docs service,
this API allows scripts to 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.
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.
/** * Create a new document. * @see https://developers.google.com/docs/api/reference/rest/v1/documents/create * @return {string} documentId */functioncreateDocument(){try{// Create document with titleconstdocument=Docs.Documents.create({'title':'My New Document'});console.log('Created document with ID: '+document.documentId);returndocument.documentId;}catch(e){// TODO (developer) - Handle exceptionconsole.log('Failed with error %s',e.message);}}
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.
/** * 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];// One option for replacing all text is to specify all tab IDs.constrequest={replaceAllText:{containsText:{text:findText,matchCase:true},replaceText:replaceText,tabsCriteria:{tabIds:[TAB_ID_1,TAB_ID_2,TAB_ID_3],}}};// Another option is to omit TabsCriteria if you are replacing across all tabs.constrequest={replaceAllText:{containsText:{text:findText,matchCase:true},replaceText:replaceText}};requests.push(request);}try{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;}catch(e){// TODO (developer) - Handle exceptionconsole.log('Failed with error : %s',e.message);}}
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.
/** * 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'}}];try{constresponse=Docs.Documents.batchUpdate({'requests':requests},documentId);returnresponse.replies;}catch(e){// TODO (developer) - Handle exceptionconsole.log('Failed with an error %s',e.message);}}
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.
/** * 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){try{// 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;}}}catch(e){// TODO (developer) - Handle exceptionconsole.log('Failed with error %s',e.message);}}
Best Practices
Batch Updates
When using the advanced Docs service, combine multiple requests in an array
rather than calling batchUpdate in a loop.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-08-18 UTC."],[[["\u003cp\u003eThe advanced Docs service in Apps Script enables programmatic reading, editing, and formatting of Google Docs content using the Google Docs API.\u003c/p\u003e\n"],["\u003cp\u003eWhile often requiring the enabling of advanced services, it offers more features compared to the built-in Docs service.\u003c/p\u003e\n"],["\u003cp\u003eThis service mirrors the functionality of the public Docs API, allowing scripts to leverage its objects, methods, and parameters.\u003c/p\u003e\n"],["\u003cp\u003eSample code snippets are provided for tasks like creating documents, finding and replacing text, inserting and styling text, and reading paragraphs.\u003c/p\u003e\n"],["\u003cp\u003eFor optimal performance, batch multiple requests into a single \u003ccode\u003ebatchUpdate\u003c/code\u003e call instead of using loops.\u003c/p\u003e\n"]]],[],null,["The advanced Docs service allows you to use the\n[Google Docs API](/docs/api) in Apps Script. Much like Apps Script's\n[built-in Docs service](/apps-script/reference/document),\nthis API allows scripts to read, edit, and format content in Google Docs. In\nmost cases the built-in service is easier to use, but this advanced service\nprovides a few extra features.\n| **Note:** This is an advanced service that you must [enable before use](/apps-script/guides/services/advanced). Follow the [quickstart](/docs/api/quickstart/apps-script) for step-by-step instructions on how to get started.\n\nReference\n\nFor detailed information on this service, see the\n[reference documentation](/docs/api/reference/rest) for the Docs API.\nLike all advanced services in Apps Script, the advanced Docs service uses the\nsame objects, methods, and parameters as the public API. For more information, see [How method signatures are determined](/apps-script/guides/services/advanced#how_method_signatures_are_determined).\n\nTo report issues and find other support, see the\n[Docs API support guide](/docs/api/support).\n\nSample code\n\nThe sample code below uses [version 1](/docs/api/reference/rest) of the API.\n\nCreate document\n\nThis sample creates a new document. \nadvanced/docs.gs \n[View on GitHub](https://github.com/googleworkspace/apps-script-samples/blob/main/advanced/docs.gs) \n\n```gosu\n/**\n * Create a new document.\n * @see https://developers.google.com/docs/api/reference/rest/v1/documents/create\n * @return {string} documentId\n */\nfunction createDocument() {\n try {\n // Create document with title\n const document = Docs.Documents.create({'title': 'My New Document'});\n console.log('Created document with ID: ' + document.documentId);\n return document.documentId;\n } catch (e) {\n // TODO (developer) - Handle exception\n console.log('Failed with error %s', e.message);\n }\n}\n```\n\nFind and replace text\n\nThis sample finds and replaces pairs of text across all tabs in a document. This\ncan be useful when replacing placeholders in a copy of a template document with\nvalues from a database. \nadvanced/docs.gs \n[View on GitHub](https://github.com/googleworkspace/apps-script-samples/blob/main/advanced/docs.gs) \n\n```gosu\n/**\n * Performs \"replace all\".\n * @param {string} documentId The document to perform the replace text operations on.\n * @param {Object} findTextToReplacementMap A map from the \"find text\" to the \"replace text\".\n * @return {Object} replies\n * @see https://developers.google.com/docs/api/reference/rest/v1/documents/batchUpdate\n */\nfunction findAndReplace(documentId, findTextToReplacementMap) {\n const requests = [];\n for (const findText in findTextToReplacementMap) {\n const replaceText = findTextToReplacementMap[findText];\n // One option for replacing all text is to specify all tab IDs.\n const request = {\n replaceAllText: {\n containsText: {\n text: findText,\n matchCase: true\n },\n replaceText: replaceText,\n tabsCriteria: {\n tabIds: [TAB_ID_1, TAB_ID_2, TAB_ID_3],\n }\n }\n };\n // Another option is to omit TabsCriteria if you are replacing across all tabs.\n const request = {\n replaceAllText: {\n containsText: {\n text: findText,\n matchCase: true\n },\n replaceText: replaceText\n }\n };\n requests.push(request);\n }\n try {\n const response = Docs.Documents.batchUpdate({'requests': requests}, documentId);\n const replies = response.replies;\n for (const [index] of replies.entries()) {\n const numReplacements = replies[index].replaceAllText.occurrencesChanged || 0;\n console.log('Request %s performed %s replacements.', index, numReplacements);\n }\n return replies;\n } catch (e) {\n // TODO (developer) - Handle exception\n console.log('Failed with error : %s', e.message);\n }\n}\n```\n\nInsert and style text\n\nThis sample inserts new text at the start of the first tab in the document and\nstyles it with a specific font and size. Note that when possible you should\nbatch together multiple operations into a single `batchUpdate` call for\nefficiency. \nadvanced/docs.gs \n[View on GitHub](https://github.com/googleworkspace/apps-script-samples/blob/main/advanced/docs.gs) \n\n```gosu\n/**\n * Insert text at the beginning of the first tab in the document and then style\n * the inserted text.\n * @param {string} documentId The document the text is inserted into.\n * @param {string} text The text to insert into the document.\n * @return {Object} replies\n * @see https://developers.google.com/docs/api/reference/rest/v1/documents/batchUpdate\n */\nfunction insertAndStyleText(documentId, text) {\n const requests = [{\n insertText: {\n location: {\n index: 1,\n // A tab can be specified using its ID. When omitted, the request is\n // applied to the first tab.\n // tabId: TAB_ID\n },\n text: text\n }\n },\n {\n updateTextStyle: {\n range: {\n startIndex: 1,\n endIndex: text.length + 1\n },\n textStyle: {\n fontSize: {\n magnitude: 12,\n unit: 'PT'\n },\n weightedFontFamily: {\n fontFamily: 'Calibri'\n }\n },\n fields: 'weightedFontFamily, fontSize'\n }\n }];\n try {\n const response =Docs.Documents.batchUpdate({'requests': requests}, documentId);\n return response.replies;\n } catch (e) {\n // TODO (developer) - Handle exception\n console.log('Failed with an error %s', e.message);\n }\n}\n```\n\nRead first paragraph\n\nThis sample logs the text of the first paragraph of the first tab in the\ndocument. Because of the structured nature of paragraphs in the\nDocs API, this involves combining the text of multiple sub-elements. \nadvanced/docs.gs \n[View on GitHub](https://github.com/googleworkspace/apps-script-samples/blob/main/advanced/docs.gs) \n\n```gosu\n/**\n * Read the first paragraph of the first tab in a document.\n * @param {string} documentId The ID of the document to read.\n * @return {Object} paragraphText\n * @see https://developers.google.com/docs/api/reference/rest/v1/documents/get\n */\nfunction readFirstParagraph(documentId) {\n try {\n // Get the document using document ID\n const document = Docs.Documents.get(documentId, {'includeTabsContent': true});\n const firstTab = document.tabs[0];\n const bodyElements = firstTab.documentTab.body.content;\n for (let i = 0; i \u003c bodyElements.length; i++) {\n const structuralElement = bodyElements[i];\n // Print the first paragraph text present in document\n if (structuralElement.paragraph) {\n const paragraphElements = structuralElement.paragraph.elements;\n let paragraphText = '';\n\n for (let j = 0; j \u003c paragraphElements.length; j++) {\n const paragraphElement = paragraphElements[j];\n if (paragraphElement.textRun !== null) {\n paragraphText += paragraphElement.textRun.content;\n }\n }\n console.log(paragraphText);\n return paragraphText;\n }\n }\n } catch (e) {\n // TODO (developer) - Handle exception\n console.log('Failed with error %s', e.message);\n }\n}\n```\n\nBest Practices\n\nBatch Updates\n\nWhen using the advanced Docs service, combine multiple requests in an array\nrather than calling `batchUpdate` in a loop.\n\nDon't --- Call `batchUpdate` in a loop. \n\n var textToReplace = ['foo', 'bar'];\n for (var i = 0; i \u003c textToReplace.length; i++) {\n Docs.Documents.batchUpdate({\n requests: [{\n replaceAllText: ...\n }]\n }, docId);\n }\n\nDo --- Call `batchUpdate` with an array of\nupdates. \n\n var requests = [];\n var textToReplace = ['foo', 'bar'];\n for (var i = 0; i \u003c textToReplace.length; i++) {\n requests.push({ replaceAllText: ... });\n }\n\n Docs.Documents.batchUpdate({\n requests: requests\n }, docId);"]]