Google Sheets Hide Images When Hiding Rows - google-apps-script

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

Related

Is it possible to insert a Bookmark in Google Docs to a Table Cell/Table/Text via Google Apps Script?

Is it possible to insert a Bookmark at a table cell or text in Google Docs using Google Apps Script by e.g. specifying the table cell? From the documentation I understand that you need the absolute position which is bound to the cursor. What if I want to set Bookmarks at specified tables automatically. Is that not possible? Here the URL of the documentation:
https://developers.google.com/apps-script/reference/document/bookmark
And if so is it possible to link the inserted bookmark with a table cell using Google Apps Script?
To add a bookmark without using cursors, you can do it via Position class. Since getCursor returns Position, we need to find other methods that returns the same, and that is newPosition which only requires the element and offset (if needed). See code below:
Sample:
Script:
function myFunction() {
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
// find the text element
var textElement = body.findText("<HERE>").getElement();
// create position using the element
var position = doc.newPosition(textElement, 0)
// addBookmark using the created position
doc.addBookmark(position);
}
Output:
Note:
For other objects, it should be doable as long as you can get the element and use it to get their positions.
Reference:
newPosition

How do i add a comment to a particular google slide using app script

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

Google Apps Script getText + replaceText from text box inside drawing in Google Docs Impossible?

I'm trying to edit an Avery template in google docs and populate it with information form a google sheet Via Google Apps Script.
I already body.replaceText to replace the placeholder text in the doc:
for (var i in data) {
var row = data[i];
var docid = DriveApp.getFileById(templateid).makeCopy().getId();
var doc = DocumentApp.openById(docid);
var body = doc.getActiveSection();
body.replaceText("%NAME%", row[0]);
body.replaceText("%ADD_LN1%", row[1]);
body.replaceText("%ADD_LN2%", row[2]);
The label template is a table with a drawing oval in each segment and I have inserted a text box inside the The problem i'm having that I have a text box inside the oval drawings in the doc (I need the oval drawings to know where the labels will print)
The placeholder text inside the drawing will not change when I run my script, but any test inside the table or on the page normally will change to the Google sheets information.
Here is the label template I am using: Label Page
I have placed the %NAME& tag in the header, on the image and on the image that is formatted to freeze in place on page (Just in case that changes anything!)
Purpose: I have a google sheet populated with customer name address and custom choices (specific safety information to print onto a label)
I then have this script insert the info into the label doc, then i can print it without having to create them from scratch every time manually.
If there isn't a way to get text / replace text that is within drawing-shape-text, is there a way I can use the circular shape as a table of as guidelines so that I can transfer across the data as standard?
If you need any more info please let me know, I'm very green and very confused.
Thank you in advance for anyone taking the time to read through this!
Unfortunately, in the current stage, there are not methods for directly modifying the texts in the drawing in the methods of Google Apps Script.
From user - Tannaike
Google slides has the function I was looking for.

Insert Image by URL Doesn't Work in Google Apps Script

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);

How can I set an image title and description when inserting an image into a Google slide using Google 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)