Get range of google spreadsheet into an image using google script - google-apps-script

I'm building a search tool by which one can convert a google range into an image using google script. I tried to paste that data range to google slides and from there I get thumbnails and their url. I'm searching any other tools that directly give me the url of image of the selected range of a google sheet.
Thanks

This is a very interesting question.
I am unsure of the reasoning behind doing this, but nonetheless, here is an answer:
This creates a custom menu on the top of your sheet that says:
Custom Functions => Export Range to Image Files.
When you click that it:
Turns whatever you have selected into a table in sheets
Saves it
Generates an image from that
Saves image to drive
Show a pop-up with the links of the saved images.
The code is ready to handle multiple ranges being exported, but right now it exports only the selected range.
function onOpen(e) {
//Create custom menu to export range to Slides.
SpreadsheetApp.getUi()
.createMenu('Custom Functions')
.addItem('Export Range to Image Files', 'SelectedRangeToImage')
.addToUi();
}
function SelectedRangeToImage() {
var slide = RangeToSlides();
var slideId = slide.getId();
var images = [];
for (var x=0; x<slide.getSlides().length;x++) {
var image = SlidesToImage(slide.getName()+x, slideId, slide.getSlides()[x].getObjectId());
images.push(image);
}
//Show interface with links to all images
var ui = SpreadsheetApp.getUi();
var html = HtmlService.createHtmlOutput();
html.append("<p>Your images:</p>");
html.append("<ul>");
for (var i=0; i<images.length; i++) {
html.append("<li><a href='"+images[i].getUrl()+"'>"+images[i].getName()+"</a></li>");
}
html.append("</ul>");
html.append("<input type='button' value='Close' onclick='google.script.host.close()' />");
ui.showModalDialog(html, "Exporting results:");
}
function RangeToSlides() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var range = ss.getActiveRange();
var rangeValues = range.getDisplayValues();
var rangeHorizontalAlignments = range.getHorizontalAlignments()
var rangeBackgrounds = range.getBackgrounds();
var rangeFontWeights = range.getFontWeights();
var sl = SlidesApp.create("ExportToImage"+new Date());
var slide = sl.getSlides()[0];
//Create table with size of the range
var table = slide.insertTable(rangeValues.length, rangeValues[0].length);
for (var x=0; x<rangeValues.length; x++) {
for (var y=0; y<rangeValues[x].length; y++) {
var cell = table.getCell(x,y);
cell.getText().setText(rangeValues[x][y]); //Set text
cell.getFill().setSolidFill(rangeBackgrounds[x][y]); //Set background
cell.getText().getTextStyle().setBold(rangeFontWeights[x][y]=="bold"?true:false); //Set text formatting
var alignment;
switch(rangeHorizontalAlignments[x][y]) {
case "general-left":
alignment = SlidesApp.ParagraphAlignment.START;
break;
case "general-right":
alignment = SlidesApp.ParagraphAlignment.END;
break;
case "center":
alignment = SlidesApp.ParagraphAlignment.CENTER;
break;
}
cell.getText().getParagraphStyle().setParagraphAlignment(alignment); //Set text alignment
}
}
sl.saveAndClose();
return sl;
}
function SlidesToImage(name, presentationId, slideId) {
var url = "https://slides.googleapis.com/v1/presentations/"+presentationId+"/pages/"+slideId+"/thumbnail";
var options = {
headers: {
Authorization: 'Bearer ' + ScriptApp.getOAuthToken()
}
};
var response = UrlFetchApp.fetch(url, options);
var responseJson = JSON.parse(response.getContentText());
var imageurl = responseJson.contentUrl;
var imageResponse = UrlFetchApp.fetch(imageurl, options);
var blob = imageResponse.getBlob();
blob.setName(name);
var resultingFile = DriveApp.createFile(blob);
return resultingFile;
}
Hope this helps!
References:
https://stackoverflow.com/a/51391196/11869748
How to download Google Slides as images?
https://developers.google.com/slides/reference/rest/v1/presentations.pages/getThumbnail

Related

Get range of google spreadsheet into an image using google script error

