Good Morning All. I have written a short script which batch-creates [single page] Google Slides based on rows from a spreadsheet. While in the loop for each creation, I would like to create a PNG of the Slide in Google Drive (or download on the user's desktop). These pictures should be the same specs as if a user clicked File>Download>PNG - the heavy small text requires full projector HD - so I don't believe I can use the "Thumbnail" function which appears limited to 1600 pixels.
My code below generates the error "Converting from text/html to image/png is not supported" - so I'm not sure if this is a limitation of the API or a problem with my coding. Thank you in advance.
var options =
{
"contentType" : "image/PNG"
};
var url = 'https://docs.google.com/presentation/d/' + presentationCopyId + '/export/PNG';
var response = UrlFetchApp.fetch(url, options);
var image = response.getAs(MimeType.PNG);
image.setName(SlideName);
DriveApp.createFile(image);
Yes, It is possible.
You can use Google slide API and make a PNG file of every page of Google slide.
Here is the code,
BUT first you have to enable API as following
open script editor
click on resources-> Advanced Google Services
Enable Google slide API and Drive API .
click on ok
now copy and paste this code,
and write your slide ID in presentationID.
function generateScreenshots() {
var presentationId = "***ADD YOUR Google Slide ID Only***";
var presentation = SlidesApp.openById(presentationId);
var baseUrl =
"https://slides.googleapis.com/v1/presentations/{presentationId}/pages/{pageObjectId}/thumbnail";
var parameters = {
method: "GET",
headers: { Authorization: "Bearer " + ScriptApp.getOAuthToken() },
contentType: "application/json",
muteHttpExceptions: true
};
// Log URL of the main thumbnail of the deck
Logger.log(Drive.Files.get(presentationId).thumbnailLink);
// For storing the screenshot image URLs
var screenshots = [];
var slides = presentation.getSlides().forEach(function(slide, index) {
var url = baseUrl
.replace("{presentationId}", presentationId)
.replace("{pageObjectId}", slide.getObjectId());
var response = JSON.parse(UrlFetchApp.fetch(url, parameters));
// Upload Googel Slide image to Google Drive
var blob = UrlFetchApp.fetch(response.contentUrl).getBlob();
DriveApp.createFile(blob).setName("Image " + (index + 1) + ".png");
screenshots.push(response.contentUrl);
});
return screenshots;
}
This answer is outdated, leaving up for documentation purposes but please see other answer.
Answer:
Unfortunately it is not possible to export a Slides as a PNG file using the the Slides nor Drive APIs.
More Information:
According to the documentation, there are only four available MimeTypes for exporting Presentations files:
application/vnd.openxmlformats-officedocument.presentationml.presentation
application/vnd.oasis.opendocument.presentation
application/pdf
text/plain
Attempting to export to the image/png MIME Type results in the following error:
Converting from text/html to image/png is not supported
For testing purposes, I tried using the /export/pdf endpoint and making a second conversion to PNG from there like so:
function slidesAsPngAttempt() {
var presentationCopyId = "1Loa...pQs";
var options =
{
"contentType" : "application/pdf"
};
// for exporting to pdf the /export/pdf needs to be all lower case to avoid 404
var url = 'https://docs.google.com/presentation/d/' + presentationCopyId + '/export/pdf';
var response = UrlFetchApp.fetch(url, options);
var pdfAsblob = response.getBlob();
var image = pdfAsblob.getAs('image/png');
image.setName(DriveApp.getFileById(presentationCopyId).getName());
DriveApp.createFile(image);
}
Unfortunately, a similar error occurs when running var image = pdfAsblob.getAs('image/png'):
Converting from application/pdf to image/png is not supported.
From the same export MIME types reference documentation, the only export types available for PDF files are:
text/csv
text/tab-separated-values
application/zip
References:
G Suite documents and corresponding export MIME types
Google Apps Script - method Blob.getAs(contentType)
Related
Good Morning All. I have written a short script which batch-creates [single page] Google Slides based on rows from a spreadsheet. While in the loop for each creation, I would like to create a PNG of the Slide in Google Drive (or download on the user's desktop). These pictures should be the same specs as if a user clicked File>Download>PNG - the heavy small text requires full projector HD - so I don't believe I can use the "Thumbnail" function which appears limited to 1600 pixels.
My code below generates the error "Converting from text/html to image/png is not supported" - so I'm not sure if this is a limitation of the API or a problem with my coding. Thank you in advance.
var options =
{
"contentType" : "image/PNG"
};
var url = 'https://docs.google.com/presentation/d/' + presentationCopyId + '/export/PNG';
var response = UrlFetchApp.fetch(url, options);
var image = response.getAs(MimeType.PNG);
image.setName(SlideName);
DriveApp.createFile(image);
Yes, It is possible.
You can use Google slide API and make a PNG file of every page of Google slide.
Here is the code,
BUT first you have to enable API as following
open script editor
click on resources-> Advanced Google Services
Enable Google slide API and Drive API .
click on ok
now copy and paste this code,
and write your slide ID in presentationID.
function generateScreenshots() {
var presentationId = "***ADD YOUR Google Slide ID Only***";
var presentation = SlidesApp.openById(presentationId);
var baseUrl =
"https://slides.googleapis.com/v1/presentations/{presentationId}/pages/{pageObjectId}/thumbnail";
var parameters = {
method: "GET",
headers: { Authorization: "Bearer " + ScriptApp.getOAuthToken() },
contentType: "application/json",
muteHttpExceptions: true
};
// Log URL of the main thumbnail of the deck
Logger.log(Drive.Files.get(presentationId).thumbnailLink);
// For storing the screenshot image URLs
var screenshots = [];
var slides = presentation.getSlides().forEach(function(slide, index) {
var url = baseUrl
.replace("{presentationId}", presentationId)
.replace("{pageObjectId}", slide.getObjectId());
var response = JSON.parse(UrlFetchApp.fetch(url, parameters));
// Upload Googel Slide image to Google Drive
var blob = UrlFetchApp.fetch(response.contentUrl).getBlob();
DriveApp.createFile(blob).setName("Image " + (index + 1) + ".png");
screenshots.push(response.contentUrl);
});
return screenshots;
}
This answer is outdated, leaving up for documentation purposes but please see other answer.
Answer:
Unfortunately it is not possible to export a Slides as a PNG file using the the Slides nor Drive APIs.
More Information:
According to the documentation, there are only four available MimeTypes for exporting Presentations files:
application/vnd.openxmlformats-officedocument.presentationml.presentation
application/vnd.oasis.opendocument.presentation
application/pdf
text/plain
Attempting to export to the image/png MIME Type results in the following error:
Converting from text/html to image/png is not supported
For testing purposes, I tried using the /export/pdf endpoint and making a second conversion to PNG from there like so:
function slidesAsPngAttempt() {
var presentationCopyId = "1Loa...pQs";
var options =
{
"contentType" : "application/pdf"
};
// for exporting to pdf the /export/pdf needs to be all lower case to avoid 404
var url = 'https://docs.google.com/presentation/d/' + presentationCopyId + '/export/pdf';
var response = UrlFetchApp.fetch(url, options);
var pdfAsblob = response.getBlob();
var image = pdfAsblob.getAs('image/png');
image.setName(DriveApp.getFileById(presentationCopyId).getName());
DriveApp.createFile(image);
}
Unfortunately, a similar error occurs when running var image = pdfAsblob.getAs('image/png'):
Converting from application/pdf to image/png is not supported.
From the same export MIME types reference documentation, the only export types available for PDF files are:
text/csv
text/tab-separated-values
application/zip
References:
G Suite documents and corresponding export MIME types
Google Apps Script - method Blob.getAs(contentType)
On my website, I am hosting a few videos via Google Drive. On my sidebar, there is a thumbnail of the videos and I'd like to show the duration of the video in the corner. I have looked at two similar questions (here and here) to solve this problem. This is what I produced from looking at these two problems:
function sample1() {
console.log("running script");
var fileId = "theFileID"; // Please set the file ID of the video file.
var fields = "mimeType,name,videoMediaMetadata"; // duration is included in "videoMediaMetadata"
var url = "https://www.googleapis.com/drive/v3/files/" + fileId + "?fields=" + encodeURIComponent(fields) + "&access_token=" + ScriptApp.getOAuthToken();
var res = UrlFetchApp.fetch(url, {headers: {Authorization: "Bearer " + ScriptApp.getOAuthToken()}});
var obj = JSON.parse(res);
console.log("filename: %s, duration: %s seconds", obj.name, obj.videoMediaMetadata.durationMillis / 1000);
}
sample1();
However, when I check the console after running this script, nothing is printed after "running script". Is there a different approach I should be taking in my program when attempting to solve this problem via Google APIs?
Using the Drive API method Files: get with Apps Script I have been able to get the durationMillis from the video.
You have to add the Drive API Advanced Services on the Apps Script project:
function getVideoLength() {
var fileId = "FILE ID";
var returnedFile = Drive.Files.get(fileId);
Logger.log(returnedFile.videoMediaMetadata.durationMillis)
}
i am trying to send the google document's content to my backend service.
In the app script i am using
if(host == 'sheets'){
var content = SpreadsheetApp.getActiveSpreadsheet().getBlob();
}else if (host == 'docs') {
var content = DocumentApp.getActiveDocument().getBlob();
}
I take the blob and sent it through multi part form request in URLFetchApp.fetch() through the payload parameter.
But the content for both the docs and sheets is converted/sent to my service as pdf.
Is there any way to preserve/send the files in google format itself ?
if not in google format then in Microsoft office formats ?
Best Regards,
Saurav
As mentioned in the similar post, this behavior is expected. If you want to get the file's content in Microsoft office formats,
you can check the following options:
(OPTION 1): Get export URL from Advanced Drive Service
Sample Code:
function getDocument(){
var host = "docs";
var fileId;
var exportFormat;
if(host == 'sheets'){
fileId = SpreadsheetApp.getActiveSpreadsheet().getId();
exportFormat = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
}else if (host == 'docs') {
fileId = DocumentApp.getActiveDocument().getId();
exportFormat = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
}
var url = Drive.Files.get(fileId).exportLinks[exportFormat];
Logger.log(url);
var oauthToken = ScriptApp.getOAuthToken();
var content = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + oauthToken
}
}).getBlob();
Logger.log(content.getContentType());
content.setName("TestFile");
MailApp.sendEmail("email#sample.com", "Test", "Test", {attachments: content});
}
Pre-requisite:
You need to enable Advanced Drive Service to get the export links of the file using Drive.Files.get(). This request will return a File Resource where you can get the exportLinks that can be accessed using a key based on the supported export MIME Types
What it does?
Depending on the host set, get the file id and export format based on supported export MIME Types
Get the file resource using Drive.Files.get() and get the export link based on the export format key set in step 1.
Use UrlFetchApp.fetch(url, params) and get the file's blob using HTTPResponse.getBlob()
Output:
(OPTION 2):Create export URL manually using the template url
Sample Code:
function getDocument(){
var host = "docs";
var fileId;
var url;
if(host == 'sheets'){
fileId = SpreadsheetApp.getActiveSpreadsheet().getId();
url = "https://docs.google.com/spreadsheets/export?id="+fileId+"&exportFormat=xlsx"
}else if (host == 'docs') {
fileId = DocumentApp.getActiveDocument().getId();
url = "https://docs.google.com/feeds/download/documents/export/Export?id="+fileId+"&exportFormat=docx";
}
Logger.log(url);
var oauthToken = ScriptApp.getOAuthToken();
var content = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + oauthToken
}
}).getBlob();
Logger.log(content.getContentType());
}
What it does?
Depending on the host set, get the file id and create an export link using this templates:
EXCEL: https://docs.google.com/spreadsheets/export?id=<fileId>&exportFormat=xlsx
WORD: https://docs.google.com/feeds/download/documents/export/Export?id=<fileId>&exportFormat=docx
Use UrlFetchApp.fetch(url, params) and get the file's blob using HTTPResponse.getBlob()
Note:
Based on Quotas for Google Services, Url Fetch Call has a daily quota of 20,000 for Consumer and G Suite free edition, while 100,000 for Google Workspace accounts
How to check the resolution of the image which is stored on Google Drive using Google Apps Script.
var childFile = files.next();
data = [
childFile.getName(),
childFile.getDateCreated(),
childFile.getUrl(),
childFile.getLastUpdated(),
childFile.getDescription(),
childFile.getSize()
];
In the above code I am able to get the size of the image but how can I get the resolution of image.
You can use the Google Drive API to get the image size and other EXIF data. Make sure you have enabled Drive API under the Developer Console for the Apps Script project.
function getImageSize(fileID) {
var api = "https://www.googleapis.com/drive/v2/files/" + fileID;
var meta = JSON.parse(UrlFetchApp.fetch(api, {
headers: {
"Authorization": "Bearer " + ScriptApp.getOAuthToken()
}
}).getContentText());
Logger.log(meta.imageMediaMetadata.height);
Logger.log(meta.imageMediaMetadata.width);
}
I have a document that i use as a template, url: https://docs.google.com/document/d/1Ng00Sw0V-3_htLF2-SyPj895g_V9bi1mKQc1LOaHPNY/edit?usp=sharing
I'm using a script when a form is submited and export it to pdf
function testExport() {
var pdf = DocumentApp.openById(docTemplate).getAs("application/pdf");
DriveApp.createFile(pdf);
};
But the exported link looks like https://drive.google.com/file/d/0B_YrT5Ue-LAvUllyQ0ZpbkRodVU/view?usp=sharing
Size of rows between the table seems to increased and the overall quality looks bad, is there a way to fix it? When I download the doc file as pdf the then it looks really good.
Document.getAs() uses a slightly different converter then the Google Docs UI does. You can get closer by using the conversion functionality built into the Drive API, exposed in File.exportLinks. The sample below uses the Drive Advanced Service to do the conversion and save the result.
function exportAsPdf(documentId) {
var file = Drive.Files.get(documentId);
var url = file.exportLinks['application/pdf'];
var token = ScriptApp.getOAuthToken();
var response = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
var contents = response.getBlob();
contents.setName(file.title + '.pdf');
DriveApp.createFile(contents);
}