Automating Google Slides production - google-apps-script

I'm wondering if there may be a way to programmatically create presentations in Google Slides. So for example if underlying data changes I can just refresh the deck without lots of copy paste for all the charts etc.
Something similar to using like markdown and R slidify to produce data driven PDF presentations. My end product needs to be a nice pretty Google Slides presentation.
Is this the sort of thing I could use the Google Drive API for? I'm not sure if App Script can be used for Slides like you can for Sheets.
Am hoping it's a common enough problem that a solution exists.
One option is to just automatically produce a PDF and then manually import into Google Slides. Problem is that this approach is a bit limited due to errors on conversion and lack of other Slides functionality.
Any input much appreciated.

It's 2018, and great news (and answers!) to this older question:
The Google Slides REST API launched in Nov 2016... here is its launch
post and 1st developer video I made to get you started. A shorter code sample than the video's is the Quickstart in the docs (available in a variety of languages). If you're new to Google APIs, I recommend you watch this video, then this one, and finally this one first to get an idea of how to use them. The code samples are in Python, but if you're not a Python developer, just pretend it's pseudocode because many languages are supported by Google APIs Client Libraries. :-)
If you code in JS and want to have Google host+run your app, the Slides service in Google Apps Script launched in Sep 2017... here is its launch
post and 1st developer video I made to get you started. This is also the same technology behind Slides Add-ons. If you're new to Apps Script, I recommend you watch this video to get an idea of what it is and how to use it. Then check out its video library for more examples of using Apps Script. (Admittedly, it's easier to code w/Apps Script vs. the REST APIs, making it more "addictive" for developers... you were warned!) :-)
Additional videos on programmatically accessing Google Slides can be found via its developer video library. Videos on this and other G Suite developer technologies can be found in the G Suite Dev Show series which I produce.
There's no video for this, but there's an open source Markdown-to-Google Slides generator (written in Node.js) my colleague created that you may be interested in, representing one of the "reference apps" using the Slides API. You can find more about this app as well as others on the Samples page of the documentation.
No video for this either, but Node.js developers who want to get up-to-speed quickly learning how to use this API should try the Slides API codelab where you build an app that uses Google BigQuery to analyze open source licenses and generate a report presentation... letting you learn TWO Google Cloud technologies with one tutorial! :-)

The Google Slides API was launched on 11/9/2016. It provides the ability to read, create, and edit Google Slides presentations.
At the moment there still isn't an equivalent service in Apps Script, but you can use the Apps Script OAuth2 library and UrlFetchApp to make calls to the API within a script.

Requested feature, follow https://code.google.com/p/google-apps-script-issues/issues/detail?id=1573&q=presentation&colspec=Stars%20Opened%20ID%20Type%20Status%20Summary%20Component%20Owner for updates.

An example from Apps Script:
Enable the Slides API in the developer console:
Click on Resources > Developers Console Project > [Your_Project_Name].
Click on Enable API, search for Slides and enable the Slides API.
Use UrlFetchApp to send authenticated requests to the Slides API
As a simple example from within Apps Script, consider fetching the latest version of a Presentation (presentations.get).
// Add your presentation ID
var presentationId = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
// Force add the Drive scope (as this comment *will* get parsed
// and trigger a popup to authorize Drive access)
// DriveApp.createFile('')
// URL formed as per the Slides REST documentation
var url = 'https://slides.googleapis.com/v1/presentations/' + presentationId;
var options = {
headers: {
Authorization: 'Bearer ' + ScriptApp.getOAuthToken()
}
};
var response = UrlFetchApp.fetch(url, options);
// Turn this back into a JS Object so it can be used.
var presentation = JSON.parse(response.getContentText());
// Log the ID of the presentation
Logger.log(presentation.presentationId);
// Log the number of slides...
Logger.log(presentation.slides.length);
// Loop through the slides
var slides = presentation.slides;
slides.forEach(function(slide) {
// ... do something with each slide...
});
The structure of presentation is also documented in the REST reference. Armed with the REST reference, this example can be extended to be used with any Slides API request and response.

Related

One question survey app Google Apps Script and Google Sheets with user management

