I'm trying to create a function which erases everything in a Google Document.
My code so far, which goes as follows, gets rid of everything, except for positioned images.
// clears document
function eraseContent(){
var body = DocumentApp.getActiveDocument().getBody();
body.clear();
// Remove all images in the document body.
var imgs = body.getImages();
for (var i = 0; i < imgs.length; i++) {
imgs[i].removeFromParent();
}
}
Most of this code comes from here.
What can I do to erase positioned images from my document?
In the current stage, unfortunately, there are no methods for deleting the positioned images in Class PositionedImage, yet. But when Google Docs API is used, the positioned images can be deleted. So how about this modification? The flow of this modified script is as follows.
Retrieve paragraphs.
Retrieve the object IDs of the positioned images.
Create request body for the method of batchUpdate in Google Docs API using the retrieved object IDs.
Delete the positioned images.
In order to use the sample script, before you run the script, please enable Google Docs API at Advanced Google Services and API console as follows.
Enable Google Docs API at Advanced Google Services
On script editor
Resources -> Advanced Google Services
Turn on Google Docs API v1
Enable Google Docs API at API console
On script editor
Resources -> Cloud Platform project
View API console
At Getting started, click "Explore and enable APIs".
At left side, click Library.
At "Search for APIs & services", input "Docs". And click "Google Docs API".
Click Enable button.
If API has already been enabled, please don't turn off.
Modified script:
Please replace eraseContent() as follows and run it.
function eraseContent(){
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
body.clear();
// Retrieve paragraphs.
var paragraphs = body.getParagraphs();
// Retrieve the object IDs of the positioned images.
// Create request body for the method of batchUpdate in Google Docs API using the retrieved object IDs.
var requests = paragraphs.reduce(function(ar, e) {
return ar.concat(e.getPositionedImages().map(function(f) {
return {deletePositionedObject: {objectId: f.getId()}}
}));
}, []);
// Delete the positioned images.
if (requests.length > 0) {
Docs.Documents.batchUpdate({requests: requests}, doc.getId());
}
}
References:
Class PositionedImage
Google Docs API
DeletePositionedObjectRequest
If I misunderstood your question, I apologize.
Related
Recently Google added this cool feature: Pageless Docs.
I would like to activate it on all my documents.
However I cannot find the Property/Method to activate it.
The code should be something like:
var files = DriveApp.getFilesByType("application/vnd.google-apps.document");
while (files.hasNext()) {
var file = files.next();
var doc = DocumentApp.openByUrl(file.getUrl());
var body = doc.getBody();
// set documet as Pageless ¿?
doc.saveAndClose();
}
}
As other Google Documents features, like setting tab stops, setting the pageless mode programmatically to a Google Document it's not yet possible. Send a feature request though the Google Apps Script issue tracker and keep an eye to the Release Notes.
Related
Is it possible to get or set the position of tab-stops (left, center or right ones)?
I have a google slide desk with three slides & i want to add a comment to each slide. I am able to reach to the slide using for loop (total rows in sheet is same as total number of slides, and slide i am using is the second slide onwards. so there is no problem with my loop)
// open the slide using slide id
var s=SlidesApp.openById(a.getId())
for(let r=2; r<=4; r++){
// get the current slide
var currentSlide=s.getSlides()[r-1];
var fileId = currentSlide.getObjectId();
var slideUrl = a.getUrl()+"#slide=id."+fileId;
var slideId = getIdFromUrl(slideUrl);
var comment = {'content':'hi'};
Drive.Comments.insert(comment, slideId);
}
function getIdFromUrl(url) { return url.match(/[-\w]{25,}/); }
This code works but its adding the comment to the file and not to the individual slide. (*Note - For this code to work, we have to enable Drive in services in app script.) How can i add the comment to the individual slides.
Answer:
Not possible.
Explanation:
It is currently not possible to add comments to a specific location in Google Documents (including Docs, Sheets, Slides). The ability for adding anchored comments refers to non-Google Docs (e.g. images, PDFs) (listen to this video for more details).
Therefore, you can only add comments unanchored comments, belonging to the whole file.
What's possible is responding to a located comment by retrieving its id and calling Replies: create.
Issue Tracker:
There are several feature requests for this in Issue Tracker, either about all of Google Docs editors or about a specific editor:
Provide read/write access to comments in Google Docs
Ability to create comments in specific cells/ranges and assign them to someone
Provide ability to create a Drive API Comment anchor resource as method on DocumentApp selection class
I'd suggest you to subscribe to some or all of these issues by starring them and/or file a new feature request to tackle Slides specifically.
Related questions:
Creating anchored comments programmatically in Google Docs
Google Drive API ignores anchor parameter when creating comments in a spreadsheet
How to match comments on an image using kix anchor (or not) in Google Docs
One of the responses in a Google Forms that I created is uploading an image, which gets saved in my Google Drive along with the URL in the linked spreadsheet. In Google slides I have created an Apps Script and successfully able to create slides for each row/entry along with text from that row, from the spreadsheet, but are having difficulty trying to insert an image using by URL. At run time I get the exception thrown "The image at URL ... could not be retrieved. Please make sure the image is valid and publicly accessible." I also get the same error when I manually try to insert the image by URL via the menu bar. All folders and files in my drive are not restricted, so any one on the internet can view the image with this link. And I have tested that out both in my browser and others and it successfully opens the image, but not in Slides.
I must be missing something, but can't figure it out.
Here is some code I am using from the function, but not including the reference to the spreadsheet. Have tried adding '/edit', '/view' to the end of the URL as well, but with same results. Logger does shows the URL is being grabbed from the sheet.
function CreateSlides() {
var deck = SlidesApp.getActivePresentation();
var a = 2; // data begins in second row in spreadsheet
while (sheet.getRange(a,2,1,1).getValue() != "") {
//Insert new slide if not first slide
if (a != 2) {
slide = deck.insertSlide(a-2,SlidesApp.PredefinedLayout.BLANK); //add new slide
} else {
slide = deck.getSlides()[0]; //get first slide
}
// Insert image of painting
Logger.log(sheet.getRange(paintingURLCol + a).getValue());
var picture = slide.insertImage(sheet.getRange(paintingURLCol + a).getValue() + '/view');
// Edit picture size and position
// Increment counter to next row in sheet
a++;
}
}
The URLs logged by Google Form by upload question type can't be used with methods like insertImage(URL) because those URLs aren't supported. Instead you should use:
https://drive.google.com/uc?id=DRIVE_FILE_ID
The above becase the URLs logged to the spreadsheet points to a page with the image embedded not to the actual image file.
Related
Inserting a Google Drive image into a document using Google Apps Script
Display Images from Google Drive folder
How do I script a photo from Google Form upload and set its size to 1 inch for display in a template?
Thanks Rubén. And that's what I actually did and it solved the issue. Here is the sample code that I used for the solution.
var fileURL = sheet.getRange(paintingURLCol + a).getValue();
var fileID = fileURL.substr(fileURL.search("=")+1); //strip off text before id= in the URL
var file = DriveApp.getFileById(fileID);
slide.insertImage(file);
I have been trying to figure out a way to hide an image in google sheets when I am hiding rows that include the image.
The image is a button that has a script attached to it, which means that I cannot just use the =IMAGE() formula, and cannot use an image inside of a cell either.
The problem is that when I hide rows the image stays. Is there any way to get around this?
Answer:
Unfortunately, there is no way of doing this.
More Information:
Images in a Google Sheet that are not inserted using the =IMAGE() formula, nor by inserting the image directly in a cell, are represented by an OverGridImage object in Google Apps Script.
As you can see in the documentation for this class, there exists no method which allows you to hide the image, other than deleting it altogether.
The reason that hiding cells/rows/columns does not hide the image either, is because the image is not tied to any indvidual cell, row or column - it is inserted over the grid system of a specific sheet.
A Mix of Both Good and Bad News:
Now, in theory, what you could do instead, is store the information about the image in the script properties, and then delete/insert the image again when you wish to hide it.
Unfortunately, it appears that the .getUrl() method of the aforementioned OverGridImage class is bugged and does not return the URL of the image - this is something that I have checked myself.
In this case, I would suggest going to the issue link for this bug and hit the ☆ next to the issue number in the top left to let Google know that more people need this to be seen to.
I would also suggest filing a Feature Request with Google here, detailing that you would like to see the showing and hiding of overlay images implemented in Google Apps Script. The above link is directly for Apps Script feature requests.
And for future readers: If you are encountering this, and the .getUrl() method has been fixed, then you can use the following functions as a workaround to show and hide images. This uses PropertiesService to save the image data into the script's properties, and then uses them to re-insert the image after deletion.
function hideImage() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var image = ss.getImages(); // assuming this is the only image
var url = image[0].getUrl();
var col = image[0].getAnchorCell().getColumn();
var row = image[0].getAnchorCell().getRow();
var xOffset = image[0].getAnchorCellXOffset();
var yOffset = image[0].getAnchorCellYOffset();
var details = [url, col, row, xOffset, yOffset];
console.log(details);
PropertiesService.getScriptProperties().setProperty("image", details.toString());
image[0].remove();
}
function showImage() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var details = PropertiesService.getScriptProperties().getProperty("image").split(",");
// change for your sheet name
ss.getSheetByName("Sheet1")
.insertImage(details[0], details[1], details[2], details[3], details[4])
}
References:
Class OverGridImage | Apps Script | Google Developers
OverTheGrid Image getUrl() seems to not working - Google Issue Tracker
Google Apps Script Feature Request Form - Google Issue Tracker
Class PropertiesService | Apps Script | Google Developers
insertImage(url, column, row, offsetX, offsetY) - Class Spreadsheet | Apps Script
Background
I have looked through the Google API for images and there are two methods I'm interested in using getDescription() and getTitle(). Both of these method appear in the autofill in my appscript, and both seem to work.
Problem
I cannot find a method to set the description and title of an image when inserting a an image into a Google slide.
This is the method for inserting an image, but there is not argument for a title or description.
currentPage.insertImage(imageUrl, left, top, width, height)
Question
How can I set an image title and description when inserting an image into a Google slide using Google Apps Script?
Although I'm not sure whether this workaround is useful for your situation, how about this answer? I always use for adding the title and description using Slides API, because I couldn't find the methods in SlidesApp. The sample script is as follows. In this case, I used batchUpdate of Slides API.
Sample script :
var id = currentPage.insertImage(imageUrl, left, top, width, height).getObjectId();
SlidesApp.getActivePresentation().saveAndClose(); // Important
var resource = {"requests": [
{"updatePageElementAltText": {
"objectId": id,
"description": "sampleDescription",
"title": "sampleTitle"
}
}]};
Slides.Presentations.batchUpdate(resource, presentationId);
var fields = {fields: "pageElements(description,objectId,title)"};
var ele = Slides.Presentations.Pages.get(presentationId, currentPage.getObjectId(), fields).pageElements;
ele.forEach(function(e){
if (e.objectId == id) {
Logger.log(e)
}
});
Note :
When you use this script
Please enable Slides API at advanced Google services and API console.
Please prepare presentationId and currentPage.
Please use saveAndClose() after the image is inserted.
Reference :
presentations.batchUpdate
Updated at November 20, 2018:
The Slides service was updated at Google's update at November 14, 2018, and several methods were added for achieving this issue.
new methods let you add alt titles and alt descriptions to page elements. The following methods have been added to the Group, Image, Line, PageElement, Shape, SheetsChart, Table, Video, and WordArt classes
setDescription(description)
setTitle(title)