Search code examples
google-apps-scriptgoogle-docs

In a Google Document how to set a tables multiple rows' height to match the cell content size?


I can click and drag each horizontal line one by one manually to match amount of content of the cell above it (how many lines of text it has), but what if you have 100 rows?
How can you get from top to the bottom table here without manually dragging each horizontal line?

So, if there is ONE line of text in the whole row height wise, I want the table be ONE line height, not 10 like in the below case in abc row.

enter image description here

enter image description here


Solution

  • enter image description here

    This can be achieved using a bound-to-your-Doc Google Apps Script. You can write a function to make all rows' height the minimum possible for tables in the Document, and for those rows with content height larger than minimum, the minimum for that row will be applied (Not hiding any of the content).

    Example of a function to achieve this:

    function fixCellSize() {
      DocumentApp.getUi().alert("All row heights will be minimized to content height.");
      var doc = DocumentApp.getActiveDocument();
      var body = doc.getBody();
      var tables = body.getTables();
      for each (var table in tables) { 
        for (var i=0; i < table.getNumRows(); i++){
          Logger.log("Fantasctic!");
          table.getRow(i).setMinimumHeight(1);
        }
      }
    }
    

    If you would like to make the function available in the menu, then you could create a Custom Menu with a function like the following:

    function onOpen() {
      var ui = DocumentApp.getUi();
      ui.createMenu("Custom Menu").addItem("Fix cell sizes", "fixCellSize").addToUi();
    };
    

    By putting this functions in a bound script you will get what you are looking for.

    You can try it out in this Document showcasing it.

    Recommended reading:

    1. Extending Google Docs
    2. Apps Script DocumentApp class