0

I have searched and found code that first inserts an image into a Table in a Google Doc.The image however is larger than the desired image space--and so we have to resize the picture by first getting the dimensions of the inserted picture and then reinserting the picture into the table. The code seems to work well except I am left with two pictures the original sized picture and the scaled picture in the specified table location.

My challenge is that when I attempt to delete the first picture after getting the sizing information needed to scale the picture -- nothing ends up being saved. Here is the code:

    if(celltext === "%PIC%") {
     table.replaceText("%PIC%", "");
      table.getCell(row, cell).insertImage(0, image);

       sizePic(table,image, row,cell);

                     }
     function sizePic(table, image) {

      var cellImage = table.getCell(row, cell).insertImage(0, image);

    //get the dimensions of the image AFTER having inserted it to fix
    //its dimensions afterwards

       var originW =  cellImage.getWidth();
        var originH = cellImage.getHeight();
         var newW = originW;
          var newH = originH;
           var ratio = originW/origin
            var styleImage = {};
             var maxWidth = 200;

        if(originW>maxWidth){
         newW = maxWidth;
          newH = parseInt(newW/ratio);

           table.getCell(row,cell).clear();
                            }             
        cellImage.setWidth(newW).setHeight(newH).setAttributes(styleImage);
                 }
               }

The problematic line is the table.getCell(row,cell).clear(); that even though it occurs after the image is inserted and before the sized image is inserted, it doesn't appear to work that way. Please note that my code is the result of looking at an existing post How to resize image on Google app Script.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • How about this GAS library ([https://github.com/tanaikech/ImgApp](https://github.com/tanaikech/ImgApp))? This library can retrieve the image size, resize the image and return the resized image as a blob. The resized image can be directly inserted using this library. Although the demo is running on Spreadsheet, it can be used for Google Document. If this information was not useful for you, I'm sorry. – Tanaike Aug 24 '17 at 23:51
  • I will certainly investigate, thanks1 – Craig Heath Aug 25 '17 at 15:05
  • Thank you, I added the library and implemented the new functionality. I have eliminated the requirement to load the image--and then get its dimensions, and then re-write the images...so, no deletion required. – Craig Heath Aug 25 '17 at 16:59
  • Welcome. I'm glad this could be useful for you. Thank you, too. – Tanaike Aug 25 '17 at 23:23

0 Answers0