When trying to convert ppt to Google Slide receive converting error - google-apps-script

In my google script program, I am trying to iterate over a folder and make all of the ppt files into google slide files.
function makeSlides(url) {
slideUrls = [];
var id = getId(url);
var powerPoints = DriveApp.getFolderById(id).getFilesByType(MimeType.MICROSOFT_POWERPOINT);
// turn ppt into slides
while(powerPoints.hasNext()) {
var powerPoint = powerPoints.next()
try{
var sheet = powerPoint.getBlob().getAs(MimeType.GOOGLE_SLIDES);
DriveApp.getFolderById(url).createFile(sheet)
Logger.log("OK " + powerPoint.getName());
}catch(e) {
Logger.log("ERROR: " + e)
}
}
After checking the logs I get an error
Exception: Converting from application/vnd.openxmlformats-officedocument.presentationml.presentation to application/vnd.google-apps.presentation is not supported.
I know within the UI of Google Drive, you can open a ppt as a Google Slide. Is there any work around to this? Or am I doing it wrong?
I did find this but this is the opposite of what I am trying to accomplish.

It cannot convert from Powerpoint format to Google Slides using getAs(). You can achieve this using Drive API. In this modification, I used Drive API using Advanced Google Services.
When you use this script, please enable Drive API at Advanced Google Services and API console. You can see about this at here.
Modified script:
Please modify as follows.
From:
var sheet = powerPoint.getBlob().getAs(MimeType.GOOGLE_SLIDES);
DriveApp.getFolderById(url).createFile(sheet)
To:
Drive.Files.insert({title: powerPoint.getName(), mimeType: MimeType.GOOGLE_SLIDES}, powerPoint.getBlob());
Note:
In this modified script, the converted file is created to the root folder. If you want to create in the specific folder, please modify from {title: powerPoint.getName(), mimeType: MimeType.GOOGLE_SLIDES} to {title: powerPoint.getName(), mimeType: MimeType.GOOGLE_SLIDES, parents: [{id: folderId}]}.
If you want to retrieve the file ID from the converted file, please use var id = Drive.Files.insert({title: powerPoint.getName(), mimeType: MimeType.GOOGLE_SLIDES}, powerPoint.getBlob()).id.
References:
Advanced Google Services
Drive API
Drive.Files.insert
If I misunderstand your question, please tell me. I would like to modify it.

Related

PDF Realtime down load and conversion

Im Looking for a way to use Google Apps Script to Download PDF file and convert file into Google Sheets.
The reason for this is that website only gives data in PDF form and i cant use Import function to get data for real-time updates
It depends on the way you will download your pdf files.
Here is simple example how you can convert PDF file from your Google Drive into Googe Document:
function pdfToDoc() {
var fileBlob = DriveApp.getFilesByName('test.pdf').next().getBlob();
var resource = {
title: fileBlob.getName(),
mimeType: fileBlob.getContentType()
};
var options = {
ocr: true
};
var docFile = Drive.Files.insert(resource, fileBlob, options);
Logger.log(docFile.alternateLink);
}
To make it work you need to enable Drive API:
Based on the answer: https://webapps.stackexchange.com/a/136948
And as far as I can see there is only DOC as output. Probably you can extract data from DOC and put it into Spreadsheet with script. But it depends on how exactly looks your data.

How do get GIF from Google Docs using Apps Script?

I want to get the gif image from google docs. Using Apps Script, gif images are got as
InlineImage. But it's only static without animating.
My code
var doc = DocumentApp.openByUrl('url');
Logger.log(doc.getBody().getImages()[0]);
var encoded = Utilities.base64Encode(doc.getBody().getImages()[0].getBlob().getBytes());
Logger.log(encoded);
You want to retrieve the original images from Google Document.
In your case, you want to retrieve an animation GIF from Google Document.
You want to achieve this using Google Apps Script.
If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.
Unfortunately, it seems that the original images cannot be directly retrieved using getImages(). So in this answer, I use the method of documents.get in Google Docs API.
Flow:
The flow of this sample script is as follows.
Retrieve the object from Google Document using the method of documents.get in Google Docs API.
Retrieve the source information from the retrieved object.
The embeded original images can be retrieved from the property of inlineObjects.
Create the original images from the retrieved source information.
Sample script:
Before you use this script, please enable Google Docs API at Advanced Google services.
function myFunction() {
var documentId = "###"; // Please set Google Document ID.
// Retrieve the object from Google Document using the method of documents.get in Google Docs API.
var obj = Docs.Documents.get(documentId);
// Retrieve the source information from the retrieved object.
var inlineObjects = Object.keys(obj.inlineObjects).reduce(function(ar, e, i) {
var o = obj.inlineObjects[e].inlineObjectProperties.embeddedObject;
if (o.hasOwnProperty("imageProperties")) {
var res = UrlFetchApp.fetch(o.imageProperties.contentUri, {headers: {Authorization: "Baerer " + ScriptApp.getOAuthToken()}, muteHttpExceptions: true});
if (res.getResponseCode() == 200) ar.push(res.getBlob().setName("image" + (i + 1)));
}
return ar;
}, []);
// Create the original images from the retrieved source information.
inlineObjects.forEach(function(blob) {
var id = DriveApp.createFile(blob).getId();
Logger.log(id)
})
}
When you run the script, the image files are created to the root folder. And you can see the file IDs of them at the log. The filename is "image1", "image2",,, as the sample.
References:
Advanced Google services
Method: documents.get
InlineObject
If I misunderstood your question and this was not the direction you want, I apologize.

Upload CSV/Excel File as Sheet via Google App Script

I see that the Drive Folder class has a createFile() which takes three arguments for name, content, and mimeType. Is it possible to use this as part of an upload call to have a user file uploaded and converted (to Google Docs) all in one go without having to call the REST API directly with convert=true?
For example, here's the HTML:
<html>
<head>
<base target="_top">
<script>
function handler(response) {
document.getElementById('uploader').innerHTML = "Uploaded file! " + response;
}
</script>
</head>
<body>
<div id="uploader">
<form>
<input type="file" name="theFile">
<input type="button" onclick="google.script.run.withSuccessHandler(handler).uploadFile(this.parentNode)" value="Upload!">
</form></div>
</body>
</html>
And here's the Google Script code:
function uploadFile(e) {
Logger.log("Uploading file!");
var dfolder = DriveApp.getFolderById('abcdefgh'); // replace w/ Drive FolderID
return dfolder.createFile(e.theFile).getName();
}
How would I go about changing that last line to something like:
return dfolder.createFile(newName, e.theFile, MimeType.GOOGLE_SHEETS);
Something I'm trying to figure out now is simply how to get the name of the file being uploaded (e.g. for newName). And then how to go about converting whatever form e.theFile is in to a string. If I try this as-is now I get the error:
Invalid argument: file.contentType at uploadFile(Code:31)
You want to upload CSV and Excel files using google.script.run.
When the file is uploaded, you want to convert to Google Spreadsheet.
You want to retrieve the filename of the uploaded file.
If my understanding is correct, how about this modification? Please think of this as just one of several answers.
I think that in your script, it is required to modify the Google Apps Script.
Modification points:
Value of e.theFile of uploadFile(e) is the blob. So you can retrieve the filename using getName().
You can convert the CSV and Excel format to Google Spreadsheet using Drive API. In this case, I used Drive API v2 at Advanced Google Services.
The reason of the error of Invalid argument: file.contentType at uploadFile is that the mimeType of MimeType.GOOGLE_SHEETS cannot be used with createFile().
Modified script:
Please modify uploadFile() as follows. Before you use this script, please enable Drive API at Advanced Google Services, and set the folder ID to folderId.
function uploadFile(e) {
Logger.log("Uploading file!");
// I modified below script.
var folderId = "###"; // Please set the folder ID here.
var blob = e.theFile;
var filename = blob.getName();
var mimeType = blob.getContentType();
if (mimeType == MimeType.CSV || mimeType == MimeType.MICROSOFT_EXCEL || mimeType == MimeType.MICROSOFT_EXCEL_LEGACY) {
return Drive.Files.insert({title: filename, mimeType: MimeType.GOOGLE_SHEETS, parents: [{id: folderId}]}, blob).title;
}
return "";
}
References:
Class Blob
Advanced Google Services
Files: insert of Drive API v2
If I misunderstood your question and this was not the result you want, I apologize.

Batch convert jpg to Google Docs

I have a folder of jpgs in Google Drive that I would like to convert to Google Docs. Now I can select each one manually and in the context menu "Open in Google Docs" This creates a new document with the image at the top of the page and OCR text below. I just want to do this with all my images.
There is a script here which converts gdoc to docx which I ought to be able to adapt for my case but I don't seem to be able to get it to work.
Here is my adapted script:
function convertJPGtoGoogleDocs() {
var srcfolderId = "~~~~~~~~~Sv4qZuPdJgvEq1A~~~~~~~~~"; // <--- Please input folder ID.
var dstfolderId = srcfolderId; // <--- If you want to change the destination folder, please modify this.
var files = DriveApp.getFolderById(srcfolderId).getFilesByType(MimeType.JPG);
while (files.hasNext()) {
var file = files.next();
DriveApp.getFolderById(dstfolderId).createFile(
UrlFetchApp.fetch(
"https://docs.google.com/document/d/" + file.getId() + "/export?format=gdoc",
{
"headers" : {Authorization: 'Bearer ' + ScriptApp.getOAuthToken()},
"muteHttpExceptions" : true
}
).getBlob().setName(file.getName() + ".docx")
);
}
}
Can anyone help?
Thanks.
You want to convert Jpeg files in a folder as Google Document.
When the Jpeg file is converted to Google Document, you want to use OCR.
If my understanding is correct, how about this modification?
Modification points:
In the script you modified, MimeType.JPG returns undefined. So the script in while is not run.
Please use MimeType.JPEG.
The script of this answer is used for exporting Google Document as Microsoft Word. Unfortunately, that script cannot be directly used for converting Jpeg file to Google Document.
If you want to modify the script of this answer, how about modifying as follows?
When you use this script, please enable Drive API at Advanced Google Services. By this, the API is automatically enabled at API console. The specification of Google Apps Script Project was Changed at April 8, 2019.
Modified script:
function convertJPGtoGoogleDocs() {
var srcfolderId = "~~~~~~~~~Sv4qZuPdJgvEq1A~~~~~~~~~"; // <--- Please input folder ID.
var dstfolderId = srcfolderId; // <--- If you want to change the destination folder, please modify this.
var files = DriveApp.getFolderById(srcfolderId).getFilesByType(MimeType.JPEG); // Modified
while (files.hasNext()) {
var file = files.next();
Drive.Files.insert({title: file.getName(), parents: [{id: dstfolderId}]}, file.getBlob(), {ocr: true}); // Modified
}
}
Note:
If there are a lot of files in the source folder, there is a possibility that the limitation of script runtime (6 min / execution) exceeds.
References:
Enum MimeType
Drive.Files.insert
If I misunderstand your question, please tell me. I would like to modify it.

Google app scripts: email a spreadsheet as excel

How do you make an app script which attaches a spreadsheet as an excel file and emails it to a certain email address?
There are some older posts on Stackoverflow on how to do this however they seem to be outdated now and do not seem to work.
Thank you.
It looks like #Christiaan Westerbeek's answer is spot on but its been a year now since his post and I think there needs to be a bit of a modification in the script he has given above.
var url = file.exportLinks[MimeType.MICROSOFT_EXCEL];
There is something wrong with this line of code, maybe that exportLinks has now depreciated. When I executed his code it gave an error to the following effect:
TypeError: Cannot read property "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" from undefined.
The workaround is as follows:
The URL in the above line of code is basically the "download as xlsx" URL that can be used to directly download the spreadsheet as an xlsx file that you get from File> Download as > Microsoft Excel (.xlsx)
This is the format:
https://docs.google.com/spreadsheets/d/<<<ID>>>/export?format=xlsx&id=<<<ID>>>
where <<>> should be replaced by the ID of your file.
Check here to easily understand how to extract the ID from the URL of your google sheet.
Here's an up-to-date and working version. One prerequisite for this Google Apps script to work is that the Drive API v2 Advanced Google Service must be enabled. Enable it in your Google Apps script via Resources -> Advanced Google Services... -> Drive API v2 -> on. Then, that window will tell you that you must also enabled this service in the Google Developers Console. Follow the link and enable the service there too! When you're done, just use this script.
/**
* Thanks to a few answers that helped me build this script
* Explaining the Advanced Drive Service must be enabled: http://stackoverflow.com/a/27281729/1385429
* Explaining how to convert to a blob: http://ctrlq.org/code/20009-convert-google-documents
* Explaining how to convert to zip and to send the email: http://ctrlq.org/code/19869-email-google-spreadsheets-pdf
* New way to set the url to download from by #tera
*/
function emailAsExcel(config) {
if (!config || !config.to || !config.subject || !config.body) {
throw new Error('Configure "to", "subject" and "body" in an object as the first parameter');
}
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var spreadsheetId = spreadsheet.getId()
var file = Drive.Files.get(spreadsheetId);
var url = 'https://docs.google.com/spreadsheets/d/'+spreadsheetId+'/export?format=xlsx';
var token = ScriptApp.getOAuthToken();
var response = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
var fileName = (config.fileName || spreadsheet.getName()) + '.xlsx';
var blobs = [response.getBlob().setName(fileName)];
if (config.zip) {
blobs = [Utilities.zip(blobs).setName(fileName + '.zip')];
}
GmailApp.sendEmail(
config.to,
config.subject,
config.body,
{
attachments: blobs
}
);
}
Update: I updated the way to set the url to download from. Doing it through the file.exportLinks collection is not working anymore. Thanks to #tera for pointing that out in his answer.