3

I'm trying to make a script that will resize the images in a google doc. What I have is:

var imgs = currentDoc.getImages();

for (var i = 1; i < imgs.length; i++)
{
   cell = row.insertTableCell(1);
   imgNew = imgs[i].setWidth(365);

   cell.insertImage(1, imgNew.getBlob());
}

The image gets inserted correctly but the size does not change regardless of what I set the width to. Since the image is going into a cell (width=370), is it possible to just make the image take up 100% of the width and scale the height proportionally? If not I can deal with manually setting the number of pixels but that is not working either. Any ideas?

j0k
  • 22,600
  • 28
  • 79
  • 90
user1626589
  • 61
  • 1
  • 9

3 Answers3

1

The problem is that the image size should be changed after it is inserted to a table. The following code works correctly

function test() {
  var doc = DocumentApp.openById('here_is_doc_id');
  var imgs = doc.getImages();
  var table = doc.getTables()[0];
  for (var i = 0; i < imgs.length; i++) {
   var row = table.appendTableRow();
   var cell = row.insertTableCell(0);
   var imgNew = imgs[i].copy();
   cell.insertImage(0, imgNew);
   imgNew.setWidth(365);
  }
}

Please mention, that array indexes, cells numbers, etc. start from 0 and not 1.

megabyte1024
  • 8,482
  • 4
  • 30
  • 44
  • Thanks for your answer. I tried your code, but it doesn't work. I can see the grey outline of the image with a 'link broken' icon in the middle. I suspect this is because of the imgs[i].copy() line. The image does resize correctly, but it is not shown. When I change the imgs[i].copy() to imgs[i].getBlob, the image display correctly, but the setWidth() function no longer works (function undefined error). Is there something I'm doing wrong with the copy()? (My code is essentially the same as yours, I just omitted some addition tabled elements that I created for clarity). Thanks – user1626589 Aug 28 '12 at 21:37
  • Ok, easy solution. Hopefully this will help someone else. You just have to set the image width at the time the image is being inserted like this: cell.insertImage(0, imgNew.getBlob()).setWidth(500) – user1626589 Aug 29 '12 at 05:43
1

Just as an FYI, you don't need to call getBlob()... anything that has a getBlob() can be passed in directly wherever a Blob is needed.

Corey G
  • 7,754
  • 1
  • 28
  • 28
-2

Have you tried:

imgs[i].attr('width', '370');

Or try assigning a class that has width: 100%

mcottingham
  • 1,926
  • 2
  • 18
  • 28
  • Thanks for the suggestion. attr is not a function. setAttributes() doesn't accept two inputs like that. Any idea how to assign it to a class with 100% width? – user1626589 Aug 28 '12 at 06:05