How to add pictures to Google Docs tables without resizing cells using Apps Script?

I’m having trouble putting pictures in my Google Docs table. The cells keep getting bigger when I add images, but I don’t want that to happen. I tried setting the cell padding to zero and making the pictures smaller, but it’s not working. Here’s what I’ve done so far:

function addImagesToTable() {
  var doc = DocumentApp.getActiveDocument();
  var table = doc.getBody().getTables()[0];
  
  for (var row = 1; row < table.getNumRows(); row++) {
    if (isSpecialRow(row)) {
      for (var col = 0; col < 5; col++) {
        var cellText = table.getCell(row, col).getText().trim().toLowerCase();
        
        if (pictureMap.hasOwnProperty(cellText)) {
          var imageFile = DriveApp.getFileById(pictureMap[cellText]);
          var prevCell = table.getCell(row - 1, col);
          
          prevCell.clear();
          prevCell.setPadding(0, 0, 0, 5);
          prevCell.insertImage(0, imageFile.getBlob()).setSize(50, 50);
        }
      }
    }
  }
}

Can anyone help me figure out how to keep the cell size the same when adding pictures? Also, my script takes a long time to run. Any tips on making it faster would be great. Thanks!

hey sofiag, i’ve had similar issues. have u tried setting a fixed width for the table columns? smth like:

table.getRow(0).getCell(col).setWidth(100);

for each column. might help keep cells from resizing. also, caching the image blobs cud speed things up. hope this helps!

I’ve dealt with this exact problem before, and it can be really frustrating. One trick that worked for me was using a LayoutCell instead of directly inserting the image into the table cell. Here’s a snippet that might help:

var layout = prevCell.insertLayout(0);
var layoutCell = layout.appendTableCell();
layoutCell.setPadding(0);
layoutCell.insertImage(0, imageFile.getBlob()).setSize(50, 50);

This approach keeps the table cell dimensions intact while allowing you to insert the image. As for performance, I’d suggest fetching all the images at once at the start of your script and storing them in a map. This way, you’re not making repeated calls to DriveApp for each cell. It made a huge difference in my script’s runtime. Give it a shot and let me know if it helps!

I’ve encountered this issue before. One effective approach is to set a fixed cell size before inserting the image. You can do this by using the setWidth() and setHeight() methods on the cell. For example:

prevCell.setWidth(100).setHeight(100);
prevCell.insertImage(0, imageFile.getBlob()).setSize(50, 50);

This ensures the cell dimensions remain constant. As for performance, consider batch processing your images and using the Advanced Drive Service for faster file retrieval. Additionally, you might want to implement error handling to manage potential issues with missing images or invalid cell references. These modifications should significantly improve your script’s efficiency and reliability.