Downloading a Google Slides presentation as PowerPoint doc using Google Apps Script? - google-apps-script

The GUI of Google Slides offers to download a GSlides presentation as a Powerpoint (myFile.pptx). I could not find the equivalent in the Google Apps Script documentation - any pointer?
EDIT
Thanks to comments and answers, I tried this snippet:
function testFileOps() {
// Converts the file named 'Synthese' (which happens to be a Google Slide doc) into a pptx
var files = DriveApp.getFilesByName('Synthese');
var rootFolder = DriveApp.getRootFolder();
while (files.hasNext()) {
var file = files.next();
var blobPptx = file.getBlob().getAs('application/vnd.openxmlformats-officedocument.presentationml.presentation');
var result = rootFolder.createFile(blobPptx);
}
}
It returns an error:
Converting from application/vnd.google-apps.presentation to
application/vnd.openxmlformats-officedocument.presentationml.presentation
is not supported. (line 7, file "Code")
SECOND EDIT
As per another suggestion in comments, I tried to make an http call from Google App Script, that would directly convert the gslides into pptx, without size limit. It produces a file on G Drive, but this file is corrupted / unreadable. The GAS script:
function convertFileToPptx() {
// Converts a public Google Slide file into a pptx
var rootFolder = DriveApp.getRootFolder();
var response = UrlFetchApp.fetch('https://docs.google.com/presentation/d/1Zc4-yFoUYONXSLleV_IaFRlNk6flRKUuAw8M36VZe-4/export/pptx');
var blobPptx = response.getContent();
var result = rootFolder.createFile('test2.pptx',blobPptx,MimeType.MICROSOFT_POWERPOINT);
}
Notes:
I got the mime type for pptx here
using the mime type 'pptx' returns the same error message

How about this modification?
Modification point:
response.getContent() returns byte array. So please use response.getBlob().
Modified script:
function convertFileToPptx() {
var fileId = "1Zc4-yFoUYONXSLleV_IaFRlNk6flRKUuAw8M36VZe-4";
var outputFileName = "test2.pptx";
var url = 'https://docs.google.com/presentation/d/' + fileId + '/export/pptx';
var rootFolder = DriveApp.getRootFolder();
var response = UrlFetchApp.fetch(url);
var blobPptx = response.getBlob();
var result = rootFolder.createFile(blobPptx.setName(outputFileName));
}
Note:
If you want to convert Google Slides, which are not published, in your Google Drive, please use access token. At that time please modify url as follows.
var url = 'https://docs.google.com/presentation/d/' + fileId + '/export/pptx?access_token=' + ScriptApp.getOAuthToken();
DriveApp.createFile() creates a file on root folder as the default.
References:
Class HTTPResponse
getOAuthToken()

As mentioned by tehhowch, you could get the Google Slide file from your Drive and get it as a .pptx. (Not sure of mime type.)
File#getAs:

I add all modifications with token part and specific folder
function convertFileToPptx() {
var fileId = "Your File ID";
var outputFileName = "name.pptx";
var url = 'https://docs.google.com/presentation/d/' + fileId + '/export/pptx';
//var rootFolder = DriveApp.getRootFolder();
var rootFolder = DriveApp.getFolderById("Your Folder ID")
var params = {method:"GET", headers:{"authorization":"Bearer "+ ScriptApp.getOAuthToken()}};
var response = UrlFetchApp.fetch(url,params);
var blobPptx = response.getBlob();
var result = rootFolder.createFile(blobPptx.setName(outputFileName));
}

To get the byte[] do:
function downloadAsPPTX(){
var presentation = SlidesApp.getActivePresentation();
var fileId = presentation.getId();
var url = 'https://docs.google.com/presentation/d/' + fileId + '/export/pptx';
var response = UrlFetchApp.fetch(url);
var blobPptx = response.getBlob();
Logger.log("size: "+blobPptx.getBytes().length);
}

Related

Google Apps Script how to export specific sheet as csv format

