Google-apps-script – How to center table text vertically and horizontally in Google Script for a Document

google docsgoogle-apps-script

I am trying to center the text in a Google Document table both horizontally and vertically for all lines using Google Scripts. The code I have is the following

var style = {};
   style[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.CENTER;
   style[DocumentApp.Attribute.VERTICAL_ALIGNMENT] = DocumentApp.VerticalAlignment.CENTER;

  for(var i = 0 ; i < text.getNumChildren(); i++)
  {
    if(text.getChild(i).getType() ==  'TABLE')
    {
      var table = text.getChild(i).asTable();
      var rows = table.getNumRows();
      var cols = table.getChild(0).asTableRow().getNumChildren();

      for(var j =0 ; j< rows; j++)
      {
        for(var k =0; k<cols; k++)
        {
          text.getChild(i).asTable().getCell(j,k).getChild(0).setAttributes(style);
        }      
      }
    }
  }

When I run this code, the table centers the text horizontally, but not vertically. I would like it to do both, if possible.

I know that I can use table properties manually, but I would prefer to use a script.

Thanks for the help in advance.

Best Answer

This works for me fine

/**
 *
 * @param {GoogleAppsScript.Document.Document} doc
 */
function setСenterAlignmentForAllTables_(doc) {
  var style = {};
  style[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] =
    DocumentApp.HorizontalAlignment.CENTER;
  style[DocumentApp.Attribute.VERTICAL_ALIGNMENT] =
    DocumentApp.VerticalAlignment.CENTER;
  var tables = doc.getBody().getTables();
  tables.forEach(function(table) {
    var numRows = table.getNumRows();
    var indexRow = 0;
    while (indexRow < numRows) {
      var row = table.getRow(indexRow);
      var numCells = row.getNumCells();
      var indexCell = 0;
      while (indexCell < numCells) {
        var cell = row.getCell(indexCell);
        cell.setAttributes(style);
        indexCell++;
      }
      indexRow++;
    }
  });
}

Full code here

Also I see you set attributes for a child of the cell, instead of this you need set this for the cell directly

text
  .getChild(i)
  .asTable()
  .getCell(j, k)
  .setAttributes(style);