I have to do a little bit of "crowdsourcing" for my work and it would consist in a very simple web app where a user can register/log in, and then be taken to a page where a picture is shown to a user and submit a number.
I'd like to be able to set up a few rules to choose which picture the user will see (so he won't have to answer twice the same question and also to allow some overlap between users to compare their answers).
We can assume that I have a google sheet with a list of images URLs that can be accessed and that I would like the answers to be populated there.
I figured that this tutorial would be a good start since it handles user creation and management and user can submit ideas :
Creating a CRUD Web App with Google Sheets
That being said I'm a bit clueless, I've tried to look for sample scripts deployed as web app but it's hard to know where to start.
I'll appreciate any help !
Google Apps Script is, basically, a javascript environment with a set of libraries that interact with the Google Apps. For instance, to read or store information from/to Google Sheets or Google Docs. If you know javascript, you can create simple applications there. In addition, you can create plugins for Google Applications if you are interested.
A very simple example
Suppose you wanna display an HTML page. You can create an stand-alone script (an script not-bound to a G suite application) and use the content or the HTML services.
You can create a function that sends a simple message to the browser using the ContentService:
function doGet() {
return ContentService.createTextOutput('Hello, world!');
}
Or you can create a function that sends an HTML file in the same project using the HtmlService:
function doGet() {
return HtmlService.createHtmlOutputFromFile('Index');
}
Once you have created the function, you must deploy the script as a web application.
Save the script as a new version doing File > Manage Versions and Save new version.
Then, publish the app using Publish > Deploy as web app and provinding information about the permissions for the application.
After Google publishes the application, it gives you an URL to access the application,
You may check more in a simple tutorial on producing content with Google Apps Script. In addition, you may check the google guide to use the HtmlService to provide templated content, i.e. where the HTML are templates which data is provided by javascript functions and variables.
Getting started with Google Apps Script
To start, you may check some tutorials in the internet:
Google has some tutorials and a series of Youtube videos.
In addition, you may find multiple resources for Google App Scripts that may help you:
Google has a list of sample projects
Tanakeich has a list of resources for taking advantage of Google Apps Script.
Oshliaer has another list of resources.
There are Google Codelab (tutorials) for Apps Scripts. They include a lab for using Google Sheets as a reporting tool and for creating a Hangouts Chat bot with Apps Script
Developing Google Apps Script projects locally
Although Google Apps Script provides a web interface to create your applications (your scripts), a better idea may be to create the software locally, using more-traditional tools for Javascript.
Clasp is a command-line tool to develop locally Google Apps Script projects.
Google has a codelab that teach you how to use clasp.

Authorizing Google Charts to access private spreadsheets

I am trying to create a Web App using Google Apps Script to query data from my Google Sheet using Google Charts.
I have been able to successfully query the spreadsheet when the Google Sheet is publicly shared, however since the spreadsheet contains confidential info I would rather do it privately using authorizations.
The reason why I want to use Google Charts visualisation functions (as opposed to the server side Spreadsheet App) is because of the speed of querying large data sets.
I have tried following the steps in the above documentation. That is, creating a client id then using the gapi.auth library to authenticate myself but I continue to receive an error.
When i add the authorization library and first part of the code from the documentation (with console.log simply to see where it get's up to):
<script src="https://apis.google.com/js/auth.js?onload=init"></script>
<script>
var clientId = '1234.apps.googleusercontent.com';
var scopes = 'https://spreadsheets.google.com/feeds';
function init() {
console.log("here");
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true},handleAuthResult);
}
</script>
I receive the following error:
1289869776-mae_html_user_bin_i18n_mae_html_user.js:41 dropping
postMessage.. was from unexpected window
Any guidance is appreciated.
Since you are creating your web app using Google Apps Script, it's not necessary to "authorize Google Charts to access private charts" because you could use Google Apps Script services and methods to get the data from the spreadsheets and pass them to Google Charts.
On Converting from UiApp + Chart Service to Html Service + Google Visualization API it's shown how to convert the old dashboard example from from UiApp + Chart Service to HtmlService + Google Visualization API. This illustrates how to create a Google Apps Script web app that builds a chart from Google Spreadsheet data without "requiring authorization" as it's "implicitly" handled by Google Apps Script.
From the above link
Two functions cooperate to retrieve the dashboard’s data and display it. As soon as the visualization API is loaded, the sendQuery() function is invoked. Using the google.script.run facility, it sends its request to the server-side getSpreadsheetData() function. This is an asynchronous operation, so two callbacks are provided, a successHandler and a failureHandler. One or the other will receive the result of the server call, depending on the outcome.
H/T to jfllmartin, author of an answer to Converting my google dashboard app from the UI service to the HTML service where the above link was shared.
Related
How to create google dashboard including piechart and range select filter from a spreadsheet?
Display Spreadsheet data in Sites with Html Service
can I suggest you change from using Google sheets to using firebase with Google sheets or just Firebase, and then with Google appscript in the back end.
I often use a Google script to problematically update Firebase with data from the Google sheet. I then enjoy the speed and security of Firebase to deliver a super fast user experience.
There are two go to pages for using Firebase in appscript. The example page and the quick start.
Furthermore, I gave up using Google's own charting library and starting using high charts or chartJS, as they are more accessible.

Create presentation with entire JSON on Google Slides API

Hello everyone (sorry for my english)
I have a problem with Google Slides API, I need to duplicate a Google Slides Document from an account to an another (so I can't use Google Drive API with the function "copy").
For that, I used Google Slides API to retrieve a JSON Object (Presentation) on client-side and send to my server (nodejs).
In my server-side application, I send the Presentation Object to anyone and the client can store it in Google Drive (always with Google Slides API).
But the problem is when the client send the Presentation Object (with all fields) to Google Slides API (presentations.create method), it just create a naked Google Slides document without properties include in my requests.
I need to store an entire Google Slides document but I can't do that and I don't know why.
I spent all day with this issue, please can you help me :) ?
Thank you !!!
The Slides API only creates empty presentations via presentations.create(), unfortunately. Only the title is taken from that input object.
For a cross-account copy, Drive's copy API is likely your best bet. If you have write access to the source presentation in Drive, one option is to share it with the destination account first using the Drive permissions.update API and then using copy. Another option is to try an export then import.

