Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 579
Daisuki Honey Avatar asked Nov 15 '14 10:11

Daisuki Honey


1 Answers

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();
}
like image 139
Serge insas Avatar answered Nov 15 '22 01:11

Serge insas