Google Slides - Creating an Add On

From NoskeWiki
Revision as of 17:23, 26 July 2019 by NoskeWiki (talk | contribs)
Jump to navigation Jump to search

About

NOTE: This page is a daughter page of: Google Slides, and is related to: JavaScript


This demos a simple "Google Slides Acknowledgement Slide Generator" which inserts a bunch of images into . a new slide via a Google Slides Add On.

Background and Instructions

This is similar to instructions from the Google Slides Quickstart (Translate)... and then the rest I figured out from the Slides API.

File:Google slides acknowledgement genrator.png
What the thing looks like after run


Steps:

  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 rename Code.gs to ackgenerator.gs.
  4. Create a new file by selecting the menu item File > New > HTML file. Name this file sidebar (Apps Script adds the .html extension automatically).
  5. Replace any code in these two files with the following content, respectively:


Google Slides Add On - Acknowledgement Slide Generator

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>
 
    <script>
      /**
       * Runs generator.
       */
      function runGenerator() {
        this.disabled = true;
        google.script.run
              .withSuccessHandler(function(numAddedProfiles, element) {
              element.disabled = false;
              if (numAddedProfiles > 0) {
                document.getElementById("txt-feedback").append('Slide created!');
              }
              return false;
             })
            .withFailureHandler(function(msg, element) {
              element.disabled = false;
              document.getElementById("txt-feedback").append('Something went wrong');
              return false;
            })
            .withUserObject(this)
            .addAcknowledgmentSlide("en");
        this.disabled = false;
      }
    </script>
 
  </head>
  <body>
    <form class="sidebar branding-below">
      <h4>Size of profile cards:</h4>
      ...
      <div class="block" id="button-bar">
        <button class="blue" id="run-generator" onclick="runGenerator()">Generate</button>
      </div>
      <h5 class="error" id="txt-feedback"></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">Ack Generator</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-generator').click(runGenerator);
        $('#languages').html(languageList);
      });

      /**
       * Runs a server-side function to translate the text on all slides.
       */
      function runGenerator() {
        this.disabled = true;
        $('#error').text('');
        google.script.run
            .withUserObject(this)
            .addAcknowledgmentSlide($('input[name=dest]:checked').val());
      }
    </script>
    -->
  </body>
</html>


ackgenerator.gs

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

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

/**
 * Open the Add-on upon install.
 * @param {Event} event The install event.
 */
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('Acknowledgement Generator');
  SlidesApp.getUi().showSidebar(ui);
}

/**
 * Insert a new slide at the start of the current presentatino.
 */
function insertTitleSlideAtStart() {
  var presentation = SlidesApp.getActivePresentation();
  presentation.insertSlide(0, SlidesApp.PredefinedLayout.TITLE_ONLY);
}

/**
 * Adds profile images and text, evenly spaced into the chosen slide.
 *
 * @param {int} numProfiles Number of profiles to insert.
 */
function insetAckSlideAtStart(numProfiles){
  // Insert new slide to start of presentation.
  insertTitleSlideAtStart();
  
  // Get first slide:
  var slideDeck = SlidesApp.getActivePresentation();
  var slide = slideDeck.getSlides()[0];
  
  // Slide dimensions:
  var SLIDE_WIDTH = slideDeck.getPageWidth();
  var SLIDE_HEIGHT = slideDeck.getPageHeight();
  var SLIDE_TOP_BANNER = Math.ceil(SLIDE_HEIGHT / 5);
  
  // Profile dimensions:
  var PROFILE_WIDTH = 100;
  var PROFILE_HEIGHT = 150;
  var PROFILE_NAME_HEIGHT = 30;
  var PROFILE_COMMENT_HEIGHT = 20;
  var PROFILE_PIC_HEIGHT = PROFILE_HEIGHT - PROFILE_NAME_HEIGHT;

  var PROFILE_NAME_Y_OFFSET = PROFILE_PIC_HEIGHT;
  var PROFILE_COMMENT_Y_OFFSET = PROFILE_NAME_Y_OFFSET + PROFILE_NAME_HEIGHT;
  
  // Determine number of rows/columns and spacing between boxes:
  var kMaxColsPerRow = 6;
  var numCols = (numProfiles > kMaxColsPerRow) ? kMaxColsPerRow : numProfiles;
  var numRows = Math.ceil(numProfiles / kMaxColsPerRow);

  var xSpacing = (SLIDE_WIDTH - (numCols * PROFILE_WIDTH)) / (numCols + 1);
  var ySpacing = ((SLIDE_HEIGHT - SLIDE_TOP_BANNER) - (numRows * PROFILE_HEIGHT)) / (numRows + 1);
  
  console.log('SLIDE_WIDTH=' + SLIDE_WIDTH + ' * SLIDE_HEIGHT=' + SLIDE_HEIGHT);  // DO NOT SUBMIT.
  console.log('numCols=' + numCols + ' * numRows=' + numRows);  // DO NOT SUBMIT.
  console.log('xSpacing=' + xSpacing + ' * ySpacing=' + ySpacing);  // DO NOT SUBMIT.
  
  // For each image:
  for(var i = 0; i < numProfiles; i++) {
    var rowIdx = Math.floor(i / kMaxColsPerRow);
    var colIdx = i - (rowIdx * kMaxColsPerRow);
    
    var x = (colIdx * PROFILE_WIDTH) + ((colIdx + 1) * xSpacing);
    var y = (rowIdx * PROFILE_HEIGHT) + ((rowIdx + 1) * ySpacing) + SLIDE_TOP_BANNER;
    
    console.log(' ' +  i + ':  x,y=' + x + ',' + y);  // DO NOT SUBMIT.
    
    var img = slide.insertImage("https://andrewnoske.com/w/images/1/16/Unknown_profile_300x300.png",
                                x, y, PROFILE_WIDTH, PROFILE_PIC_HEIGHT);
    
    var nameBox = slide.insertTextBox("Andrew",
                                       x, y + PROFILE_NAME_Y_OFFSET, PROFILE_WIDTH, PROFILE_NAME_HEIGHT);
    nameBox.getText().getTextStyle().setBold(true);
    var commentBox = slide.insertTextBox("anoske@",
                                          x, y + PROFILE_COMMENT_Y_OFFSET, PROFILE_WIDTH, PROFILE_COMMENT_HEIGHT);
    commentBox.getText().getTextStyle()
        .setLinkUrl('www.example.com')
        .setFontSize(10)
        .setForegroundColor('#0000dd');
  }
}

/**
 * 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 profiles created.
 */
function addAcknowledgmentSlide(targetLanguage) {
  // Add title slide to start:
  var numProfiles = 6;
  insetAckSlideAtStart(numProfiles);
  
  return numProfiles;
}



Links

  • Google Slides - official site, where you can create your own slides.