Workflow for integrating Google Docs with my web app through Google Apps Script

I was searching for an SDK or API to create and/or edit Google Docs files, but (correct me if I'm wrong) it seems Google Apps Script is the way to integrate your app with G Suite. I'm now trying to grasp the basic workflow for a basic document editing operation.
For instance, say we have a Quote Template document that serves as the template for our business to create quotations for customers. From within our web app system, we would press a button that would duplicate that file with a new name and maybe replace some variables.
Now, here's where I am in a gray area. I'd think we would have to install some sort of SDK (PHP/Js/Ruby library) in our project, that would let us create a new file based on the template, and call some replacePattern(regex, value) method.
However, the more I read, it looks like the approach is different, where you would create a Google Apps Script and, from our web app, we make HTTP calls to a REST API that will run said script. Then, this script would do the creating document and replacing values.
Am I correct in assuming this is the basic workflow to integrate our web app with G Suite products, or am I missing something essential?
Yes, that would be the basic workflow. There is no public Google Docs REST API, so apps script at the moment is the only way to automate docs. If you want to integrate it with a current tool you can expose the script using the Execution API. There are client libraries, though being a REST API they can be accessed from anywhere you can make a http request. Links to the client libraries can be found in their respective quick starts found below:
https://developers.google.com/apps-script/guides/rest/
All of the business logic can be handled by the script such as copying a template, replacing values, and setting permissions to the file.
The DocumentApp service docs can be found at:
https://developers.google.com/apps-script/reference/document/

How can developers edit a Google Doc programmatically? Is there a Docs API?

There doesn't seem to be (to my knowledge) an API to edit Google Docs (not spreadsheets, their HTML based documents). Has anyone done something like the? Maybe by downloading the HTML version, editing and uploading the changes?
UPDATE (May 2019) The Google Docs API was officially launched in Feb 2019. The documentation is located at the link from my update in July below. A few weeks after launch, I produced a high-level video overview of what a mail merge application using the API would look like. (It's not a full-fledged G Suite Dev Show episode but does link to a working sample.)
UPDATE (Jul 2018) The Google Docs team pre-announced a forthcoming REST API at Google Cloud NEXT '18. Developers interested in getting into the early access program for the new API should register at https://developers.google.com/docs. The original answer below still stands as the REST API will become the second way you can access Google Docs programmatically.
Original answer (Mar 2017): (Most other answers are outdated.) Google Docs does not currently have a REST API, however developers can programmatically access (CRUD) documents using Google Apps Script, server-side JavaScript apps that are hosted at and run in Google's cloud. If you're new to Apps Script or to editing Google Docs with it, here are some learning resources:
Your first script which creates & edits a Doc, then uses Gmail to send it
to you.
I've got 4 intro videos for you (mostly Sheets-flavored)
They're in this playlist (see videos 5, 8, 22, 24)
Any forthcoming videos will be in this series
Useful pages in the official docs
How to CRUD Google Docs with Apps Script overview page
Extend Docs functionality by creating Docs add-ons via this quickstart
Apps Script reference documentation for Google Docs (Document Service)
See Google Docs add-ons that other developers have built
Simple example: if you have an existing Doc with a (Drive) file ID of DOCUMENT_ID_GOES_HERE, here's how you'd basically edit it with Apps Script, doing a pseudo "mail merge" of name & email into the document given placeholders {NAME} and {ADDR}:
function mergeNameEmail() {
// Open a document by ID
var doc = DocumentApp.openById(DOCUMENT_ID_GOES_HERE);
// Access the body of the document
var body = doc.getBody();
// Merge name & address from template
body.replaceText("{NAME}", "Ima Developer");
body.replaceText("{ADDR}", "123 Main St, Anytown, XX 00000");
}
The Document List API has been deprecated since September 2012 and looks like it could be retired after April 2015.
Updating the HTML version using the Drive API, as the question suggests, looks to be the only other way. I have been trying this and I have experienced a few of issues.
Comments are converted into citations and added to end of document.
If someone else is editing the doc via the browser any changes made by them between the API read and update time are lost.
Updates to a doc can break the formatting. For example I updated a doc several times and the vertical spacing between some elements (h1's, h2's etc) kept widening each time and ruined the doc.
When an API update occurs the cursor of anyone in the doc is moved to the top of the page.
There may be more issues. These are just the ones I have found in the last few days.
Not really sure if this is what you're looking for exactly but have you taken a look here http://code.google.com/apis/documents/docs/3.0/developers_guide_protocol.html It looks like it allows editing for content (v3.0 anyway).
There is com.google.api.services.drive.model.File.getExportLinks
You can get a Google Doc as a docx (for example), edit it using your favourite docx editor, then upload again. See the samples for doing this (starting with GoogleDriveDownloadAsDocx) in the context of docx4j. Note the README.
Or do the same with any of the other export formats.
(2019) Google now provides API for docs, slides, sheets, drive.
There is a sample app for this, Dr. Edit, on Google Drive's documentation.