在特定位置添加段落

时间:2014-12-17 01:34:17

标签: javascript google-app-engine google-apps-script google-docs

我需要能够将一串文本更改为heading1,然后再进行一些额外的格式化。暂时抓住这一部分。这是我现在的示例代码。

function pocket() {
    // Try to get the current selection in the document. If this fails (e.g.,
    // because nothing is selected), show an alert and exit the function.
    var selection = DocumentApp.getActiveDocument().getSelection();
    var body = DocumentApp.getActiveDocument().getBody();
    if (!selection) {
        DocumentApp.getUi().alert('Cannot find a selection in the document.');
        return;
    }
    var selectedElements = selection.getSelectedElements();
    var selectedElement = selectedElements[0];
    var pocketelement = selectedElement.getElement().getText();
    body.appendParagraph(pocketelement).setHeading(DocumentApp.ParagraphHeading.HEADING1);
}

我需要它来删除原始字符串并将段落附加到原始字符串位置。不知道该怎么做。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:8)

body.appendParagraph()方法将给定的段落(如javascript)追加<+ strong>到主体的末尾。

您正在寻找.insertParagraph(索引,段落)。要获取索引,请尝试body.getChildIndex(段落)。请参阅下面的代码。

function pocket() {
  // Try to get the current selection in the document. If this fails (e.g.,
  // because nothing is selected), show an alert and exit the function.
  var doc = DocumentApp.getActiveDocument();
  var selection = doc.getSelection();
  var body = doc.getBody();
  if (!selection) {
      DocumentApp.getUi().alert('Cannot find a selection in the document.');
      return;
  }
  var selectedElements = selection.getSelectedElements();
  var selectedElement = selectedElements[0];
  //holds the paragraph
  var paragraph = selectedElement.getElement();
  //get the index of the paragraph in the body
  var paragraphIndex = body.getChildIndex(paragraph);
  //remove the paragraph from the document
  //to use the insertParagraph() method the paragraph to be inserted must be detached from the doc
  paragraph.removeFromParent();
  body.insertParagraph(paragraphIndex, paragraph).setHeading(DocumentApp.ParagraphHeading.HEADING1);
};