In MIT Inventor II, I use web component to get SpreadsheetID and SheetID through doGet() of google apps script. After I get the information I use another web component to set url as below to get csv-formatted file from specific sheet. My question is how to make GAS to get SpreadsheetID & SheetID and then export csv file at one time, so that I don't have to use 2 web components in Inventor side?
GAS codes is as below. This is to "return" spreadsheetID and sheetID.
function doGet(e) {
filename = e.parameter.account;
fileList = DriveApp.getFilesByName(filename);
while (fileList.hasNext()) {
var fileID = fileList.next().getId()
}
var file = SpreadsheetApp.openById(fileID) ;
sheet = file.getSheetByName("Message").activate()
var messageID = sheet.getSheetId();
return ContentService.createTextOutput([fileID,messageID]);
After I got SpreadsheetID & SheetID, I have to set 2nd web component from Inventor side to get csv file, see below.
https://docs.google.com/spreadsheets/d/xxxxSpreadsheetIDxxxx/edit#gid=sheetID
Here is how you can create a csv file of a selected sheet in google drive:
function sheetToCsv()
{
var ssID = SpreadsheetApp.getActiveSpreadsheet().getId();
var sheet_Name = "Sheet1"
var requestData = {"method": "GET", "headers":{"Authorization":"Bearer "+ScriptApp.getOAuthToken()}};
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheet_Name)
var sheetNameId = sheet.getSheetId().toString();
params= ssID+"/export?gid="+sheetNameId +"&format=csv"
var url = "https://docs.google.com/spreadsheets/d/"+ params
var result = UrlFetchApp.fetch(url, requestData);
var resource = {
title: sheet_Name+".csv",
mimeType: "application/vnd.csv"
}
var fileJson = Drive.Files.insert(resource,result)
}
The code creates a csv file that has the content of Sheet1.
In order to run the aforementioned function you need to activate the Advanced Drive Service.
Explanation:
Go to Resources => Advanced Google Services => activate Drive API
Another option is to create the csv file to a particular folder, then you need to replace the resource part of the code with this:
var folder_id ='id';
var resource = {
title: sheet_Name+".csv",
mimeType: "application/vnd.csv",
parents: [{ id: folder_id }]
}
My application was how to save a tab of a Google sheets spreadsheet to a CSV file in a shared drive. Doing it to the default "My Drive" was relatively easy based on Marios' answer in this post, but I struggled with this for a shared drive while until I came across ziganotschka's example which solved my problem.
Code for my simple App Script is:
function sheetToCsv()
{
var ssID = SpreadsheetApp.getActiveSpreadsheet().getId();
var sheet_Name = "[Your sheet name goes here]";
var requestData = {"method": "GET", "headers":{"Authorization":"Bearer "+ScriptApp.getOAuthToken()}};
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheet_Name);
var sheetNameId = sheet.getSheetId().toString();
params= ssID+"/export?gid="+sheetNameId +"&format=csv";
var url = "https://docs.google.com/spreadsheets/d/"+ params;
var result = UrlFetchApp.fetch(url, requestData);
var resource = {
title: sheet_Name+".csv",
mimeType: "MimeType.CSV",
parents:[{
"id": "[Your Shared Drive Folder ID goes here]"
}]
}
var optionalArgs={supportsAllDrives: true};
var fileJson = Drive.Files.insert(resource, result, optionalArgs);
}
I added a timestamp to the file name and a trigger to cause the script to execute daily via a timer.

is there a reason my getOAuthToken() was working and now isnt?

var sourceFolderId = "15Kux2yyL_OWoZBwnYPbJtyrlp1zQjY3T";
var folder = DriveApp.getFolderById(sourceFolderId);
var token = ScriptApp.getOAuthToken()
var imageUrl = folder.getFilesByName(uid).next().getDownloadUrl() + "&access_token=" +
ScriptApp.getOAuthToken();
var slide = Slides.Presentations.get(newTargetDocId).slides[0]
Logger.log(token)
Logger.log(imageUrl)
I have been using the above code to get an image from google drive and using batchupdate put it into google slides, however the auth token no longer allows a download, do i need to refresh it somehow?
The url goes to the correct image and the image is the correct file format but the code returns
API call to slides.presentations.batchUpdate failed with error: Invalid requests[1].createImage: The provided image is in an unsupported format. (line 243, file "Code").
I know the image is ok as i have already used it. I know the url is correct as it takes me to the image if i cut the authtoken off. The authtoken on the end no longer allows me to download the file on another browser.
New code based on comment about Drive changes
var sourceFolderId = "15Ku...............zQjY3T";
var folder = DriveApp.getFolderById(sourceFolderId);
var file = folder.getFilesByName(uid).next()
file.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW);
var imageUrl = "https://drive.google.com/uc?export=download&id=" + file.getId();
But now i get an invalid argument error on file.setSharing line
var sourceFolderId = "15Ku...............zQjY3T";
var folder = DriveApp.getFolderById(sourceFolderId);
var file = folder.getFilesByName(uid).next()
file.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW);
var imageUrl = "https://drive.google.com/uc?export=download&id=" + file.getId();
General file permissions will need to be altered to allow this to run with Gsuite admin pages

