2014-10-08 28 views
1

我有以下代碼,這是一個更大的程序的一部分。我試圖從我的谷歌驅動器插入一個圖像到谷歌文檔,並調整大小和居中。到目前爲止,我可以讓程序插入圖像並調整它的大小,但我不知道如何居中一個inlineImage。我是使用谷歌應用程序腳本的新手,我基本上一直在複製其他人的示例並修改它們。您的幫助將不勝感激。如果我需要澄清,請告訴我。再次,我想中心inlineImage(var inlineI)。謝謝!谷歌應用程序腳本:如何水平對齊圖像

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 
} 

回答

0

您需要居中對齊包含圖像的段落。添加該代碼做到這一點:

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

getParent()方法獲取包含圖像的容器元素(段落)。 setAttributes()方法將custom style attributes(在此情況下爲中心對齊)應用於元素。