Guide de démarrage rapide du module complémentaire de l'éditeur Google Slides
Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
Ce guide de démarrage rapide crée un module complémentaire de l'éditeur Google Slides qui traduit le texte sélectionné dans une présentation.
Objectifs
- Configurez le script.
- Exécutez le script.
Prérequis
Pour utiliser cet exemple, vous devez remplir les conditions préalables suivantes :
- Un compte Google (l'approbation de l'administrateur peut être nécessaire pour les comptes Google Workspace).
- Un navigateur Web avec accès à Internet.
Configurer le script
- Créez une présentation Slides sur slides.new.
- Cliquez sur Extensions > Apps Script.
- Cliquez sur Projet sans titre.
- Renommez le projet Apps Script Translate Slides, puis cliquez sur Rename (Renommer).
- À côté du fichier
Code.gs
, cliquez sur Plus more_vert
> Renommer. Nommez le fichier translate
.
- Cliquez sur Ajouter un fichier add
> HTML. Nommez le fichier
sidebar
.
Remplacez le contenu de chaque fichier par le code correspondant ci-dessous, puis cliquez sur Enregistrer
.
Exécuter le script
- Dans votre présentation Slides, actualisez la page.
- Cliquez sur Extensions >
Traduire les diapositives
> Démarrer. L'élément de menu du module complémentaire peut mettre plusieurs secondes à s'afficher.
- Lorsque vous y êtes invité, autorisez le module complémentaire.
- Cliquez de nouveau sur Extensions >
Traduire les diapositives
> Démarrer.
- Ajoutez du texte à votre présentation et sélectionnez-le.
- Dans le module complémentaire, cliquez sur Traduire pour remplacer le texte sélectionné.
Étapes suivantes
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
Dernière mise à jour le 2025/07/25 (UTC).
[null,null,["Dernière mise à jour le 2025/07/25 (UTC)."],[[["\u003cp\u003eThis quickstart guide details how to build a Google Slides add-on using Apps Script to translate selected presentation text.\u003c/p\u003e\n"],["\u003cp\u003eThe add-on allows users to select text within their Google Slides presentation and translate it into various languages such as Arabic, Chinese, English, French, German, Hindi, Japanese, Portuguese, and Spanish.\u003c/p\u003e\n"],["\u003cp\u003eTo utilize this add-on, users need a Google Account, a web browser, and must follow setup instructions which include creating a Slides presentation, enabling Apps Script, and pasting provided code into designated script files.\u003c/p\u003e\n"],["\u003cp\u003eUsers can run the add-on by reloading their Slides presentation, authorizing the add-on, and selecting the text they wish to translate before clicking the "Translate" button in the add-on sidebar.\u003c/p\u003e\n"]]],["This document outlines how to create a Google Slides add-on that translates selected text. Key steps include: creating a new Slides presentation and an Apps Script project named \"Translate Slides,\" renaming the default code file to \"translate\", adding a file named \"sidebar\" and replacing the content of these files with the specified code. The script creates a menu to \"Open Translate\", which shows a sidebar with language options, allowing users to select text in the presentation and click \"Translate\" to change it into the chosen language.\n"],null,["# Google Slides Editor add-on quickstart\n\nThis quickstart creates a Google Slides Editor add-on\nthat translates selected text in a presentation.\n\nObjectives\n----------\n\n- Set up the script.\n- Run the script.\n\nPrerequisites\n-------------\n\nTo use this sample, you need the following prerequisites:\n\n- A Google Account (Google Workspace accounts might require administrator approval).\n- A web browser with access to the internet.\n\nSet up the script\n-----------------\n\n1. Create a Slides presentation at [slides.new](https://docs.google.com/presentation/create).\n2. Click **Extensions** \\\u003e **Apps Script**.\n3. Click **Untitled project**.\n4. Rename the Apps Script project to **Translate Slides** and click **Rename**.\n5. Next to the `Code.gs` file, click More more_vert \\\u003e **Rename** . Name the file `translate`.\n6. Click Add a file add \\\u003e **HTML** . Name the file `sidebar`.\n7. Replace the contents of each file with the following corresponding code, then\n click Save .\n\n ### translate.gs\n\n slides/translate/translate.gs \n [View on GitHub](https://github.com/googleworkspace/apps-script-samples/blob/main/slides/translate/translate.gs) \n\n ```javascript\n /**\n * @OnlyCurrentDoc Limits the script to only accessing the current presentation.\n */\n\n /**\n * Create a open translate menu item.\n * @param {Event} event The open event.\n */\n function onOpen(event) {\n SlidesApp.getUi().createAddonMenu()\n .addItem('Open Translate', 'showSidebar')\n .addToUi();\n }\n\n /**\n * Open the Add-on upon install.\n * @param {Event} event The install event.\n */\n function onInstall(event) {\n onOpen(event);\n }\n\n /**\n * Opens a sidebar in the document containing the add-on's user interface.\n */\n function showSidebar() {\n const ui = HtmlService\n .createHtmlOutputFromFile('sidebar')\n .setTitle('Translate');\n SlidesApp.getUi().showSidebar(ui);\n }\n\n /**\n * Recursively gets child text elements a list of elements.\n * @param {PageElement[]} elements The elements to get text from.\n * @return {Text[]} An array of text elements.\n */\n function getElementTexts(elements) {\n let texts = [];\n elements.forEach((element)=\u003e {\n switch (element.getPageElementType()) {\n case SlidesApp.PageElementType.GROUP:\n element.asGroup().getChildren().forEach((child)=\u003e {\n texts = texts.concat(getElementTexts(child));\n });\n break;\n case SlidesApp.PageElementType.TABLE:\n const table = element.asTable();\n for (let y = 0; y \u003c table.getNumColumns(); ++y) {\n for (let x = 0; x \u003c table.getNumRows(); ++x) {\n texts.push(table.getCell(x, y).getText());\n }\n }\n break;\n case SlidesApp.PageElementType.SHAPE:\n texts.push(element.asShape().getText());\n break;\n }\n });\n return texts;\n }\n\n /**\n * Translates selected slide elements to the target language using Apps Script's Language service.\n *\n * @param {string} targetLanguage The two-letter short form for the target language. (ISO 639-1)\n * @return {number} The number of elements translated.\n */\n function translateSelectedElements(targetLanguage) {\n // Get selected elements.\n const selection = SlidesApp.getActivePresentation().getSelection();\n const selectionType = selection.getSelectionType();\n let texts = [];\n switch (selectionType) {\n case SlidesApp.SelectionType.PAGE:\n selection.getPageRange().getPages().forEach((page)=\u003e {\n texts = texts.concat(getElementTexts(page.getPageElements()));\n });\n break;\n case SlidesApp.SelectionType.PAGE_ELEMENT:\n const pageElements = selection.getPageElementRange().getPageElements();\n texts = texts.concat(getElementTexts(pageElements));\n break;\n case SlidesApp.SelectionType.TABLE_CELL:\n selection.getTableCellRange().getTableCells().forEach((cell)=\u003e {\n texts.push(cell.getText());\n });\n break;\n case SlidesApp.SelectionType.TEXT:\n selection.getPageElementRange().getPageElements().forEach((element) =\u003e{\n texts.push(element.asShape().getText());\n });\n break;\n }\n\n // Translate all elements in-place.\n texts.forEach((text)=\u003e {\n text.setText(LanguageApp.translate(text.asRenderedString(), '', targetLanguage));\n });\n\n return texts.length;\n }\n ```\n\n ### sidebar.html\n\n slides/translate/sidebar.html \n [View on GitHub](https://github.com/googleworkspace/apps-script-samples/blob/main/slides/translate/sidebar.html) \n\n ```html\n \u003chtml\u003e\n \u003chead\u003e\n \u003clink rel=\"stylesheet\" href=\"https://ssl.gstatic.com/docs/script/css/add-ons1.css\"\u003e\n \u003cstyle\u003e\n .logo { vertical-align: middle; }\n ul { list-style-type: none; padding: 0; }\n h4 { margin: 0; }\n \u003c/style\u003e\n \u003c/head\u003e\n \u003cbody\u003e\n \u003cform class=\"sidebar branding-below\"\u003e\n \u003ch4\u003eTranslate selected slides into:\u003c/h4\u003e\n \u003cul id=\"languages\"\u003e\u003c/ul\u003e\n \u003cdiv class=\"block\" id=\"button-bar\"\u003e\n \u003cbutton class=\"blue\" id=\"run-translation\"\u003eTranslate\u003c/button\u003e\n \u003c/div\u003e\n \u003ch5 class=\"error\" id=\"error\"\u003e\u003c/h5\u003e\n \u003c/form\u003e\n \u003cdiv class=\"sidebar bottom\"\u003e\n \u003cimg alt=\"Add-on logo\" class=\"logo\"\n src=\"https://www.gstatic.com/images/branding/product/1x/translate_48dp.png\" width=\"27\" height=\"27\"\u003e\n \u003cspan class=\"gray branding-text\"\u003eTranslate sample by Google\u003c/span\u003e\n \u003c/div\u003e\n\n \u003cscript src=\"//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js\"\u003e\u003c/script\u003e\n \u003cscript\u003e\n $(function() {\n // Add an input radio button for every language.\n const languages = {\n ar: 'Arabic',\n zh: 'Chinese',\n en: 'English',\n fr: 'French',\n de: 'German',\n hi: 'Hindi',\n ja: 'Japanese',\n pt: 'Portuguese',\n es: 'Spanish'\n };\n const languageList = Object.keys(languages).map((id)=\u003e {\n return $('\u003cli\u003e').html([\n $('\u003cinput\u003e')\n .attr('type', 'radio')\n .attr('name', 'dest')\n .attr('id', 'radio-dest-' + id)\n .attr('value', id),\n $('\u003clabel\u003e')\n .attr('for', 'radio-dest-' + id)\n .html(languages[id])\n ]);\n });\n\n $('#run-translation').click(runTranslation);\n $('#languages').html(languageList);\n });\n\n /**\n * Runs a server-side function to translate the text on all slides.\n */\n function runTranslation() {\n this.disabled = true;\n $('#error').text('');\n google.script.run\n .withSuccessHandler((numTranslatedElements, element) =\u003e{\n element.disabled = false;\n if (numTranslatedElements === 0) {\n $('#error').empty()\n .append('Did you select elements to translate?')\n .append('\u003cbr/\u003e')\n .append('Please select slides or individual elements.');\n }\n return false;\n })\n .withFailureHandler((msg, element)=\u003e {\n element.disabled = false;\n $('#error').text('Something went wrong. Please check the add-on logs.');\n return false;\n })\n .withUserObject(this)\n .translateSelectedElements($('input[name=dest]:checked').val());\n }\n \u003c/script\u003e\n \u003c/body\u003e\n \u003c/html\u003e\n ```\n\nRun the script\n--------------\n\n1. In your Slides presentation, reload the page.\n2. Click **Extensions** \\\u003e **Translate Slides** \\\u003e **Start**. It might take several seconds for the add-on menu item to appear.\n3. When prompted, authorize the add-on.\n4. Again, click **Extensions** \\\u003e **Translate Slides** \\\u003e **Start**.\n5. Add text to your presentation and select it.\n6. In the add-on, click **Translate** to replace the selected text.\n\nNext steps\n----------\n\n- [Extending Google Slides with Apps Script](/apps-script/guides/slides)\n- [Slides service reference](/apps-script/reference/slides)"]]