Advanced Docs Service

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.

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

Sample code

The sample code below uses version 1 of the API.

Create document

This sample creates a new document.

advanced/docs.gs
/**
 * Create a new document.
 */
function createDocument() {
  var document = Docs.Documents.create({'title': 'My New Document'});
  Logger.log('Created document with ID: ' + document.documentId);
}

Find and replace text

This sample finds and replaces pairs of text in a document. This can be useful when replacing placeholders in a copy of a template document with values 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".
 */
function findAndReplace(documentId, findTextToReplacementMap) {
  var requests = [];
  for (var findText in findTextToReplacementMap) {
    var replaceText = findTextToReplacementMap[findText];
    var request = {
      replaceAllText: {
        containsText: {
          text: findText,
          matchCase: true,
        },
        replaceText: replaceText
      }
    };
    requests.push(request);
  }

  var response = Docs.Documents.batchUpdate({'requests': requests}, documentId);
  var replies = response.replies;
  for (var i = 0; i < replies.length; i++) {
    var reply = replies[i];
    var numReplacements = reply.replaceAllText.occurrencesChanged || 0;
    Logger.log('Request %s performed %s replacements.', i, numReplacements);
  }
}

Insert and style text

This sample inserts new text at the start of the document and styles if with a specific font and size. Note that when possible you should batch together multiple operations into a single batchUpdate call for efficiency.

advanced/docs.gs
/**
 * Insert text at the beginning of 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.
 */
function insertAndStyleText(documentId, text) {
  var requests = [{
    insertText: {
      location: {
        index: 1
      },
      text: text
    }
  },
  {
    updateTextStyle: {
      range: {
        startIndex: 1,
        endIndex: text.length + 1
      },
      text_style: {
        fontSize: {
          magnitude: 12,
          unit: 'PT'
        },
        weightedFontFamily: {
          fontFamily: 'Calibri'
        }
      },
      fields: 'weightedFontFamily, fontSize'
    }
  }];
  Docs.Documents.batchUpdate({'requests': requests}, documentId);
}

Read first paragraph

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

advanced/docs.gs
 /**
 * Read the first paragraph of the body of a document.
 * @param {string} documentId The ID of the document to read.
 */
function readFirstParagraph(documentId) {
  var document = Docs.Documents.get(documentId);
  var bodyElements = document.body.content;

  for (var i = 0; i < bodyElements.length; i++) {
    var structuralElement = bodyElements[i];
    if (structuralElement.paragraph !== null) {
      var paragraphElements = structuralElement.paragraph.elements;
      var paragraphText = '';

      for (var j = 0; j < paragraphElements.length; j++) {
        var paragraphElement = paragraphElements[j];
        if (paragraphElement.textRun !== null) {
          paragraphText += paragraphElement.textRun.content;
        }
      }

      Logger.log(paragraphText);
      return;
    }
  }
}

Best Practices

Batch Updates

When using the advanced Docs service, combine multiple requests in an array rather than caling 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(docId, {
    requests: [{
      replaceAllText: ...
    }]
  });
}

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(docId, {
  requests: requests
});

Envoyer des commentaires concernant…

Besoin d'aide ? Consultez notre page d'assistance.