在段落的特定点插入图像

wiv*_*vku 6 google-docs google-apps-script

*我有一个带有"text {logo} text"字样的Google文档.如何将图片放在{logo}所在的位置?到目前为止我试过:

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

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

小智 6

我希望会有所帮助,以下代码对我来说没问题.

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);
}
Run Code Online (Sandbox Code Playgroud)


wiv*_*vku 3

感谢 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
Run Code Online (Sandbox Code Playgroud)

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