Google apps script - Bookmark a selected image - google-apps-script

How can I addBookmark() a selected image from Goole docs.

In your situation, how about the following sample script?
Sample script:
function myFunction() {
const doc = DocumentApp.getActiveDocument();
const selection = doc.getSelection();
if (!selection) return;
selection.getRangeElements().forEach(e => {
const ele = e.getElement();
const type = ele.getType();
if (type == DocumentApp.ElementType.TEXT) {
doc.addBookmark(doc.newPosition(ele, e.getStartOffset()));
} else if (type == DocumentApp.ElementType.INLINE_IMAGE) {
doc.addBookmark(doc.newPosition(ele.asInlineImage().getParent(), 1));
}
});
}
When you use this script, please select an inline image on Google Drive and run the script. By this, the bookmark is added to the inline image. And, when you select a text, the bookmark is added to the text.
Reference:
asInlineImage()

Related

Is it possible to fill template text fields in Google Slides, from a google sheet, when someone click a link to create a pdf of the slides?

I have a Google Slide presentation with several text templates. I also have a master file, with text data. As an example, in the slide there is a template called and similar in the master Google Sheets file. I want to share a link that is unique and never changed in an email, and is there a way that when someone click that link, the google slide updated all values and let the user download an updated PDF. Basically, if the is changed, I update the sheets file, and the user will download a pfd with the correct adress?
I have tried to create the script for the Slides, but if the data is changed in sheets, I need to change in Slides as well.
Here is an example of how to change text from a Slides Presentation and from a Spreadsheet.
Fist I create a simple slide with a marker.
Then a script that searches the presention for the marker and replaces the text from a spreadsheet.
function test() {
try {
let present = SlidesApp.getActivePresentation();
let slides = present.getSlides();
slides.forEach( slide => {
let shapes = slide.getShapes();
shapes.some( shape => {
let range = shape.getText();
if( range.find(/\{\{marker\}\}/)) {
let spread = SpreadsheetApp.openById("your spreadsheet id here");
let value = spread.getSheetByName("Sheet1").getRange("A1").getValue();
range.replaceAllText("{{marker}}",value);
return true;
}
return false;
}
);
}
);
}
catch(err) {
console.log(err);
}
}
Then in my spreadsheet I create an installed onEdit to replace the text in the presentation if the value in cell A1 is changed. Note this only will work the first time because the marker is replaced by the text.
function onEditPresentation(e) {
try {
if( e.range.getSheet().getName() === "Sheet1" ) {
if( e.range.getA1Notation() === "A1" ) {
let present = SlidesApp.openById("1o6ml4KZ4crkaYw06LAouDidaCrwMHWkE36Iuo0A_3Mo");
let slides = present.getSlides();
slides.forEach( slide => {
let shapes = slide.getShapes();
shapes.some( shape => {
let range = shape.getText();
if( range.find(/\{\{marker\}\}/)) {
range.replaceAllText("{{marker}}",e.value);
return true;
}
return false;
}
);
}
);
}
}
}
catch(err) {
SpreadsheetApp.getActiveSpreadsheet().toast("onEdit() "+err);
}
}
References:
SlidesApp
Presentation.getSlides()
Slide.getShapes()
Shape.getText()
TextRange.replaceAllText()

Copy Multiple Charts from Sheets to Docs

We have switched from Microsoft to Google Workspace.
We have a Sheet with multiple tabs with a table and graph in each tab. I would like to automate inserting these graphs (as images) at specific points into a preformated Google Doc. I am sure this is something very routinely done.
I am told this can be done with Google Apps Script, but I have never used it.
Could someone point me to some good examples to get me started?
Thanks
Description
Here is a sample example script to get a chart from Google Sheet and place in a Google Doc. I use as a place holder the paragraph "Chart1".
Spreadsheet
Doc (Before)
Doc (After)
Code.gs
function testChart() {
try {
let charts = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Chart").getCharts();
// In this case there is only 1
let chart = charts[0];
chart = chart.getAs("image/png");
let doc = DocumentApp.openById("1A........................ds");
let body = doc.getBody();
let paras = body.getParagraphs();
for( let i=0; i<paras.length; i++ ) {
let para = paras[i];
let text = para.getText();
if( text === "Chart1" ) {
para.addPositionedImage(chart);
}
}
}
catch(err) {
console.log(err);
}
}
Reference
Sheet.getCharts()
DocumentApp.openById()
Document.getBody()
PositionImage

How overwrite docs with scripts in google?

I make one script to auto fill a Google Doc from a Google Form Submissiom. Now I need another script to overwrite the document when there is a change in some spreadsheet value . (the user cannot edit the form's response but can change values ​​in the spreadsheet).
enter image description here
As long as you know what paragraph it is that needs to be edited you can try this.
Before:
function myFunction() {
try {
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var paras = body.getParagraphs();
var i = 0;
for( i=0; i<paras.length; i+=2 ) {
paras[i].setText("Line "+(100+i));
}
}
catch(err) {
console.log(err);
}
}
After:

How to Extract link from a sentence in google document with appscript

I have a table in google doc, in which I want to extract the hyperlinked text and its link using appscript
Suppose : The community is here to help you with specific coding, algorithm, or language problems.
I have a code for google spreadsheet which can extract links from the text, however the same code is not usuable in google docs.
function myFunction() {
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;
}, [])
}
}
How to modify it for google docs ?

