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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With