2

I have the following code, which is part of a larger program. I am trying to insert an image from my Google drive into a google doc and have it resized and centered. So far I am able to get the program to insert the image and resize it, but I do not know how to center an inlineImage. I am new to using google apps script and I have basically been copying other people's examples and modifying them. Your help would be appreciated. Let me know if I need to clarify. Again, I am trying to CENTER the inlineImage (var inlineI). Thanks!

var GDoc = DocumentApp.openByUrl("URL"); //I deleted my actual URL

function insertImageFromDrive(){
 var img = DriveApp.getFileById(myImageFileID).getBlob(); //I deleted my actual image ID
 var inlineI = GDoc.appendImage(img); //insert image

  //resizing the image
  var width = inlineI.getWidth();
  var newW = width;
  var height = inlineI.getHeight();
  var newH = height;
  var ratio = width/height;
  Logger.log('w='+width+'h='+height+' ratio='+ratio);
    if(width>320){ 
      //max width of image
      newW = 320; 
      newH = parseInt(newW/ratio);
    }
  inlineI.setWidth(newW).setHeight(newH); //resizes the image but also needs to center it
} 
Jeremy Gerber
  • 53
  • 3
  • 5

1 Answers1

3

You need to center-align the paragraph that contains your image. Add this code to do it:

var styles = {};
styles[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.CENTER;
inlineI.getParent().setAttributes(styles);

getParent() method gets the container element (paragraph) containing your image. setAttributes() method applies custom style attributes (center alignment in this case) to the element.

azawaza
  • 3,065
  • 1
  • 17
  • 20