我试图从findText的结果插入一个段落中间的图像,但是当在段落之前有其他图像时,它不会按计划工作。
目前,我的代码(部分基于对这个问题的回答)通过查找需要插入的位置,然后获取findText()返回的段落的子索引来工作。但是,如果有内联图像,则返回子索引作为段落的开始,但是findText的偏移量是图像末尾的字符,而不是段落的开始。
下面是脚本的相关部分:
function placeImage(start, end) {
var d = DocumentApp.getActiveDocument()
var s = d.getBody();
var logoResult = s.findText(start);
var placeHolderStart = logoResult.getStartOffset(); //position of image insertion
var logoResult2 = s.findText(end, logoResult);
var placeHolderEnd = logoResult2.getStartOffset(); //text between placeHolderStart and placeHolderEnd will be permanently deleted
var textElement = logoResult.getElement();
var paragraph= textElement.getParent();
var childIndex = paragraph.getParent().getChildIndex(paragraph); //gets paragraph number
var par = s.getChild(childIndex).asParagraph(); //entire paragraph containing point of insertion
var parcopy = par.copy();
var totalLen = par.editAsText().getText().length-1;
par.editAsText().deleteText(placeHolderStart, totalLen); //delete all text after insertion point; some will be added back later from parcopy
parcopy.editAsText().deleteText(0, placeHolderEnd + 1); //this would be the remaining text that gets pasted at the end
var resp = UrlFetchApp.fetch("https://www.google.com/images/srpr/logo11w.png");
var logoBlob = resp.getBlob();
var img = s.getChild(childIndex).appendInlineImage(logoBlob);
var toMerge = s.insertParagraph(childIndex+1, parcopy);
toMerge.merge();
return 1;
}
一个段落包含几个子元素,例如文本字符串或图像。您需要获得段落内文本元素的索引,而不是文档内段落的索引。试试这个
function placeImage(start, end) {
var d = DocumentApp.getActiveDocument()
var s = d.getBody();
var logoResult = s.findText(start);
var placeHolderStart = logoResult.getStartOffset(); //position of image insertion
var logoResult2 = s.findText(end, logoResult);
var placeHolderEnd = logoResult2.getEndOffsetInclusive(); //text between placeHolderStart and placeHolderEnd will be permanently deleted
var textElement = logoResult.getElement();
var text = textElement.getText();
var paragraph = textElement.getParent();
var childIndex = paragraph.getChildIndex(textElement); //gets index of text element in paragaph
var textSecondHalf = text.substring(placeHolderEnd + 1);
textElement.deleteText(placeHolderStart, text.length-1);
paragraph.insertText(childIndex+1, textSecondHalf);
var resp = UrlFetchApp.fetch("https://www.google.com/images/srpr/logo11w.png");
var logoBlob = resp.getBlob();
paragraph.insertInlineImage(childIndex+1, logoBlob);
}