0
votes

I'm writing a script that generates some tables within a Google Doc using Google Apps Scripts. I'm looking to distribute the rows of those tables evenly. Essentially, to accomplish the same thing as right-clicking on said table in Google Docs and selecting Distribute Rows. Is this possible?

Right now I have a fully functioning script to generate these tables. Inside of it, I have:

var tableData = [['1', '2'], 
                         ['3', '4']];

table = body.appendTable(tableData);

///Now I want something like
// table.distributeRows(true);
1
Welcome to Stack Overflow. You may want to review the information about asking a question: On Topic Questions The best questions have some code in them.Alan Wells

1 Answers

0
votes

There is no built in method to distribute columns evenly. But, you can write your own function which calculates the page width and then sets the width of each column to fit equally.

function colWidth() {
  var doc = DocumentApp.getActiveDocument().getBody();

  // Get the table. If you have multiple, you'll need another loop.
  var table = doc.getTables();

  // Calculate the width of the document
  var docWidth = (doc.getPageWidth() - doc.getMarginLeft() - doc.getMarginRight());

  // Rows are children of tables. Loop through each row.        
  for(var i=0; i<table[0].getNumChildren(); i++) {

    // Columns are children of rows. Loop through each column.
    for(var j=0; j<table[0].getRow(i).getNumChildren(); j++) {

      // Get the cell and set the calculated width. You probably only need to do this for the first row.
      var cols = table[0].getRow(i).getCell(j);
      cols.setWidth((docWidth / table[0].getRow(i).getNumChildren()));

    }
  }
}

Update

Setting row height is similar. There is no method to get the height of the table, so you need to calculate it from individual row heights.

function rowHeight() {
  var doc = DocumentApp.getActiveDocument().getBody();

  var table = doc.getTables();

  // set an integer to hold the current table height
  var tableHeight = 0;

  var numRows = table[0].getNumChildren();

  // get the height of the table  
  for(var i=0; i<numRows; i++) {
    tableHeight += table[0].getRow(i).getMinimumHeight();
  }

  // loop again to set the height for each row evenly
  for(var j=0; j<numRows; j++) {
    table[0].getRow(j).setMinimumHeight(tableHeight / numRows);
  }
}