Add a button to automatically download a google sheet to excel from a google application script

I have an application made on google than handdle different sheets on a google workbook. I need to add a button to allow users download some of these sheets but in an excel format if is possible. I took one code from StackOv and try to modify it, as i donĀ“t want it name the file and save it in drive, i only need it download as same that when from excel it is download in Book1 ("libro1") without saving anywhere. THK!
var ss = SpreadsheetApp.openById("fffffffffffffffffffffffffffff...myID");
var sheetId = ss.ss.getSheetByName('nameSheetNeedToDownload');
var url = "https://docs.google.com/spreadsheets/d/" + sheetId + "/export?format=xlsx&access_token=" + ScriptApp.getOAuthToken();
var blob = UrlFetchApp.fetch(url).getBlob().setName(name + ".xlsx");
createFile(blob); // here need to create but without saving
THK you Tanaike!...Yes here i copy the code i have
function downloadAsXlsx() {
var bogus = DriveApp.getRootFolder();
var spreadSheet = SpreadsheetApp.openById('WorkbookID');
var ssID = spreadSheet.getSheetByName('SheetName');
Logger.log(ssID);
var url = "https://docs.google.com/spreadsheets/d/"+ssID+"/export?format=xlsx";
var params = {method:"GET", headers:{"authorization":"Bearer "+
ScriptApp.getOAuthToken()}};
var response = UrlFetchApp.fetch(url, params);
// save to drive
DriveApp.createFile(response);
}

Can I download file from URL link generated by google apps script

Please help I'm learning google-apps-script for short time.
I want to download file from remote site by url generating from data that stores in my spreadsheet.
for example, i have 2 paremeters:
Cell1 = val1, val2, ... valN
Cell2 = val21, val22, ... val2N
I split string from cell data to Arrays and than generate URL. for example: http://mysite.com/files/file.val1.val22.zip
Than i need to download file from this link...
Can I do this process automaticaly ?
This example function will retrieve your zip file, and place it into your Google Drive in folder "StackOverflow". You can also download a more complete version from this gist.
function getFile(fileURL) {
// see https://developers.google.com/apps-script/class_urlfetchapp
var response = UrlFetchApp.fetch(fileURL);
var fileBlob = response.getBlob()
var folder = DocsList.getFolder('StackOverflow');
var result = folder.createFile(fileBlob);
debugger; // Stop to observe if in debugger
}
For example:
getFile( "http://mysite.com/files/file.val1.val22.zip" );
Note that you cannot download per se, since you have no access to your PC's resources (e.g. file system) from apps-script. The file is still in "the cloud"... in this case, it's been copied from the web site it was on, into Google Drive. If you're running the Drive app, though, the file will now sync to your PC.
Yes, You can.
Hope below code can solve your problem:
//Declare function
function downloadFile() {
//Getting url,existing name and new name for image from the sheet in
//variable url, name and new_name respectively
var sh = SpreadsheetApp.getActiveSheet();
var row = sh.getLastRow();
Logger.log(row);
for (var i = 2; i <= row; i++) {
var url = sh.getRange(i, 10).getValue();
Logger.log(url);
var name = sh.getRange(i, 13).getValue();
var new_name = sh.getRange(i, 4).getValue();
//Creating authentication token for downloading image, it may not be //required if image can be downloaded without login into
var user = "***************";
var password = "************";
var headers = {
"Accept": "application/xml",
"Content-Type": "application/xml",
"Authorization": "Basic " + Utilities.base64Encode(user + ":" + password)
};
//defining method to download file
var options = {
"method": "get",
"headers": headers
};
//Getting folder name where to store downloaded image
var folders = DriveApp.getFoldersByName('test');
while (folders.hasNext()) {
var folder = folders.next();
Logger.log(folder.getName());
}
//Getting response on hit of url using downloading method defined //earlier storing in Blob
var response = UrlFetchApp.fetch(url, options).getBlob();
//Creating image in folder defined with response in blob and logging same file //in log to check, if required
var file = folder.createFile(response);
Logger.log(file);
//renaming image
var images = folder.getFiles();
while (images.hasNext()) {
var image = images.next();
file.setName(new_name);
Logger.log(image.getName());
}
}
}
//Hope you get it now
It's worked for me.
function downloadFile() {
var url = "https://raw.githubusercontent.com/hoat23/VisionArtificialAndImageProcessing/master/bin/utils_imgprocessing.py"
Logger.log(url);
var response = UrlFetchApp.fetch(url);
var text = response.getContentText()
var newFile = DriveApp.createFile('testfilegoogle.txt',text);
debugger; // Stop to observe if in debugger
}
//Hope you get it now

