Apps script to format selected text on a Google Slide - google-apps-script

I'm trying to create a script to format selected text (selected by the user using a mouse) on a Google Slide. For example, the script might change the selected text to Arial Font, size 11, left aligned.
I know how to create a new menu item to run the script within slides - so I've got that part of the puzzle.
I've tried converting a similar script created for Google Sheets ... but it doesn't seem to work with slides.
This is what I have so far:
function onOpen() {
let ui = SlidesApp.getUi();
ui.createMenu('Macros').addItem('ParagraphFormat',
'ParagraphFormat').addToUi();
};
function ParagraphFormat() {
var slide = SlidesApp.getActivePresentation();
slide.getSelection()
.setFontSize(11)
.setFontFamily('Arial');
};

I believe your goal is as follows.
You want to change the text style of the selected text in the text box of Google Slides.
getSelection() returns Class Selection. In this case, there are no methods of setFontSize and setFontFamily. I think that this is the reason for your current issue. When you want to use setFontSize and setFontFamily to the selected text, how about the following modification?
From:
slide.getSelection()
.setFontSize(11)
.setFontFamily('Arial');
To:
var textRange = slide.getSelection().getTextRange();
if (textRange) {
textRange.getTextStyle().setFontSize(11).setFontFamily('Arial');
}
When you use this modification, please select a text in the text box and run the script. By this, setFontSize and setFontFamily are reflected in the selected text.
References:
Class Selection
getTextRange()
Added:
About your new question of One more cheeky question: how would I add one more property to align the text to the left? (eg. adding .setTextAlignment('left') ... but this doesn't work), in the current stage, only a part of the text the text in the text box cannot be aligned. So, in this case, the paragraph of the selected text can be aligned. If you want to do this, how about the following sample script?
var textRange = slide.getSelection().getTextRange();
if (textRange) {
textRange.getTextStyle().setFontSize(11).setFontFamily('Arial');
textRange.getParagraphStyle().setParagraphAlignment(SlidesApp.ParagraphAlignment.START);
}

Related

Google Script Select Partial Text in Docs

My Goal is to build a system that selects whitespace that has been underlined, and so far I have a system that moves the cursor to the start of the underlined section and highlights it.
I'm new to using Google's Apps Script, and have gotten stuck trying to programatically select only part of a paragraph. I've figured out how to select an entire paragraph and how to move the cursor to a specific location within a paragraph, but I can't figure out how to only select part of a paragraph; partially highlighted text.
I've tried using var range = DocumentApp.getActiveDocument().newRange(); and DocumentApp.getActiveDocument().setSelection(range.build());, but they only select entire paragraphs, not small portions of them.
Is there a way to select text in a paragraph between a start point and and end point?
I believe your goal is as follows.
From Is there a way to select text in a paragraph between a start point and and end point?, you want to select a part of the text on Google Document using Google Apps Script.
About I've tried using var range = DocumentApp.getActiveDocument().newRange(); and DocumentApp.getActiveDocument().setSelection(range.build());, but they only select entire paragraphs, not small portions of them., I think that in your script an erro occurs, because no range is included. In this case, it is required to include the range.
The sample script is as follows. In this case, a part of text in a paragraph is selected using the method of addElementsBetween(startTextElement, startOffset, endTextElementInclusive, endOffsetInclusive) of Class RangeBuilder.
Sample script:
Please copy and paste the following script to the script editor of Google Document. And, please set start and end. In this sample script, a part of the text in 1st paragraph is selected using a script.
function myFunction() {
const start = 8; // Please set the start offset.
const end = 14; // Please set the end offset.
const doc = DocumentApp.getActiveDocument();
const paragraph = doc.getBody().getParagraphs()[0]; // As a sample, the 1st paragraph is used.
const text = paragraph.editAsText();
const range = doc.newRange().addElementsBetween(text, start, text, end).build();
doc.setSelection(range);
}
Testing:
When this script is used, the following result is obtained.
From:
To:
Note:
This is a simple sample script. So, please modify this for your actual situation.
References:
Class RangeBuilder
addElementsBetween(startTextElement, startOffset, endTextElementInclusive, endOffsetInclusive)

google doc addon how to add textbox value to google doc

I am not a programmer.
Can someone help me with the following.
I am following this guide on how to make a google doc add-on.
http://www.cs.ucr.edu/~vahid/usefulstuff/gdoc_addon/
I have gotten this to work.
What I want to achieve is,
The user types in the google doc as normal and adds words typed in text box (in the sidebar) with some formatting added by app-script, where the cursor is.
for example
//on button click insert text in gdoc where the cursor is
"formatting1" + textbox1-text + "formating2" + textbox2-text + "formating3"
Any help would be appreciated.
Textbox is an image right, so you get all the images and check which one is a textbox image and look for the text inside it by perhaps using a get text method.
DocumentApp.getActiveDocument().getBody().getImages().forEach((elem) => {//your logic});

How can I have the text I enter into each cell automatically appended to the same root URL without creating any new columns?

I am rephrasing my original question to make it more intelligible.
I put spaces between "https" below because StackOverflow would not allow me to enter the actual URL.
Of course I could enter the text "apple" in cell A1 and then add a link from A1 to foo.com/Apple so that I would end up with [Apple](h t t p s://foo.com/Apple) in A1. However, I want that done automatically.
In other words, I want to...
Go to a cell, and then
type "apple" on my keyboard, and then
press enter, and then
instead of merely seeing "apple" in plain text, I actually I want to see
"apple" hyperlinked to foo.com/Apple like this [Apple](h t t p s://foo.com/Apple).
To get what you want you can use Google Apps Script. Adding a trigger that fires every time column A is edited, getting the entered value and combining it with the =HYPERLINK(url, link_label) function, should get what you need.
Open the Google Apps Script editor, Tools>Script Editor
Add the following code
function onEdit(e) {
// Check the edit is in column A
if(e.range.getColumn()==1){
// Get the values from the onEdit
let cell = e.range.getA1Notation()
let value = e.value
let ss = e.source
// Adding as HYPERLINK Formulas
ss.getRange(cell)
.setFormula(`=HYPERLINK("https://example.com/${value}","${value}")`)
}
}
Documentation
HYPERLINK Function
onEdit(e) Trigger
SpreadSheetApp Overview
try:
=INDEX("foo.com/"&B2:B3)

Google Script different aligment in same table row in Docs table

I'm trying to put three paragraphs (loaded from google spreadsheet) into docs via google app script.
One should be on its own row and the other two should be on same row but with different alignment.
Pic. 1 - What I want
The problem is, google allow only appending paragraphs into table cells. And paragraph contains new line so the second text is on the new line.
Pic. 2 - What I get
I've tried appending paragraph and then appending text.
But I don't know how to set up right-aligned tab and insert tab after first text.
Is it even possible to set up tabs using google script only ?
I welcome any help or suggestion how can I create text as showed in Pic. 1. Than you for any help.
There is actually an issue (3211) that prevents doing exactly what you want : the merge() method is causing the doc crash.
so the code below will result in something like this :
because we cannot merge the 2 cells in the first row from the script.
Doing it manually works well :
code :
function myFunction() {
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
body.clear();
var table = body.appendTable([['',''],['','']]);
table.setBorderColor('#ffffff');
table.getCell(0,0).appendParagraph('Some important text important text important text important text ');
//table.getCell(0,1).merge();// this is the issue...it crashes the doc
table.getCell(1,0).appendParagraph('left text').setAlignment(DocumentApp.HorizontalAlignment.LEFT);
table.getCell(1,1).appendParagraph('right text').setAlignment(DocumentApp.HorizontalAlignment.RIGHT);
doc.saveAndClose()
}

Bold conditional formatting script for Google Spreadsheets

What I want to do is essentially what this user wanted to do here:
I need a script that formats the cells in column A bold, but only the cells that contain the word 'Hello'.
However I have no knowledge of Google Apps scripts at all, and I need an answer put in much simpler terms than what I could find there or anywhere else. Any help is appreciated; thank you!
To start, from your spreadsheet, open "Tools / Script Editor...". When the dialog opens, choose to "Create Script For... Spreadsheet". You will end up with a sample script - we're going to edit it to do what you want.
Change the readRows() function as shown here. The change is that instead of logging the content of every row, we will use an if statement to check if the cell contains a string with 'Hello' in it. Then, if it does, we'll bold the cell text.
function readRows() {
var sheet = SpreadsheetApp.getActiveSheet();
var rows = sheet.getDataRange();
var numRows = rows.getNumRows();
var values = rows.getValues();
// Arrays start at 0, Google Sheets start at 1 - must remember that.
// We will loop starting at 1, because we want to skip the header in
// Row 1, aka Array index 0
for (var i = 1; i <= numRows - 1; i++) {
var colA = values[i][0];
if (colA.toString().indexOf('Hello') >= 0) {
sheet.getRange(i+1,1).setFontWeight("bold");
}
}
};
Now, how to run that? The sample already has an onOpen() function that will set up a custom menu... let's just change the text it displays in the User Interface, as shown here. The only change is in the 'name' property of the menu entries.
function onOpen() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var entries = [{
name : "Bold Hello",
functionName : "readRows"
}];
sheet.addMenu("Script Center Menu", entries);
};
Save your script. Go back to your spreadsheet, and reload it (to get it to run the onOpen trigger function). When your menu shows up, you're all set.
Next - start with the "First Script" tutorial here. The Google Apps Script documentation covers all the services provided by Apps Script, but the basic language structure and objects are javascript, so you should get familiar with that. Just try googling "learn javascript", and you'll find tons of tutorials, books, and other resources.
I can't make this simpler.
In the now not so new 'New' Sheets this can be achieved without a script:
Clear formatting, select ColumnA and Format, Conditional formatting..., Format cells if... Text contains and:
hello
Then for Formatting style click the B and Done.
This way is not case sensitive and will embolden contents such as OTHELLO.
If you aren't trying to set too many conditional formatting rules, there's an easier way to set colors, though not bold. In Google Drive Spreadsheet, click the "Format" menu. The bottom menu item should be "Conditional formatting..."; click that. That should produce a dialog box that defaults to something like this (to the extent that I can draw it with text):
x
Conditional formatting
[Text contains ◊ ] [ ] []Text: [ ] []Background: [ ] x
e.g. "done" or "Jonathan"
_______________________________________________________________________________
+ Add another rule
[ Save rules ] [ Cancel ]
In your example, you're looking for cells that contain "Hello", so the default of "Text contains" would do the job. Put "Hello" into the text box, and set a format in the "Text":" and "Background:" boxes. That doesn't give you bold, but it does allow colors.
I see that your question dates back half a year, so it's probably too late for you (and if you strictly need bold, it doesn't solve the problem anyway), but it may help others.