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)
Related
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);
}
I need to get all the paragraphs from a google document. For that, I am using body.getParagraphs().
The problem is, in any document, if any table exists, the body.getParagraphs() method takes all the table cells as a paragraph and returns as a paragraph. Now what I want is to get all the paragraphs only, from a document and exclude the table and table cells from that. How can I achieve this?
Thanks!
I believe your goal as follows.
You want to retrieve the paragraphs except for the table cell using Google Apps Script.
In this case, how about checking the element type? When this is reflected to a script, it becomes as follows.
Sample script:
Please copy and paste the following script to the script editor of Google Document.
function myFunction() {
const doc = DocumentApp.getActiveDocument();
const body = doc.getBody();
const paragraphs = body.getParagraphs();
const res = paragraphs.filter(p => p.getParent().getType() != DocumentApp.ElementType.TABLE_CELL);
// do something
}
In this sample script, the values of paragraphs include the paragraphs of table cell.
By filtering the element type, res can have only the paragraphs except for the table cell.
References:
getParent() of Class Paragraph
getType()
I'm very new using GAS what I'm trying to do is to copy some information that is already on the bottom of my doc to anywhere I want in my docs, this should work just by copying the information and paste it at the place I desire, but I want it to be done with Google App Script because it's a daily task and it's easier to do it with a function, instead of copying and pasting manually. Searching on how to do this, I found a lot of information about how to do it on Spreadsheets, but I needed it to be done on Google Docs. How can I do that?
If someone can guide me or send me a link to another similar question that would be very helpful, I don't know where to start.
This is what I have until now, I get all the data of the current doc and set it again to the page, the code gives me problems because it deletes my other information, also it selects all the doc's information. I want to select a piece of specific information and don't copy the content style.
function copyPasteInfo() {
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var notesText = body.getText();
body.appendPageBreak();
body.setText(notesText);
}
Link to the doc document
https://docs.google.com/document/d/1s2TCspXbjvHVurwhIWSdwJ_hMcZIoLTKj4FAB82nmhM/edit
Video example of how what i want to do
https://www.screencast.com/t/UmEon8Fm0lPe
Picture of the information i'm trying to copy and paste to the bottom of my doc
If I correctly understood your question, this code will help you to achieve your goal.
let body = DocumentApp.getActiveDocument().getBody();
function moveTable() {
// Get the last table and the previous table found in your Doc
const [previousTable, bottomTable] = getDesireTables();
// Make a copy of your last table
const bottomTableCopy = bottomTable.copy();
// Get the previous table's index
const previousTableIndex = body.getChildIndex(previousTable);
// Insert the last table's copy under the previous table in your Doc
body.insertTable(previousTableIndex + 1, bottomTableCopy);
// Remove the original last table
body.removeChild(bottomTable);
}
function getDesireTables(){
const tablesArr = body.getTables().slice(-3);
// Get the parent element type to check if it's a cell
const parentELementType = tablesArr[tablesArr.length - 1].getParent().getType();
if(parentELementType === DocumentApp.ElementType.TABLE_CELL){
// If there's a table inside a table, return this
return tablesArr.slice(0, 2);
}
else{
return tablesArr.slice(-2);
}
}
What I did was to get the last two tables in the Doc, then I made a copy of the last one and with the index of the previous one, I inserted it under the previous one.
Edit
I noticed you had a table inside a table. therefore I added the getDesireTables function. Which it will check if your bottom table has a table inside.
Docs
These are the docs I used to help you:
getTables().
copy().
insertTable(childIndex, 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()
}
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.