Google apps脚本:如何水平对齐inlineImage

时间:2014-10-08 02:38:28

标签: javascript image google-apps-script center

我有以下代码,它是更大程序的一部分。我正在尝试将我的Google驱动器中的图像插入到Google文档中并将其调整大小并居中。到目前为止,我能够让程序插入图像并调整大小,但我不知道如何将inlineImage居中。我是使用谷歌应用程序脚本的新手,我基本上已经复制了其他人的示例并对其进行了修改。非常感谢您的帮助。如果我需要澄清,请告诉我。我再次尝试将inlineImage(var inlineI)设为CENTER。谢谢!

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 个答案:

答案 0 :(得分:2)

您需要居中对齐包含图片的段落。添加此代码来执行此操作:

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

getParent()方法获取包含图像的容器元素(段落)。 setAttributes()方法将custom style attributes(在这种情况下为中心对齐)应用于元素。

相关问题