Google Script different aligment in same table row in Docs table - google-apps-script

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()
}

Related

Apps script to format selected text on a Google Slide

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);
}

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)

How to insert and center a Table in Google Docs with Google Script

I am trying to create a table and have it end up being centered in the document body of a Google DocumentApp using Google Script.
As of now, I create Tables using a For Loop and they are created fine, they Just will not center.
I have tried the Following:
Attempt 1:
var insertedTable = updateBody.insertTable(numberOfTables, objectivesTables[g]);
insertedTable.setAlignment(DocumentApp.HorizontalAlignment.CENTER);
RESULT: This makes one LEFT aligned table then stalls and times out. (I am using a library that I have created and I am calling this function from another Script so I do not get an error message)
Attempt 2:
var style = {};
style[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.CENTER;
updateBody.insertTable(numberOfTables, objectivesTables[g]).setAttributes(style);
RESULT: All Tables Are created but are Left Aligned.
I have seen this done with Text, Paragraphs, and Images but I cannot figure out how to accomplish this with a Table so any help would be graciously received.
A nasty solution might be to put a placeholder in the doc, center it manually and then replace it with a table.

Align multiple images beside in Google Doc

after several hours of searching and try & error, I have to give up.
I got a google doc wich I fill up with some data from a google sheet.
Also I create some pie charts with the data and would like to align 2 (or even more) little charts (>200x200 px) inline beside eachother.
But I am not able to do it. :(
One single image, or chart isnĀ“t any problem, but 2 or more seems to be pretty hard.
Thats why I picked up this option and Your experience as my last option.
Thank you very much for every hint and have a nice Day.
Michael
"Short" Code Sample:
Step 1: Open Google Sheet
var reportDataStorage = SpreadsheetApp.openByUrl('https://docs.google.com/.../edit');
var sheet = reportDataStorage.getSheetByName(...);
Step 2: Create Table
var daten_besucher_nach_quelle = Charts.newDataTable()
...
daten_besucher_nach_quelle.addRow([sheet.getRange('O'+y).getValue(), sheet.getRange('P'+y).getValue(), sheet.getRange('Q'+y).getValue(); sheet.getRange('R'+y).getValue()]);
...
daten_besucher_nach_quelle.build();
Step 3: Create Chart from Table
var chart_besucher_nach_quelle = Charts.newPieChart()
.setDataTable(daten_besucher_nach_quelle)
.setDimensions(300, 300)
...
.build();
Step 4: Append Image
body.appendImage(chart_besucher_nach_quelle.getAs('image/png'));
Is this enough?
As you noticed, when you insert an image in a document, a new paragraph is automatically added to the document's body.
This paragraph container is accessible using image.getParent() method. As soon as we get this paragraph we can add another image in it, this image will be directly aligned side by side (as long as the total width is less than the maximum size between margins).
Try this small simple code and see the result in the scren capture below :
function importImageTest(){
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var image1 = DriveApp.getFileById("0B3qSFd3iikE3TUFFLWY0ZWJjNzM2LWFiNDYtNGU1OC1hMGNhLTViM2UxNTBlMTE3Nw");// some image in my drive
var image2 = DriveApp.getFileById("0B3qSFd3iikE3TUFFLWI3Y2JiOTU1LWM0OGYtNDVkMS05ZTRiLTkzNjQ5NDBlZGFkNA");
var firstImage = body.appendImage(image1).setWidth(150).setHeight(100);// an arbitrary size
var currentParagraph = firstImage.getParent();// the container of first image
currentParagraph.asParagraph().appendInlineImage(image2).setWidth(150).setHeight(100);// add the second image to this parent paragraph
doc.saveAndClose();
}

Google Apps Script Chart Use row 1 as headers

I have the following chart:
var ss = ... // get sheet
var chart = ss.newChart().asLineChart();
chart.setTitle("My Title");
chart.addRange(dataSheet.getRange(1, 1, ss.getLastRow(), 4));
chart.setColors(["#3c78d8", "#a61c00", "#38761d"]);
chart.setXAxisTitle("X Title");
chart.setYAxisTitle("Y Title");
chart.setPosition(1, 1, 0, 0);
chart.setCurveStyle(Charts.CurveStyle.SMOOTH);
ss.insertChart(chart.build());
This code will use the show the first row as part of the data, instead of using it to label the legend. As a side note, if I use asColumnChart instead of line chart, it does the right thing.
How can I tell a chart to use the first row as headers using Google Apps Script?
First off - your code is OK. I took a copy and made minor changes to it just to use a single sheet for illustration:
The problem is likely with your data, specifically the first row. Here's that same example, with some of the "Headers" changed from text into numbers. I believe it is behaving in the bad way you're describing.
One more time, but with the numbers in the header forced to be text. (In the spreadsheet, I input them as '4 and '5 - the leading single quote tells Spreadsheet to treat as text.)
Just take a look at the data types in your first row, and make sure that they are Text.