Google apps script: How to horizontally align an inlineImage

淺唱寂寞╮ 提交于 2021-02-08 09:29:45

问题


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
} 

回答1:


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.



来源:https://stackoverflow.com/questions/26248384/google-apps-script-how-to-horizontally-align-an-inlineimage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!