【发布时间】:2015-10-08 08:21:03
【问题描述】:
考虑接下来 3 行所代表的文档。
..一些文字..
6 7 8 9 10 11
..一些文字..
想象所有数字都是它们各自的字体大小(即 10 是字体大小 10)。现在我想在 8 和 9 之间的空间中插入一个内联图像,并删除该空间,但不破坏未受影响文本的格式(本示例中的大小)。结果是
..一些文字..
6 7 89 10 11
..一些文字..
但是,当我尝试时
function placeImage() {
var s = DocumentApp.getActiveDocument().getBody();
//Find in Document
var found = s.findText("8");
if(found==null)
return 0;
var foundLocation = found.getStartOffset(); //position of image insertion
//Get all the needed variables
var textAsElement = found.getElement();
var text = textAsElement.getText();
var paragraph = textAsElement.getParent();
var childIndex = paragraph.getChildIndex(textAsElement); //gets index of found text in paragraph
//Problem part - when removing the space, destroys all formatting
var textRemaining = text.substring(foundLocation + 2);
textAsElement.deleteText(foundLocation, text.length-1);
if(textRemaining != "")
paragraph.insertText(childIndex+1, textRemaining);//destroys formatting for the rest of the child index
//Insert image
var imgSource = UrlFetchApp.fetch("https://upload.wikimedia.org/wikipedia/commons/thumb/1/1f/Red_information_icon_with_gradient_background.svg/48px-Red_information_icon_with_gradient_background.svg.png");
var ingBlob = imgSource.getBlob();
paragraph.getChild(childIndex+1).insertInlineImage(foundLocation, ingBlob);
}
问题是当我删除空格并在段落中创建另一个子元素以插入图像时,子字符串也会删除剩余的文本格式。我曾尝试研究 copy(),但我不确定它如何有效地工作。
我研究了许多其他地方,here 的两个答案都没有保留格式,并且 position.insertInlineImage() 似乎被破坏了,正如here 所问的那样。
【问题讨论】:
-
您从哪里获得 logoResult 值?它包含文档中的什么元素?请更新并添加详细信息。
-
糟糕!对不起,它应该被找到。
-
感谢您的更新。将尝试找到一些可能的解决方案。
-
太棒了!我在问题的末尾添加了一个句子,其中的解决方案(还)不起作用,也许解决其中一个也可以帮助您解决这个问题。
标签: google-apps-script string-formatting children deep-copy inline-images