Quickstart: Translate Add-on

Complete the steps described in the rest of this page, and in about five minutes you'll have created a Google Slides add-on that translates text in your presentation.

Set it up

  1. Create a new Google Presentation.
  2. From within your new presentation, select the menu item Tools > Script editor. If you are presented with a welcome screen, click Blank Project.
  3. Delete any code in the script editor and paste in the code below.

Code.gs

/**
 * @OnlyCurrentDoc Limits the script to only accessing the current presentation.
 */

/**
 * Create a open translate menu item.
 */
function onOpen(event) {
  SlidesApp.getUi().createAddonMenu()
      .addItem('Open Translate', 'showSidebar')
      .addToUi();
}

/**
 * Open the Add-on upon install.
 */
function onInstall(event) {
  onOpen(event);
}

/**
 * Opens a sidebar in the document containing the add-on's user interface.
 */
function showSidebar() {
  var ui = HtmlService
      .createHtmlOutputFromFile('Sidebar')
      .setTitle('Translate');
  SlidesApp.getUi().showSidebar(ui);
}

/**
 * Recursively gets child text elements a list of elements.
 * @param {PageElement[]} elements The elements to get text from.
 * @return {Text[]} An array of text elements.
 */
function getElementTexts(elements) {
  var texts = [];
  elements.forEach(function(element) {
    switch (element.getPageElementType()) {
      case SlidesApp.PageElementType.GROUP:
        element.asGroup().getChildren().forEach(function(child) {
          texts = texts.concat(getElementTexts(child));
        });
        break;
      case SlidesApp.PageElementType.TABLE:
        var table = element.asTable();
        for (var y = 0; y < table.getNumColumns(); ++y) {
          for (var x = 0; x < table.getNumRows(); ++x) {
            texts.push(table.getCell(x, y).getText());
          }
        }
        break;
      case SlidesApp.PageElementType.SHAPE:
        texts.push(element.asShape().getText());
        break;
    }
  });
  return texts;
}

/**
 * Translates selected slide elements to the target language using Apps Script's Language service.
 *
 * @param {string} targetLanguage The two-letter short form for the target language. (ISO 639-1)
 * @return {number} The number of elements translated.
 */
function translateSelectedElements(targetLanguage) {
  // Get selected elements.
  var selection = SlidesApp.getActivePresentation().getSelection();
  var selectionType = selection.getSelectionType();
  var texts = [];
  switch (selectionType) {
    case SlidesApp.SelectionType.PAGE:
      var pages = selection.getPageRange().getPages().forEach(function(page) {
        texts = texts.concat(getElementTexts(page.getPageElements()));
      });
    break;
    case SlidesApp.SelectionType.PAGE_ELEMENT:
      var pageElements = selection.getPageElementRange().getPageElements();
      texts = texts.concat(getElementTexts(pageElements));
    break;
    case SlidesApp.SelectionType.TABLE_CELL:
      var cells = selection.getTableCellRange().getTableCells().forEach(function(cell) {
        texts.push(cell.getText());
      });
    break;
    case SlidesApp.SelectionType.TEXT:
      var elements = selection.getPageElementRange().getPageElements().forEach(function(element) {
        texts.push(element.asShape().getText());
      });
    break;
  }

  // Translate all elements in-place.
  texts.forEach(function(text) {
    text.setText(LanguageApp.translate(text.asRenderedString(), '', targetLanguage));
  })

  return texts.length;
}

  1. Create a new file by selecting the menu item File > New > HTML file. Name the file "Sidebar".
  2. Delete any code in the new editor tab and paste in the code below.

Sidebar.html

<html>
  <head>
    <link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
    <style>
      .logo { vertical-align: middle; }
      ul { list-style-type: none; padding: 0; }
      h4 { margin: 0; }
    </style>
  </head>
  <body>
    <form class="sidebar branding-below">
      <h4>Translate selected slides into:</h4>
      <ul id="languages"></ul>
      <div class="block" id="button-bar">
        <button class="blue" id="run-translation">Translate</button>
      </div>
      <h5 class="error" id="error"></h5>
    </form>
    <div class="sidebar bottom">
      <img alt="Add-on logo" class="logo"
        src="https://www.gstatic.com/images/branding/product/1x/translate_48dp.png" width="27" height="27">
      <span class="gray branding-text">Translate sample by Google</span>
    </div>

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script>
      $(function() {
        // Add an input radio button for every language.
        var languages = {
          ar: 'Arabic',
          zh: 'Chinese',
          en: 'English',
          fr: 'French',
          de: 'German',
          hi: 'Hindi',
          ja: 'Japanese',
          pt: 'Portuguese',
          es: 'Spanish'
        };
        var languageList = Object.keys(languages).map(function(id) {
          return $('<li>').html([
            $('<input>')
                .attr('type', 'radio')
                .attr('name', 'dest')
                .attr('id', 'radio-dest-' + id)
                .attr('value', id),
            $('<label>')
                .attr('for', 'radio-dest-' + id)
                .html(languages[id])
          ]);
        });

        $('#run-translation').click(runTranslation);
        $('#languages').html(languageList);
      });

      /**
       * Runs a server-side function to translate the text on all slides.
       */
      function runTranslation() {
        this.disabled = true;
        $('#error').text('');
        google.script.run
            .withSuccessHandler(function(numTranslatedElements, element) {
              element.disabled = false;
              if (numTranslatedElements === 0) {
                $('#error').empty()
                    .append('Did you select elements to translate?')
                    .append('<br/>')
                    .append('Please select slides or individual elements.');
              }
              return false;
             })
            .withFailureHandler(function(msg, element) {
              element.disabled = false;
              $('#error').text('Something went wrong. Please check the add-on logs.');
              return false;
            })
            .withUserObject(this)
            .translateSelectedElements($('input[name=dest]:checked').val());
      }
    </script>
  </body>
</html>

  1. Select the menu item File > Save all. Name your new script "Translate Quickstart" and click OK. The script's name is shown to end users in several places, including the authorization dialog.

Try it out

  1. Switch back to your presentation and reload the page.
  2. After a few seconds, a Translate Quickstart sub-menu appears under the Add-ons menu. Click Add-ons > Translate Quickstart > Start.
  3. A dialog box indicates that the script requires authorization. Click Continue. A second dialog box requests authorization for specific Google services. Click Allow.
  4. A sidebar appears. To test it, type some text into your presentation, then select it, and click the blue Translate button. To replace the text in the presentation, click Insert.

Publish

Since this is an example add-on, our tutorial ends here. If you were developing a real add-on, the last step would be to publish it for other people to find and install. To learn more, check out our add-ons guide.

Learn more

To continue learning about how to extend Google Slides with Apps Script, take a look at the following resources:

发送以下问题的反馈:

此网页
Apps Script
Apps Script