Export images from Google Sheets - google-apps-script

I have a Google Sheets sheet that creates QR images from the Google charts API using the IMAGE function that takes a URL to encode as an argument. I would like to export the created images to an image file, say a JPG. Problem is Sheets does not recognize the cell content as an image so SHIFT + Right click does not show the Save Image As in the context menu. Any ideas on how to export all of these to separate files.

Download the sheet in Microsoft Excel .xlsx format by going to the File > Download menu.
Then open the .xlsx file in your computer using any unzip program (e.g. 7z) and navigate to ../xl/media in the zip file. All the images would be there - extract where you want them.

This will fit your needs:
Tools -> Script editor
Clear the little code you see
Paste the code from below
Change sheetname (now Data) to your needs
sheet.getRange(2,1, ..... This assumes your images starting at row 2 in the first column (A). Change this to fit your needs.
Changed the folder id to the folder you want the images. (found in url)
Hit run -> Give permission (once)
Look at the folder.
The script:
function isImageToImage(){
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheetByName('Data');
const formulas = sheet.getRange(2,1, sheet.getLastRow()-1).getFormulas().flat();
const urls = formulas.map(formula => {
return /\"(.*?)\"/gmi.exec(formula)[1]
})
const folder = DriveApp.getFolderById('1QVo_pr_Wo6xxxxxxxxx9Yx')
urls.forEach(url => {
console.log(url)
const blob = UrlFetchApp.fetch(url).getBlob();
folder.createFile(blob)
})
}

Related

With Google script, Insert 4:3 image into Google Slide of 16:9 ratio, then export it as PNG file

With Google Apps script I'm trying to automate the process of inserting 4:3 image file (in Google Drive) into an empty slide of 16:9 ratio, aligning the image to the centre, then export the slide as PNG file.
I encountered the issue that the exported PNG file is still an empty slide and missing the inserted image.
Is there something wrong with my code?
Slides API enabled.
Please see below the code I have written so far:
const file = DriveApp.openById(#####);
const presentation1 = SlidesApp.openById(######);
var slide = presentation1.getSlides()[0];
var image = slide.insertImage(file);
image.alignOnPage(SlidesApp.AlignmentPosition.HORIZONTAL_CENTER);
var url = Slides.Presentations.Pages.getThumbnail(pptImageConverterId, slide.getObjectId(), {
"thumbnailProperties.mimeType": "PNG"
}).contentUrl;
var blob = UrlFetchApp.fetch(url).getAs('image/png');
folder.createFile(blob.setName("Slide1.png"));
I believe your goal is as follows.
You want to remove your issue of I encountered the issue that the exported PNG file is still an empty slide and missing the inserted image.. This is your question.
Modification points:
In your script, pptImageConverterId and folder are not declared. pptImageConverterId is the same with ###### of SlidesApp.openById(######);?
DriveApp.openById(#####); is not correct. Is that DriveApp.getFileById("###");?
About aligning the image to the centre, in this case, I thought that you might have wanted SlidesApp.AlignmentPosition.CENTER instead of SlidesApp.AlignmentPosition.HORIZONTAL_CENTER.
But, you say I encountered the issue that the exported PNG file is still an empty slide and missing the inserted image.. So, I'm worried that you might have miscopied your script.
When I saw your script, if the above points are modified, I thought that the reason for your issue is due to that saveAndClose() is not used. When these are reflected in your script, it becomes as follows.
Modified script:
Please set pptImageConverterId, fileId, and folderId.
function myFunction() {
const pptImageConverterId = "###"; // Please set your Google Slides ID.
const fileId = "###"; // Please set the file ID of the image you want to use.
const folderId = "###"; // Please set the folder ID you want to use.
const file = DriveApp.getFileById(fileId);
const presentation1 = SlidesApp.openById(pptImageConverterId);
var slide = presentation1.getSlides()[0];
var image = slide.insertImage(file);
image.alignOnPage(SlidesApp.AlignmentPosition.CENTER);
presentation1.saveAndClose();
var url = Slides.Presentations.Pages.getThumbnail(pptImageConverterId, slide.getObjectId(), {
"thumbnailProperties.mimeType": "PNG"
}).contentUrl;
var blob = UrlFetchApp.fetch(url).getBlob();
DriveApp.getFolderById(folderId).createFile(blob.setName("Slide1.png"));
}
When this script is run, an image is put to the 1st slide of the Google Slides, and the slide is exported as a PNG file.
References:
getFileById(id)
saveAndClose()

Appscript to get hyperlink to another google sheet

I am looking for a code that will help me to find the hyperlink of another google sheet on my google drive, everything i have read explains how to get the link for the active sheet..
any ideas?
Thanks a lot
You need to use DriveApp with functions getFilesByName or getFilesByType. Then provide file id to SpreadsheetApp.openById.
This look will give you the hyperlink to every sheet in a spreadsheet
SpreadsheetApp.openById(file.getId()).getSheets().forEach(s =>
tree.txt.push([ `=HYPERLINK("https://docs.google.com/spreadsheets/d/${file.getId()}/edit#gid=${s.getSheetId()}","${s.getName()}")`]));
It generates a column. It's just a fragment of a piece of code
I have something a bit more simple to apply. The code below goes into the Drive folder and list down every file (doc/sheets/pdf etc) and its hyperlink.
All you will need to change is your tab name to store the folder details and your Gdrive folder ID.
If you want to extract folders within a folder in the future you can switch getFiles() to getFolders().
function folderitems(){
const ss=SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet 1'); //Edit tab name to list the folder details
const parentFolder=DriveApp.getFolderById('INPUT FOLDER ID HERE'); //Input Gdrive ID here
const contents=parentFolder.getFiles();
ss.appendRow(['name','link']);
while (contents.hasNext()){
var file = contents.next();
var name=file.getName();
var link=file.getUrl();
ss.appendRow([name,link]);
}
}
Outcome should look something like this.
To retrieve the URL of one spreadsheet by script
function getFileUrl() {
var nameOfFile = 'your file name'
var files = DriveApp.getFilesByName(nameOfFile);
while (files.hasNext()) {
var file = files.next();
console.log (file.getUrl())
}
}

Getting image url in google script

Trying to get image url in google script.
couldn’t find any function that is able to get the url from images that are not in a specific cell, images are located above the grid.
any ideas?
Issue and workaround:
On October 30, 2018, in order to manage the images on the cells in Spreadsheet, a new Class of OverGridImage has been added. Ref By this, the images on the cells got to be able to be managed. This class has the method of getUrl. The official document of this method says as follows.
Gets the image's source URL; returns null if the URL is unavailable. If the image was inserted by URL using an API, this method returns the URL provided during image insertion.
Namely, for example, when the following script is run, the URL of the image can be retrieved.
function sample1() {
const sheet = SpreadsheetApp.getActiveSheet();
// Put image from URL.
sheet.insertImage("https://stackoverflow.design/assets/img/logos/so/logo-stackoverflow.png", 1, 1);
// Retrieve image URL.
const images = sheet.getImages();
const url = images[0].getUrl();
console.log(url)
}
In your actual situation, if your images are put on the cells using the above script, the URLs can be retrieved by the above simple script. But, here, there is an important point. After the image was put using this script, when you manually move the image, the URL cannot be retrieved. I think that this is a bug.
And also, if you had manually put the images from the URL and your drive, unfortunately, the URL of the images cannot be retrieved. About this, it has already been reported to the Google issue tracker. Ref
If you had manually put the images from the URL and your drive, and when you want to retrieve the URLs of the images, it is required to use a workaround. In this case, I would like to propose to use this method of this answer. In this answer, my created Google Apps Script library is used.
Usage:
1. Install Google Apps Script library.
You can see the method for installing this library at here.
2. Enable Drive API.
In this case, Drive API is used. So, please enable Drive API at Advanced Google services.
3. Sample script.
function sample2() {
const sheetName = "Sheet1"; // Please set the sheet name.
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheetByName(sheetName);
const images = sheet.getImages();
const obj = images.reduce((o, e) => {
const u = e.getUrl();
if (u) o[e.getAnchorCell().getA1Notation()] = u;
return o;
}, {});
const res = DocsServiceApp.openBySpreadsheetId(ss.getId()).getSheetByName(sheetName).getImages();
if (res.length == 0) return;
const urls = res.map(({ image, range }, i) => {
if (obj[range.a1Notation]) return obj[range.a1Notation];
const o = Drive.Files.insert({ title: `sample${i + 1}` }, image.blob);
const url = o.thumbnailLink.replace(/\=s\d+/, "=s1000");
DriveApp.getFileById(o.id).setTrashed(true);
return url;
});
console.log(urls)
}
4. Testing.
When the above script is run, the images are retrieved from "Sheet1" and retrieve the URLs of the images. For example, when there are images put with the image URL using the script, the URL can be retrieved.
Note:
In this workaround, in order to retrieve the URL of the image, the thumbnail link is used. This link is not permanent. Please be careful about this. If you are required to retrieve the permanent link, please create the retrieved image file blob as the file, and please publicly share them, and then, please retrieve the WebContentLink. By this, you can retrieve the permanent link of the image.
References:
DocsServiceApp
Related thread
How to access new 'in-cell-image' from google apps script?

Is there anyway to download current slide in Google Slides with the AppScript?

I'd like to download the current page open in google slides as pdf.
Google Slides allows in their own UI to download the whole presentation as PDF but I am interested in downloading slides in the presentation one by one.
Right now I am able to select current page with,
export const getCurrentPage = () => {
return SlidesApp.getActivePresentation()
.getSelection()
.getCurrentPage();
};
This function returns a Page Class.
The problem is I don't know how to cast this 'Page Class' to a PDF and download it. I've checked the available methods but couldn’t found anything useful yet. Any suggestions?
Save Google Slide as PDF using Google Apps Script that was mentioned by #Luke converts the whole slide file to PDF and save it to your Google Drive. If you want to download a specific slide on your local computer, You can refer to the sample code.
Sample Code:
function onOpen() {
// get the UI for the Spreadsheet
const ui = SlidesApp.getUi();
// add the menu
const menu = ui.createMenu("Download")
.addItem("Download Current Slide",'downloadModal')
.addToUi();
}
function downloadModal() {
var pdfFile = convertToPdf();
//Get the pdf file's download url
var html = "<script>window.open('" + pdfFile.getDownloadUrl() + "');google.script.host.close();</script>";
var userInterface = HtmlService.createHtmlOutput(html)
.setHeight(10)
.setWidth(100);
SlidesApp.getUi().showModalDialog(userInterface, 'Downloading PDF ... ');
//Delete pdf file in the drive
pdfFile.setTrashed(true);
}
function convertToPdf() {
//Get current slide
var presentation = SlidesApp.getActivePresentation();
var slide = presentation.getSelection().getCurrentPage().asSlide();
Logger.log(slide.getObjectId());
//Create temporary slide file
var tmpPresentation = SlidesApp.create("tmpFile");
//Delete default initial slide
tmpPresentation.getSlideById("p").remove();
//Add current slide to the temporary presentation
tmpPresentation.insertSlide(0,slide);
tmpPresentation.saveAndClose();
//Create a temporary pdf file from the temporary slide file
var tmpFile = DriveApp.getFileById(tmpPresentation.getId());
var pdfFile = DriveApp.createFile(tmpFile.getBlob().setName("slide.pdf"))
//delete temporary slide file
tmpFile.setTrashed(true);
return pdfFile;
}
What it does?
Convert Current Slide to PDF file:
Get the current slide using Page.asSlide().
Create a temporary slide file. Select the initial slide and delete it using Slide.remove().
Note:
First slide in the file has an object id = 'q', you can check the object id in the slide url in your browser#slide=id.<object id>
Insert the current slide in Step 1, to our temporary slide file using Presentation.insertSlide(insertionIndex, slide). Save and close
Create a pdf file from our temporary slide file. Get the File object of our temporary slide using DriveApp.getFileById(id), get its blob using File.getBlob(). Set the name of the blob to pdf file using Blob.setName(name).Create a pdf file from the blob using DriveApp.createFile(blob)
Download the file:
Create a custom menu that will call downloadModal() to download the current slide in your local computer
Call convertToPdf() to get the pdf file's File object. Get the download url using File.getDownloadUrl()
Use custom dialog to display HTML service that will download the file using the download url obtained in Step2.
Delete the pdf file in your Google Drive using File.setTrashed(trashed)

Insert Image into Spreadsheet Cell from Drive using Google Apps Script

I would like to be able to add an image file into my spreadsheet from Google Drive. I see there is a built-in image function available =image, but this requires a URL and that image files should be shared publicly on the internet. However, I am working with digital assets and can not share them publicly.
I have the following code, this works but does not add to the required cell. Is this at all possible?
function insertImageFromDrive(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var fileId = '0B5UAkV0avfiKNGYtd1VzUzlsTVk';
var img = DriveApp.getFileById(fileId).getBlob();
sheet.insertImage(img, 4, 3)
}
Try using the guide Insert image in a spreadsheet from App Script:
function insertImageOnSpreadsheet() {
var SPREADSHEET_URL = 'INSERT_SPREADSHEET_URL_HERE';
// Name of the specific sheet in the spreadsheet.
var SHEET_NAME = 'INSERT_SHEET_NAME_HERE';
var ss = SpreadsheetApp.openByUrl(SPREADSHEET_URL);
var sheet = ss.getSheetByName(SHEET_NAME);
var response = UrlFetchApp.fetch(
'https://developers.google.com/adwords/scripts/images/reports.png');
var binaryData = response.getContent();
// Insert the image in cell A1.
var blob = Utilities.newBlob(binaryData, 'image/png', 'MyImageName');
sheet.insertImage(blob, 1, 1);
}
Just replace the necessary values. The part where you indicate which cell you insert the image is in:
sheet.insertImage(blob, 1, 1);
There is a google spreadsheet add-on ImageKit to help insert multiple images from difference sources including Google Drive, check it out > https://chrome.google.com/webstore/detail/imagekit/cnhkaohfhpcdeomadgjonnahkkfoojoc
Here you find a screenshot of tool's interface.
It is not possible if the drive image file is not public on your google drive, Having said that there is a trick to overcome i.
First make sure the image file is temporary public on your drive. you can do that also via app script by changing the file permissions to DriveApp.Access.ANYONE, DriveApp.Permission.EDIT. Then the drive file is like a file as if it was from the internet. You can then add the blob.
After that you can decide two things.
Change the permissions back or remove the image file from your drive (if you only want to use it embedded in your blob (also via app script code if you want)
good luck
I don't think it is currently possible, see here: https://code.google.com/p/google-apps-script-issues/issues/detail?id=3303
Here's another alternative:
var fileId = "..."; // your image's google drive id
sheet.insertImage("https://docs.google.com/uc?id=" + fileId, column, row);
Just make sure your file has link sharing turned on (anyone with the link can view) otherwise this method won't work.
Documentation