PFB
PFB

Reputation: 167

How do I center a table in a google document page using Google Apps Script

I have inserted a table in a google docs using the Google Apps Script function

var grg = body.appendTable(griglia);

I am able to format the text in the table (font size, weight, alignment) and I can format individual cells (background, foreground, borders).

However the table is aligned left, and I would like it to be (horizontally) centered in the page. From the google docs user interface this can be done from the menu "Table>Table properties", which generates a dialog box with a dropdown menu for "Table alignment".

I cannot find a way to obtain the same from the script. I tried

var grg = body.appendTable(griglia).setAlignment(DocumentApp.HorizontalAlignment.CENTER);

but I get an error because the setAlignment function is not defined for a table (this works for paragraphs).

I also tried by defining a style

  var gTxt={};
  gTxt[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.CENTER;
  grg.setAttribute(gTxt);

but this does not seem to produce any effect on the table. Actually I also tried with a different property, just to try to understand how things work.

Using

gTxt[DocumentApp.Attribute.FOREGROUND_COLOR] = '#ff0000';
grg.setAttribute(gTxt);

all the text in the table, and whatever follows it, becomes red. So it seems that the setAttributes is not "limited" to the table. I am confused, because in the documentation "setAttributes" is listed under "Table" (although in the example it is used on a paragraph).

I did extensive research, but found only one similar question (in fact basically identical) dating back two years. As far as I understand from this meta post, my question should not be marked as a duplicate, since the older question was not really answered.

There is only an answer, but its author misunderstood the question. The point here is centering the table, and not the text in its cells (which I can do no problem).

I tried to upvote or comment the old question, but was not able because I have only a few points.

Thanks for any insight.

Upvotes: 1

Views: 2964

Answers (2)

Cameron Roberts
Cameron Roberts

Reputation: 7387

A potential workaround is to insert your table into another 3 column table, with hidden borders. By default the 3 column table will fill the entire width of the page, so the middle cell is naturally centered.

 body.appendTable([['','','']])
       .setBorderWidth(0)
       .getCell(0,1)
       .appendTable([['one','two','three']]);

You could further tweak the positioning by adjusting the width of column 0 in the outer table.

Upvotes: 1

user555121
user555121

Reputation:

It is not possible to center table via Apps Script at the moment.

There's feature request created in Google tracker, you can "star" it: https://issuetracker.google.com/issues/36765133

Upvotes: 0

Related Questions