Google Apps 脚本:如何复制文本并保留格式?

Google Apps Script: How to copy text and preserve formatting?

考虑下 3 行表示的文档。

..一些文字..
6 7 8 9 10 11
..一些文字..

假设所有数字都是它们各自的字体大小(即 10 是字体大小 10)。现在我想在 8 和 9 之间的 space 中插入一个内联图像,并删除 space,但不要破坏未受影响文本的格式(本例中的大小)。结果将是

..一些文字..
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);
}

问题是,当我删除 space 并在段落中创建另一个子元素以插入图像时,子字符串也会删除剩余的文本格式。我已经尝试查看 copy(),但我不确定它如何有效地工作。

我研究了很多其他地方,两个答案here don't preserve formatting, and position.insertInlineImage() seems to be broken, as asked here

主要看你文档的内容是怎么设置段落的。尝试在文档中使用简单的内容并插入图像。

插入图像效果很好,也没有改变其余文本的格式。

检查下面的代码:

function placeImage()
 {
 var s = DocumentApp.getActiveDocument().getBody();
 var number = '8'
 //Find in Document
 var found = s.findText(number);
 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.asText().copy();// getText();
 textAsElement.editAsText().deleteText(foundLocation + number.length  ,textAsElement.asText().getText().length -1)

text.asText().editAsText().deleteText(0, foundLocation + 1 );
 //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();

 var children =DocumentApp.getActiveDocument().getBody().getChild(0).asParagraph().appendInlineImage(ingBlob);

 DocumentApp.getActiveDocument().getBody().getChild(0).asParagraph().appendText(text);

 var child = DocumentApp.getActiveDocument().getBody().getNumChildren();


}

测试的文档内容为:

6 7 8 9 10 11

(文本的大小与您提到的相似。'8' 是大小 8,依此类推)

您必须根据您的文档内容使用试错法进行测试。

希望对您有所帮助!