Get range of google spreadsheet into an image using google script
ZektorH wrote a script to save a selected range of cells to google drive as an image. I imported the script and Im able to save images to google drive but only if all the cells in the selected range have text. otherwise I get this error
"Exception: The object (SLIDES_APIxxxxxxxxxx_0) has no text."
Is there a way to avoid having text on all cells? for example on merged cells
function onOpen(e) {
//Create custom menu to export range to Slides.
SpreadsheetApp.getUi()
.createMenu('Custom Functions')
.addItem('Export Range to Image Files', 'SelectedRangeToImage')
.addToUi();
}
function SelectedRangeToImage() {
var slide = RangeToSlides();
var slideId = slide.getId();
var images = [];
for (var x=0; x<slide.getSlides().length;x++) {
var image = SlidesToImage(slide.getName()+x, slideId, slide.getSlides()[x].getObjectId());
images.push(image);
}
//Show interface with links to all images
var ui = SpreadsheetApp.getUi();
var html = HtmlService.createHtmlOutput();
html.append("<p>Your images:</p>");
html.append("<ul>");
for (var i=0; i<images.length; i++) {
html.append("<li><a href='"+images[i].getUrl()+"'>"+images[i].getName()+"</a></li>");
}
html.append("</ul>");
html.append("<input type='button' value='Close' onclick='google.script.host.close()' />");
ui.showModalDialog(html, "Exporting results:");
}
function RangeToSlides() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var range = ss.getActiveRange();
var rangeValues = range.getDisplayValues();
var rangeHorizontalAlignments = range.getHorizontalAlignments()
var rangeBackgrounds = range.getBackgrounds();
var rangeFontWeights = range.getFontWeights();
var sl = SlidesApp.create("ExportToImage"+new Date());
var slide = sl.getSlides()[0];
//Create table with size of the range
var table = slide.insertTable(rangeValues.length, rangeValues[0].length);
for (var x=0; x<rangeValues.length; x++) {
for (var y=0; y<rangeValues[x].length; y++) {
var cell = table.getCell(x,y);
cell.getText().setText(rangeValues[x][y]); //Set text
cell.getFill().setSolidFill(rangeBackgrounds[x][y]); //Set background
cell.getText().getTextStyle().setBold(rangeFontWeights[x][y]=="bold"?true:false); //Set text formatting
var alignment;
switch(rangeHorizontalAlignments[x][y]) {
case "general-left":
alignment = SlidesApp.ParagraphAlignment.START;
break;
case "general-right":
alignment = SlidesApp.ParagraphAlignment.END;
break;
case "center":
alignment = SlidesApp.ParagraphAlignment.CENTER;
break;
}
cell.getText().getParagraphStyle().setParagraphAlignment(alignment); //Set text alignment
}
}
sl.saveAndClose();
return sl;
}
function SlidesToImage(name, presentationId, slideId) {
var url = "https://slides.googleapis.com/v1/presentations/"+presentationId+"/pages/"+slideId+"/thumbnail";
var options = {
headers: {
Authorization: 'Bearer ' + ScriptApp.getOAuthToken()
}
};
var response = UrlFetchApp.fetch(url, options);
var responseJson = JSON.parse(response.getContentText());
var imageurl = responseJson.contentUrl;
var imageResponse = UrlFetchApp.fetch(imageurl, options);
var blob = imageResponse.getBlob();
blob.setName(name);
var resultingFile = DriveApp.createFile(blob);
return resultingFile;
}
ZektorH script below

Get the hyperlink and its text value using google docs

