How can I move the cursor to the beginning of the document with Google Apps Script for Docs?

我怕爱的太早我们不能终老 提交于 2019-12-10 13:47:12

问题


I am writing a script of Google Apps Script with my Google Document and wondering how to move the cursor to the very beginning of the document. What I was trying to do at the end is just replace the first line with some string.


回答1:


This is very simple, you can use the setCursor() method documented here.

Example code :

function setCursorToStart() {
 var doc = DocumentApp.getActiveDocument();
 var paragraph = doc.getBody().getChild(0);
 var position = doc.newPosition(paragraph.getChild(0), 0);
 doc.setCursor(position);
}

This will set the cursor position to the start of your document but in your question you say you want to insert some data at this position, then the actual cursor position is irrelevant, you can insert a string there without necessarily moving the cursor . Example code :

function insertTextOnTop() {
  var doc = DocumentApp.getActiveDocument();
  var top = doc.getBody().getChild(0);
  top.asParagraph().insertText(0,'text to insert');
  doc.saveAndClose();
}


来源:https://stackoverflow.com/questions/26945026/how-can-i-move-the-cursor-to-the-beginning-of-the-document-with-google-apps-scri

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!