在段落的特定点插入图像

时间:2013-12-11 17:59:42

标签: google-apps-script google-docs

*我的Google文档中包含“text {logo} text”字符串 如何将图片放在{logo}所在的位置? 到目前为止我试过了:

var logoElement = s.findText("{logo}").getElement();
logoElement.getParent().insertInlineImage(0,logoBlob);
s.replaceText("{logo}", "");

但是这会在找到的段落之前插入图像(或者在之后使用1:)。如何将放在段落中的确切位置?

3 个答案:

答案 0 :(得分:5)

I hope will be helpful, The following code is fine to me.

function insertImage(doc) {
  // Retrieve an image from the web.
  var resp = UrlFetchApp.fetch("http://www.google.com/intl/en_com/images/srpr/logo2w.png");
  var image = resp.getBlob();
  var body = doc.getBody();
  var oImg = body.findText("<<Logo1>>").getElement().getParent().asParagraph();
  oImg.clear();
  oImg = oImg.appendInlineImage(image);
  oImg.setWidth(100);
  oImg.setHeight(100);
}

答案 1 :(得分:2)

我根据你的答案尝试了一个更简单的版本,保留了原始段落的格式......

尝试一下,它不是“万无一失”,但它在我的测试中起作用,并且(我认为)是一个有趣的试验; - )

代码在这里:

function test(){
  placeImage('{logo}','0B3qSFd3iikE3SkFXc3BYQmlZY1U');
//This is my page and I’d like to have a {logo} on it right here
}


function placeImage(placeHolder,imageId) {
  var logoBlob = DocsList.getFileById(imageId).getBlob();
  var d = DocumentApp.getActiveDocument()
  var s = d.getHeader();
  var logoResult = s.findText(placeHolder); 
  var placeholderStart = logoResult.getStartOffset(); 
  var par = s.getChild(0).asParagraph();
  var parcopy = par.copy();
  var parLen = par.editAsText().getText().length-1;
  Logger.log('placeholderStart = '+placeholderStart+'  parLen = '+parLen)
  par.editAsText().deleteText(placeholderStart, parLen);
  parcopy.editAsText().deleteText(0, placeholderStart+placeHolder.length);
  var img = s.getChild(0).appendInlineImage(logoBlob);
  s.appendParagraph(parcopy);
  parcopy.merge();
}

enter image description here

答案 2 :(得分:1)

感谢Serge的评论和链接的原始帖子,指出我正确的方向。 这就是我现在所拥有的:

var s = d.getHeader();
var logoResult = s.findText("{logo}"); // search result
var logoElement = logoResult.getElement(); // the paragraph that contains the placeholder
var text = logoElement.getText();
var placeholderStart = logoResult.getStartOffset(); // character position start placeholder
var placeholderEnd = logoResult.getEndOffsetInclusive(); // char. position end placeholder
var parent = logoElement.getParent(); 
var parPosition = parent.getChildIndex(logoElement);

// add new paragraph after the found paragraph, with text preceding the placeholder
var beforeAndLogo = s.insertParagraph(parPosition+2, text.substring(0, placeholderStart));
var logo = beforeAndLogo.appendInlineImage(logoBlob); // append the logo to that new paragraph

// add new paragraph after the new logo paragraph, containing the text after the placeholder
var afterLogo = s.insertParagraph(parPosition+3, text.substring(placeholderEnd+1));
afterLogo.merge(); // merge these two paragraphs

// finally remove the original paragraph
parent.removeFromParent(); // remove the original paragraph

它不完整,我还应该复制所有属性。 更重要的是,它不会复制选项卡设置(例如中心选项卡)。还没有找到设置标签位置的方法。