exporting spreadsheet to pdf then saving the file in google drive

I'm having problems saving to google drive after printing a google spreadsheet to pdf.
If i just put the "printurl" string into a browser, it will automatically give me the file. But I want it to be saved to google drive automatically. I've tried this code by borrowing code from other posts that emails a spreadsheet as PDF. But this produces a pdf that is unable to be opened. What am I doing wrong?
function printpdf() {
var spreadsheet_id="0Aiy1DTQRndx6dDRidXoxNzlXZFhxd2FITTlBbnUybnc";
var settings = '&fitw=true&portrait=false&exportFormat=pdf&gid=0&gridlines=false';
var printurl = 'https://spreadsheets.google.com/feeds/download/spreadsheets/Export? key=' + spreadsheet_id + settings;
var result=UrlFetchApp.fetch(printurl);
var content=result.getContent();
var file=DocsList.createFile("temp",content,"application/pdf");
}
Here is an update to this question under the new oauth2 format.
Printing spreadsheet to PDF then saving file in Drive using OAuth2
You can do it in a much simpler fashion
function printpdf(){
var spreadsheet_id="0Aiy1DTQRndx6dDRidXoxNzlXZFhxd2FITTlBbnUybnc";
var spreadsheetFile = DocsList.getFileById(spreadsheet_id);
var blob = spreadsheetFile.getAs('application/pdf');
DocsList.createFile(blob);
}
Note that the DocsList.createFile(blob) works only with Google Apps accounts.
did you mean it like that?
var id = SpreadsheetApp.getActiveSpreadsheet().getId();
var sheetName = getConfig(SHEET_NAME_CELL);
var dataSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
if (!dataSheet) {
Browser.msgBox("Can't find sheet named:" + sheetName);
return;
}
var dataSheetIndex = dataSheet.getSheetId();
//this is three level authorization
var oauthConfig = UrlFetchApp.addOAuthService("google");
oauthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
oauthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope=https://spreadsheets.google.com/feeds/");
oauthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
oauthConfig.setConsumerKey("anonymous");
oauthConfig.setConsumerSecret("anonymous");
//even better code
//oauthConfig.setConsumerKey(ScriptProperties.getProperty("consumerKey"));
//oauthConfig.setConsumerSecret(ScriptProperties.getProperty("consumerSecret"));
var requestData = {
"method": "GET",
"oAuthServiceName": "google",
"oAuthUseToken": "always"
};
var url = "https://spreadsheets.google.com/feeds/download/spreadsheets/Export?key=" + id + "&gid=" + dataSheetIndex + "&fitw=true&size=A4&portrait=true&sheetnames=false&printtitle=false&exportFormat=pdf&format=pdf&gridlines=false";
//Save File to Google Drive
var seplogoBlob = UrlFetchApp.fetch(url, requestData).getBlob().setName("Filename.pdf");
DocsList.createFile(seplogoBlob);