I want to import an image to Google Slides over Google Apps Script after the instruction Google Developers - How to...
function createImage(presentationId) {
// Add a new image to the presentation page. The image is assumed to exist in
// the user's Drive, and have 'imageFileId' as its file ID.
var requests = [];
var pageId = 'g1fe0c....';
var imageId = 'MyImage_01';
var imageUrl = DriveApp.getFileById('0B6cQESmLJfX...').getUrl();
var emu4M = {
magnitude: 4000000,
unit: 'EMU'
};
requests.push({
createImage: {
objectId: imageId,
url: imageUrl,
elementProperties: {
pageObjectId: pageId,
size: {
height: emu4M,
width: emu4M
},
transform: {
scaleX: 1,
scaleY: 1,
translateX: 100000,
translateY: 100000,
unit: 'EMU'
}
}
}
});
// Execute the request.
var response = Slides.Presentations.batchUpdate({
requests: requests
}, presentationId);
}
But for every image-format I tried, there is an error message in Google Apps Script:
Invalid requests[0].createImage: The provided image is in an
unsupported format.
Drive- and Slides API is activated in Google Advanced Services. The folder and the file has a public share.
Does anyone use the command DriveApp.getFileById() with subsequent export to Google Slides successfully?
How about a following modification?
From :
var imageUrl = DriveApp.getFileById('0B6cQESmLJfX...').getUrl();
To :
var imageUrl = DriveApp.getFileById('0B6cQESmLJfX...').getDownloadUrl() + "&access_token=" + ScriptApp.getOAuthToken();
From this document, it seemed that the access token is required. https://developers.google.com/slides/how-tos/add-image
Updated: February 7, 2020
From January, 2020, the access token cannot be used with the query parameter like access_token=###. Ref So please use the access token to the request header instead of the query parameter.
In OP's case, I think that this answer can be used.
Related
I 'm very new to both Apps Script and coding in general.
I'm trying to take a google slides presentation, and merge with a csv to create multiple images.
I cannot get the merge function to work. I'm pretty sure I am not loading the csv data correctly - I can get it to show the data range in the execution log but it does not merge into the new presentation. I know I have my tags correct, because I've used them in a 3rd party extension and it works.
I know I'm probably just missing something stupid, but I cannot figure it out. Any help would be appreciated!
Below is the code I currently have:
Update 1
I was able to figure out how to call the data correctly, and am now able to replace the text correctly. However, when I use replaceAllShapesWithImage I get the following error:
GoogleJsonResponseException: API call to slides.presentations.batchUpdate failed with error: Invalid requests[2].replaceAllShapesWithImage: There was a problem retrieving the image. The provided image should be publicly accessible, within size limit, and in supported formats.
The images are being called from google drive, and are accessible by anyone with the link. Any ideas? Updated code below:
const spreadsheetId = '1JSXC0XrfUAtcRLXCgVnB-SAQjwk_-YG7W_kGefowONE';
const thetemplateId = '1Pug2cPiGsPL9iKPEnBAhvBVqfSTMyJERCRaSGkyFOr0';
const dataRange = 'Monthly Top Producers!A2:F';
function generateTopPro(){
var Presentation=SlidesApp.openById(thetemplateId);
let values = SpreadsheetApp.openById(spreadsheetId).getRange(dataRange).getValues();
for (let i = 0; i < values.length; ++i) {
const row = values[i];
const agent_name = row[0]; // name in column 1
const agent_phone = row[3]; // phone in column 4
const agent_photo = row[4]; // agent photo url column 5
const logo_state = row[5]; // state logo url column 6
// Duplicate the template presentation using the Drive API.
const copyTitle = agent_name + ' September';
let copyFile = {
title: copyTitle,
parents: [{id: 'root'}]
};
copyFile = Drive.Files.copy(copyFile, templateId);
const presentationCopyId = copyFile.id;
// Create the text merge (replaceAllText) requests for this presentation.
const requests = [{
replaceAllText: {
containsText: {
text: '{{agent_name}}',
matchCase: true
},
replaceText: agent_name
}
}, {
replaceAllText: {
containsText: {
text: '{{agent_phone}}',
matchCase: true
},
replaceText: agent_phone
}
}, {
replaceAllShapesWithImage: {
imageUrl: agent_photo,
imageReplaceMethod: 'CENTER_INSIDE',
containsText: {
text: '{{agent_photo}}',
matchCase: true
}
}
}, {
replaceAllShapesWithImage: {
imageUrl: logo_state,
imageReplaceMethod: 'CENTER_INSIDE',
containsText: {
text: '{{logo_state}}',
matchCase: true
}
}
}];
// Execute the requests for this presentation.
const result = Slides.Presentations.batchUpdate({
requests: requests
}, presentationCopyId);
// Count the total number of replacements made.
let numReplacements = 0;
result.replies.forEach(function(reply) {
numReplacements += reply.replaceAllText.occurrencesChanged;
});
console.log('Created presentation for %s with ID: %s', agent_name, presentationCopyId);
console.log('Replaced %s text instances', numReplacements);
}
}
There was a problem retrieving the image. The provided image should be publicly accessible, within size limit, and in supported formats is a known issue when trying to use an image from Google Drive
See for example Google slides API replaceAllShapesWithImage returns error for Google Drive file (2020)
There are workarounds like Google script replaceAllShapesWithImage with image from drive doesn"t work any more that work for some users/ images but not always.
There are several related issues filed on Google's Issue Tracker and a feature request asking for a full support of the functionality.
If no workaround work for you, the only two things you can do in the current state are:
"Star" the feature request to increase visibility which will hopefully accelerate implementation
Use the thumbnailLink that oyu can retrieve with Files: get as imageUrl - this gives you an image in low quality, but better than nothing
Since yesterday one of my google script doesn't work anymore.
The script
take an image on the drive
copie a slide
replace a shape with an image
But I got this error:
"The provided image is in an unsupported format."
-> I give all access to the image: it doesn't change anything
-> The script work if I take an url outside the drive
Any idea
function test_image(){
var imageUrls = DriveApp.getFilesByName("DSC_3632.png");
var file = "undefined";
while ( imageUrls.hasNext()) {
var file = imageUrls.next();
}
var imageUrl = file.getDownloadUrl() + "&access_token=" + ScriptApp.getOAuthToken();
var model_file = DriveApp.getFileById("your-id");
var presentation = model_file.makeCopy("totot");
var presentation =Slides.Presentations.get(presentation.getId())
var requests = [{
"replaceAllShapesWithImage":
{
"imageUrl": imageUrl,
"imageReplaceMethod": "CENTER_INSIDE",
"containsText": {
"text": "toto",
"matchCase": false,
}
}
}];
var presentationId = presentation.presentationId
var createSlideResponse = Slides.Presentations.batchUpdate({
requests: requests
}, presentationId);
}
How about this answer? Please think of this as just one of several possible answers.
Issue and workaround:
I think that the reason of your issue is due to the following modification of official document.
First, we’re making changes to authorization for the Google Drive API. If you authorize download requests to the Drive API using the access token in a query parameter, you will need to migrate your requests to authenticate using an HTTP header instead. Starting January 1, 2020, download calls to files.get, revisions.get and files.export endpoints which authenticate using the access token in the query parameter will no longer be supported, which means you’ll need to update your authentication method.
By above situation, the URL of var imageUrl = file.getDownloadUrl() + "&access_token=" + ScriptApp.getOAuthToken(); cannot be used. For example, when it accesses to the URL, the login screen is displayed even when the access token is used.
In order to avoid this issue, how about the following modification?
Modification points:
The file is shared publicly and put to Google Slides. Then, the sharing file is closed.
In this case, even when the share of file is closed, the put image on Slides is not removed.
The webContentLink is used as the URL.
It's like https://drive.google.com/uc?export=download&id=###.
Modified script:
When your script is modified, it becomes as follows.
function test_image(){
var imageUrls = DriveApp.getFilesByName("DSC_3632.png");
var file; // Modified
while (imageUrls.hasNext()) {
file = imageUrls.next();
}
file.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW); // Added
var imageUrl = "https://drive.google.com/uc?export=download&id=" + file.getId(); // Modified
var model_file = DriveApp.getFileById("your-id");
var presentation = model_file.makeCopy("totot");
var presentation =Slides.Presentations.get(presentation.getId())
var requests = [{
"replaceAllShapesWithImage": {
"imageUrl": imageUrl,
"imageReplaceMethod": "CENTER_INSIDE",
"containsText": {
"text": "toto",
"matchCase": false,
}
}
}];
var presentationId = presentation.presentationId
var createSlideResponse = Slides.Presentations.batchUpdate({requests: requests}, presentationId);
file.setSharing(DriveApp.Access.PRIVATE, DriveApp.Permission.NONE); // Added
}
References:
Upcoming changes to the Google Drive API and Google Picker API
setSharing()
If I misunderstood your question and this was not the direction you want, I apologize.
Either using rest API, Google Scripts, Node SDK, whatever works.
I'm seeing this in the docs but that doesn't seem to tell me the duration:
function watchFile(fileId, channelId, channelType, channelAddress) {
var resource = {
'id': channelId,
'type': channelType,
'address': channelAddress
};
var request = gapi.client.drive.files.watch({
'fileId': fileId,
'resource': resource
});
request.execute(function(channel){console.log(channel);});
}
I found this link but it doesn't seem to help https://apis-nodejs.firebaseapp.com/drive/classes/Resource$Files.html#watch
You want to retrieve the duration of the video on your Google Drive.
You want to achieve this using Google Apps Script.
If my understanding is correct, how about this sample script? In this modification, I used files.get and files.list methods of Drive API. From your question, I thought that the script that the endpoint is directly requests might be useful for your situation. So I proposed the following script.
1. Using files.get method
In this sample script, the duration is retrieved from a video file.
Sample script:
function sample1() {
var fileId = "###"; // 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);
var obj = JSON.parse(res);
Logger.log("filename: %s, duration: %s seconds", obj.name, obj.videoMediaMetadata.durationMillis / 1000);
// DriveApp.getFiles() // This line is put for automatically detecting the scope (https://www.googleapis.com/auth/drive.readonly) for this script.
}
2. Using files.list method
In this sample script, the durations are retrieved from a folder including the video files.
Sample script:
function sample2() {
var folderId = "###"; // Please set the folder ID including the video files.
var q = "'" + folderId + "' in parents and trashed=false";
var fields = "files(mimeType,name,videoMediaMetadata)"; // duration is included in "videoMediaMetadata"
var url = "https://www.googleapis.com/drive/v3/files?q=" + encodeURIComponent(q) + "&fields=" + encodeURIComponent(fields) + "&access_token=" + ScriptApp.getOAuthToken();
var res = UrlFetchApp.fetch(url);
var obj = JSON.parse(res);
for (var i = 0; i < obj.files.length; i++) {
Logger.log("filename: %s, duration: %s seconds", obj.files[i].name, obj.files[i].videoMediaMetadata.durationMillis / 1000);
}
// DriveApp.getFiles() // This line is put for automatically detecting the scope (https://www.googleapis.com/auth/drive.readonly) for this script.
}
Note:
These are simple sample scripts. So please modify them for your situation.
I'm not sure about the format of your video files. So if above script cannot be used for your situation, I apologize.
References:
Files of Drive API
Class UrlFetchApp
If I misunderstood your question and this was not the result you want, I apologize.
Updated: March 19, 2020
From January, 2020, the access token cannot be used with the query parameter like access_token=###. Ref So please use the access token to the request header instead of the query parameter. It's as follows.
var res = UrlFetchApp.fetch(url, {headers: {Authorization: "Bearer " + ScriptApp.getOAuthToken()}});
I am trying to insert chart to Google Slides presentation using CreateSheetsChartRequest.
Request fails with error:
Execution failed: GoogleJsonResponseException: Invalid value at 'requests[0].create_sheets_chart.chart_id' (TYPE_INT32), "u1935822328711"
Sample code:
var ss = SpreadsheetApp.getActiveSpreadsheet();
var chartSheet = ss.getSheets()[0];
// get chart id via Sheets API
// returns string like 'u1935822328711'
var chartId = chartSheet.getCharts()[0].getId();
var slidesReqs = [];
slidesReqs.push({
createSheetsChart: {
objectId: 'someSlideChartId',
elementProperties: {
pageObjectId: slideId,
size: {
width: {
magnitude: (7/9)*900,
unit: 'PT'
},
height: {
magnitude: (7/9)*560,
unit: 'PT'
}
},
transform: {
scaleX: 1,
scaleY: 1,
translateX: 100000,
translateY: 100000,
unit: 'EMU'
}
},
spreadsheetId: ss.getId(),
chartId: chartId,
linkingMode: 'NOT_LINKED_IMAGE'
}
});
// throws error
// Execution failed: GoogleJsonResponseException: Invalid value at 'requests[0].create_sheets_chart.chart_id' (TYPE_INT32), "u1935822328711"
Slides.Presentations.batchUpdate({'requests': slidesReqs}, presentationFileId);
I see that CreateSheetsChartRequest expects field chartId to be integer, but Google Sheets API returns string like "u1935822328711" for chart id.
How do I get Google Sheets chart inserted to slide?
Short answer
Use getChartId() instead of getId().
Explanation
EmbeddedChart.getId() returns an ID that is only useful in the context of UiApp, a deprecated service for building component-based UIs.
However, as of today, there is now a method on the EmbeddedChart class called getChartId() that returns a unique, stable integer identifying the chart.
If you change the one line in your code to
var chartId = chartSheet.getCharts()[0].getChartId();
your CreateSheetsChartRequest should now work.
Source: https://issuetracker.google.com/issues/79784012#comment2
I have this javascript to extract html table and then pass the arrays to google apps script as parameters.
var CLIENT_ID = 'some ID';
var SCRIPT_ID = 'some ID';
var SCOPES = ['https://www.googleapis.com/auth/drive.file'];
function handleAuthClick(event) {
gapi.auth.authorize(
{'client_id': CLIENT_ID, 'scope': SCOPES, 'immediate': true},
handleAuthResult);
}
function handleAuthResult(authResult) {
if (authResult) {
// Access token has been successfully retrieved, requests can be sent to the API
} else {
// No access token could be retrieved, force the authorization flow.
gapi.auth.authorize(
{'client_id': CLIENT_ID, 'scope': SCOPES, 'immediate': false},
handleAuthResult);
}
}
function exportGsheet() {
var myTableArray = [];
$("table#fin tr").each(function() {
var arrayOfThisRow = [];
var tableData = $(this).find('td');
if (tableData.length > 0) {
tableData.each(function() { arrayOfThisRow.push($(this).text()); });
myTableArray.push(arrayOfThisRow);
}
});
var params = JSON.stringify(myTableArray);
var request = {
'function': 'setData',
'parameters': params,
'devMode': true // Optional.
};
var op = gapi.client.request({
'root': 'https://script.googleapis.com',
'path': 'v1/scripts/' + SCRIPT_ID + ':run',
'method': 'POST',
'body': request
});
op.execute(function(resp){opensheet(resp)});
}
Below is the apps script. This uses Drive API and Executable API.
var DOC_ID = 'some id';
var formattedDate = Utilities.formatDate(new Date(), "GMT", "yyyy-MM-dd'T'HH:mm:ss'Z'");
var folder = DriveApp.getFolderById('some id');
function setData(parameters) {
var getFile = DriveApp.getFileById(DOC_ID);
var file = getFile.makeCopy(formattedDate, folder);
var ss = SpreadsheetApp.open(file);
var ssId = ss.getId();
ss.getSheets()[0].getRange(5,1,50,24).clear();
var e = JSON.parse(parameters);
var outerArray = [];
for(var i = 0; i < e.length; i++) {
outerArray.push(e[i]);
}
ss.getSheets()[0].getRange(5, 2, outerArray.length, outerArray[0].length).setValues(outerArray);
return {"url":ssId};
Logger.log(ssId);
}
Everything works fine when I authorize using the gmail ID that owns the apps script and project (my own gmail account). But when I authenticate using a different gmail account I get the below error:
error: {code: 403, message: "The caller does not have permission", status: "PERMISSION_DENIED"}
code: 403
message: "The caller does not have permission"
status: "PERMISSION_DENIED"
I intend to make this application public and anyone should be able to authenticate using their gmail account and execute the script. How do I do that? Please help.
Folks, I figured out the problem later. It happened to be permission issue n Developer console. We have to assign permission under Developer Console Project for the project which the apps-script is associated. So follow these steps:
Open your apps script Go to Resources-Developers Console Project
Click on the project name appearing in blue under "This script is
currently associated with project:" It will redirect you to Developer
Console Project.
Click on Menu on the left hand side upper corner and click on
Permissions
Under Permissions click on Add members
In the member type the email ID or domain you want to provide
permission and desired permission level. Click on 'Add'
You are done.
However, I wasnt able to add the entire gmail domain, nor able to add allAuthenticatedUsers. I have raised an issue with google support