Translate Documents with Google Apps Script

The LanguageApp service of Apps Script can be used to translate any selected piece of text in a Google Document from one language to another. Select a paragraph in the document, or a word or a partial sentence, and choose the translate option from the menu bar. It will append the translated text with the original selection.

The functionality is offered by existing add-ons but this will give you an idea of what happens behind the scenes.

function translateSelection() {
  
  var selection = DocumentApp.getActiveDocument().getSelection();
  
  if (!selection) {
    DocumentApp.getUi().alert("Please select text for translation.");
    return;
  }
  
  var elements = selection.getSelectedElements();
  
  /* Append the translated text with the original */
  for (var i = 0; i < elements.length; i++) {
    
    if (elements[i].isPartial()) { /* Is partial text selected */
      
      var element = elements[i].getElement().asText();
      var startIndex = elements[i].getStartOffset();
      var endIndex = elements[i].getEndOffsetInclusive();
      
      var text = element.getText().substring(startIndex, endIndex + 1);
      var translatedText = LanguageApp.translate(text, 'ja', 'en'); 
      element.insertText(endIndex + 1, " [" + translatedText + "] ");
      
    } else {
      
      var element = elements[i].getElement();
      
      if (element.editAsText) { /* Is the selection contains text */
        var text = element.asText().getText();
        var translatedText = LanguageApp.translate(text, 'ja', 'en'); 
        element.asText().setText(text + " [" + translatedText + "] ");
      }
      
    }
  }
}