Search code examples
google-apps-scriptgoogle-docs-api

Set "Left Indent" for a table in Google Docs using Google Apps Script


We can set the left indent for a table in Google Docs manually by right clicking on the table and selecting "Table Properties":

enter image description here

I have tried to achieve the same using Google Apps Script by setting the INDENT_FIRST_LINE and INDENT_START attributes, but there is no effect on the table:

var style = {};
style[DocumentApp.Attribute.INDENT_FIRST_LINE] = 72;
style[DocumentApp.Attribute.INDENT_START] = 72; 

body.insertTable(elementIndex, table).setAttributes(style);

How can I set the same property for a table using Google Apps Script? Is there an alternate way to achieve the same?

Please star this issue so that Google team takes it on priority:

https://issuetracker.google.com/issues/36764951


Solution

  • Since Apps Script does not provide this feature. I ended up doing the following:

    • create an outer table with two columns. Set the border width to zero
    • the width of the first column is the length of the indentation required
    • the width of the second column is the width of the actual table
    • insert the table into the second column. The resulting document looks like as if the table has been indented

    Following is the sample script for the above algorithm:

    var insertTableWithIndentation = function(body, 
                                            document, 
                                            originalTable, 
                                            elementIndex, 
                                            nestingLevel) {
    
      var docWidth = (document.getPageWidth() - 
                      document.getMarginLeft() - 
                      document.getMarginRight());
    
      var table = body.insertTable(elementIndex);
      var attrs = table.getAttributes();
      attrs['BORDER_WIDTH'] = 0;
      table.setAttributes(attrs);
    
      var row = table.appendTableRow();
      var column1Width = (nestingLevel+1) * 36;
      row.appendTableCell().setWidth(column1Width);
    
      var cell = row.appendTableCell();
      var column2Width = docWidth - column1Width;
      cell.setPaddingTop(0)
          .setPaddingBottom(0)
          .setPaddingLeft(0)
          .setPaddingRight(0)
          .setWidth(column2Width);
    
      cell.insertTable(0, originalTable);
    }