I hope everyone is in good health.
My main goal
So main goal was to get the hyperlink and the text linked with it. I initially used code as below :
var ekArr = [];
function myFunction() {
var doc= DocumentApp.getActiveDocument();
var isCell4Blank1 = doc.getBlob().getDataAsString();
var data = Utilities.parseCsv(isCell4Blank1);
var linku = doc.getBody().getTables()[0].getCell(2,1);
var t = doc.getBody().getTables()[0].getCell(2,1).getText();
Logger.log("link is. " + linku);
// Logger.log(doc.getBody().getText());
for(var find in data){
var fi = data[find].toString().includes("http");
if(fi===true){
var newArr = data[find].toString().split(" ");
var output = newArr[1].replace("(","").replace(")","").replace(">>>>","")
ekArr.push(output);
}
}
var tex = doc.getBody().getText();
var fo = tex.split(ekArr[0]);
Logger.log(tex);
doc.getBody().getTables()[0].getCell(2,2).setText(ekArr);
doc.getBody().getTables()[0].getCell(2,3).setText(t);
Logger.log(ekArr);
return ekArr;
}
I need to extract the links and content from the cells of a table.
From above code I am able to extract the links however I am not able to extract the text linked with it.
Also I have another code which helped me to extract the links and text but from googlesheets. As I am new to google docs I want to modify the below code according to google docs.
function sheetFunction() {
var sheet= SpreadsheetApp.getActiveSheet();
var isCell4Blank1 = sheet.getRange("A1").isBlank();
if (!isCell4Blank1) {
var linkData =
sheet.getRange("A1").getRichTextValue().getRuns().reduce((ar, e) => {
var url = e.getLinkUrl();
Logger.log(url);
if (url) {
var color = e.getTextStyle().getForegroundColor();
var startIndex = e.getStartIndex();
var endIndex = e.getEndIndex();
var text = e.getText()
ar.push(color);
ar.push(text);
ar.push(startIndex);
ar.push(endIndex);
ar.push(url);
}
return ar;
}, [])
}
Use the methods getText() and getLinkUrl()
Sample based on your first code snippet:
function myFunction() {
var doc = DocumentApp.getActiveDocument();
var linku = doc.getBody().getTables()[0].getCell(2,1);
Logger.log("link text is: " + linku.getText());
Logger.log("link is: " + linku.getLinkUrl());
}

Google sheets OCR image at URL in Col1, output text in Col2?

in a Google Sheet, I'm trying to use a function to OCR an image whose URL is in column A, and output the OCR text in column B. The code I'm attempting to use is from this thread:
ocr images from list of urls and store the results in spreadsheet
function onOpen() {
var ss = SpreadsheetApp.getActive();
var menuItems = [
{name: 'RUN', functionName: 'doGet2'}
];
ss.addMenu('OCR', menuItems);
}
function doGet2() {
var ROW_START = 3;
var URL_COL = 1;
var TEXT_COL = 2;
var ss = SpreadsheetApp.getActive();
var sheet = ss.getActiveSheet();
var urls = sheet.getRange(ROW_START,URL_COL, sheet.getLastRow()-ROW_START+1,1).getValues();
var texts = [];
for(var i=0; i<urls.length; i++) {
var url = urls[i];
if(url != undefined && url != "") {
var imageBlob = UrlFetchApp.fetch(url).getBlob();
var resource = {
title: imageBlob.getName(),
mimeType: imageBlob.getContentType()
};
var options = {
ocr: true
};
var docFile = Drive.Files.insert(resource, imageBlob, options);
var doc = DocumentApp.openById(docFile.id);
var text = doc.getBody().getText().replace("\n", "");
texts.push([text]);
Drive.Files.remove(docFile.id);
}
else {
texts.push("request error");
}
}
sheet.getRange(ROW_START,TEXT_COL, urls.length,1).setValues(texts);
}
Here is the Google Sheet I'm testing with. Anyone can edit:
https://docs.google.com/spreadsheets/d/1jhSmE295bTOzjoXmgcyymNi-6ylKg5PLEKktPZJTD1c/edit?usp=sharing
I think the original code is meant to pull from Google Drive. I don't need that, I just want to pull from a URL. Being able to use the function inside an arrayformula would be a plus.
Thanks!

CopyTo Method doesn't capture the Alt Text Titles from my Spreadsheet using Apps Script

I have a code that deletes sheet and copies sheet from another Spreadsheet to another. However, the source spreadsheet I have copied contains an images with Alt Text titles on it. When I tried to copy it to my destination file, the Alt Text titles are not captured.
Any thoughts on how to fix this? Thanks
function deleteAndReplaceSheet() {
var masterConfigSheetId = 'xxxxxxx';
var replicatedCardsFolderId = 'xxxxxxx';
var masterSheetName = 'Mastersheet'
var cardSheetName = "Card";
var ss = SpreadsheetApp.openById(masterConfigSheetId);
var masterSheetReference = ss.getSheetByName(masterSheetName);
var replicatedCards = DriveApp.getFolderById(replicatedCardsFolderId).getFiles();
var employeeNumbers = masterSheetReference.getRange("A2:A").getValues();
var employeeNumbersTrunc = [];
for(var i = 0; i < employeeNumbers.length; i++){
if(employeeNumbers[i][0] != "")
employeeNumbersTrunc.push("" + employeeNumbers[i][0]);
// Logger.log(employeeNumbersTrunc);
}
while (replicatedCards.hasNext()) {
var file = replicatedCards.next();
// Logger.log(file);
//check if employee number is existing inside the gdrive folder
if (employeeNumbersTrunc.indexOf(file.getName())==-1) {
continue;
}
try {
var activeSpreadSheet = SpreadsheetApp.open(file);
var destination = SpreadsheetApp.openById(file.getId());
var source = SpreadsheetApp.openById('xxxxxxx');
var sheet = source.getSheets()[0];
var toBeDeletedSheet = activeSpreadSheet.getSheetByName('Card');
//delete card sheetname
activeSpreadSheet.deleteSheet(toBeDeletedSheet);
sheet.copyTo(destination).setName('Card');
destination.moveActiveSheet(2);
} catch(err) {
}
}
}
Unfortunately, what you are trying to do is not possible. Since inserting images in cells is still a new feature in Google Sheets, the .copyTo() method doesn't support copying the Alt Text Titles.
I suggest you file a feature request at Google Issue Tracker at this link.

Changing the colour of a template Slide using app script

I have a created a slide template in which multiple teams will use to use to create an information sheet about their respective Process. This content is intended to be produced in a standardised way.
To make things easier I have created a sheet in which key information can be input into cells to populate elements of the template.
The issue I'm having is I want each process to have a different colour scheme. Is there a way I can set a cell to the desired font or background colour in sheets and then get the template to create in that colour? or even a colour scheme?
How do I single out certain text or text boxes of the slide to set the background colour?
Desired Solution
Any help is much appreciated
// Add a custom menu to the active spreadsheet, including a separator and a sub-menu.
function onOpen(e) {
SpreadsheetApp.getUi()
.createMenu('Templates')
.addItem('Cheat Sheet', 'createNewCase')
.addToUi();
}
function createNewCase(input) {
var category = input
var ui = SpreadsheetApp.getUi();
// get active spreadsheet
var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var activeSheet = activeSpreadsheet.getActiveSheet();
// Check to ensure script being run from 'Option 1' sheet
if (activeSheet.getName() != "Sheet1") {
ui.alert("Active sheet must be 'Sheet1', terminating script");
return;
}
//Get active cell
var sourceRow = activeSheet.getActiveCell().getRow();
// Read case variables
var sourceProcess = activeSheet.getRange('A' + sourceRow).getValue();
var sourceName1 = activeSheet.getRange('B' + sourceRow).getValue();
var sourceName2 = activeSheet.getRange('C' + sourceRow).getValue();
var sourceTeam = activeSheet.getRange('D' + sourceRow).getValue();
var sourcePurpose = activeSheet.getRange('E' + sourceRow).getValue();
var sourceDef = activeSheet.getRange('F' + sourceRow).getValue();
var sourceColor = activeSheet.getRange('G' + sourceRow).getFontColor();
// Message prompt
var userChoice = ui.alert("You are about to generate a Cheat Sheet template for " + sourceProcess +"\n\nDo you wish to continue?\n\n",ui.ButtonSet.YES_NO);
if (userChoice == ui.Button.NO) {
ui.alert("Terminating script");
return;
}
//Set case document filename
var newFilename = sourceProcess + "Process Cheat Sheet"
//Get template folder
var templateFolder = DriveApp.getFolderById("1MCQn9_oiaaUt4_dNzr2EoDWkUGsYOH-O");
// Get case Template document
var docTemplate = DriveApp.getFileById("1cmm1ifvfRv7omGVmRhD0zunCngBcIY_qo2jpCA_sHV4");
var caseDocument = docTemplate.makeCopy(newFilename);
var caseDocumentID = caseDocument.getId();
var caseSlide = SlidesApp.openById(caseDocumentID);
var caseName1 = caseSlide.replaceAllText("%NAME1%", sourceName1);
var caseName2 = caseSlide.replaceAllText("%NAME2%", sourceName2);
var caseProcess = caseSlide.replaceAllText("%PROCESS%", sourceProcess);
var caseTeam = caseSlide.replaceAllText("%TEAM%", sourceTeam);
var casePurpose = caseSlide.replaceAllText("%PURPOSE%", sourcePurpose);
var caseDef = caseSlide.replaceAllText("%DEFINITION%", sourceDef);
// Record Case Document link
activeSheet.getRange('H' + (sourceRow)).setFormula('=HYPERLINK("' + caseDocument.getUrl() + '", "Cheat Sheet Template")');
}