Fetching latest file URL in Drive and posting it to Google Spreadsheet based on a criteria

I am wondering whether it's possible or not to retrieve the URL of the latest file in a Drive Folder then have it posted into a cell in Column B of a Spreadsheet.
Then there's the other part where the URL should only be posted if Column A has the word "YES". So if A has "NO" URL isn't necessary.
The full scenario would be like this.
Picture uploaded into Drive Folder.
"YES" is entered into A1.
URL of latest uploaded picture is fetched then pasted into B1.
Then it continues for all the other rows as well.
Theoretically, that's how I want it to work. But I don't know whether it could work or not.
This is the script that I use to upload picture into Drive:
function doGet(e) {
return message("Error: no parameters in doGet");
}
function doPost(e) {
if (!e.parameters.filename || !e.parameters.file || !e.parameters.imageformat) {
return message("Error: Bad parameters in doPost");
} else {
var imgf = e.parameters.imageformat[0].toUpperCase();
var mime =
(imgf == 'BMP') ? MimeType.BMP
: (imgf == 'GIF') ? MimeType.GIF
: (imgf == 'JPEG') ? MimeType.JPEG
: (imgf == 'JPG') ? MimeType.JPEG
: (imgf == 'PNG') ? MimeType.PNG
: (imgf == 'SVG') ? MimeType.SVG
: false;
if (mime) {
var data = Utilities.base64Decode(e.parameters.file, Utilities.Charset.UTF_8);
var blob = Utilities.newBlob(data, mime, e.parameters.filename);
DriveApp.getFolderById('Folder Id').createFile(blob);
return message("Success");
} else {
return message("Error: Bad image format");
}
}
}
function message(msg) {
return ContentService.createTextOutput(JSON.stringify({Result: msg })).setMimeType(ContentService.MimeType.JSON);
}
While this is the script I use to enter "YES" or "NO" into Column A:
function doGet(e) {
var ss = SpreadsheetApp.openByUrl("Sheet_URL");
var sheet = ss.getSheetByName("Sheet_Name");
addRecord(e,sheet);
}
function doPost(e) {
var ss = SpreadsheetApp.openByUrl("Sheet_URL");
var sheet = ss.getSheetByName("Sheet_Name");
addRecord(e,sheet);
}
function addRecord(e,sheet) {
var HvPict = e.parameter.HvPict;
sheet.appendRow([Hv.Pict]);
}
You want to retrieve the URL of the latest uploaded file in the specific folder.
You want to achieve this using Google Apps Script.
I could understand like above. If my understanding is correct, how about this sample script? Please think of this as just one of several possible answers.
In your case, I thought that the method of getDateCreated() in Class File might be able to be used. So how about the following sample script?
Sample script:
function getLatestFile(folderId) {
var files = DriveApp.getFolderById(folderId).getFiles();
var fileObj = [];
while (files.hasNext()) {
var file = files.next();
fileObj.push({url: file.getUrl(), date: file.getDateCreated()});
}
fileObj.sort(function(a, b) {return new Date(b.date) - new Date(a.date)});
return fileObj[0].url;
}
function myFunction() {
var folderId = "###";
var lastFileUrl = getLatestFile(folderId);
Logger.log(lastFileUrl)
}
When you run the script, please set folderId. This script retrieves the files in the folder of folderId.
When you run the function of myFunction(), the URL of the latest created file is retrieved.
Note:
In your case, above function might should be used at the script of the 2nd HTML form.
If in your actual situation, the uploaded file is modified and you want to retrieve the latest modified file, please try to use getLastUpdated() instead of getDateCreated().
In this case, fileObj.sort(function(a, b) {return new Date(b.date) - new Date(a.date)}); might not be required.
References:
getDateCreated()
getLastUpdated()
Added:
function getLatestFile(folderId) {
var files = DriveApp.getFolderById(folderId).getFiles();
var fileObj = [];
while (files.hasNext()) {
var file = files.next();
fileObj.push({url: file.getUrl(), date: file.getDateCreated()});
}
fileObj.sort(function(a, b) {return new Date(b.date) - new Date(a.date)});
return fileObj[0].url;
}
function doGet(e) { // or doPost(e)
var folderId = "###";
var ss = SpreadsheetApp.openByUrl("Sheet_URL");
var sheet = ss.getSheetByName("Sheet_Name");
sheet.appendRow([e.parameter.HvPict, getLatestFile(folderId)]);
}
When you modified the script of Web Apps, please redeploy Web Apps as new version. By this, the latest script is reflected to the Web Apps. Please be careful this.