Reputation: 1807
So , I am trying to insert date and time in google docs and using the following google apps script to do that. I found this script in this site and edited a little bit. It's does the job. But my problem is, after the script is run the cursor stays at the same place, I want it to go the start of the next new line. Also the formatting to the page is stuck to the specified in the script, I want it to change like changing the font and size, reset bold etc. How do I do that?
function onOpen() {
// Add a menu with some items, some separators, and a sub-menu.
DocumentApp.getUi().createMenu('Utilities')
.addItem('Insert Date', 'insertAtCursor')
.addToUi();
}
function insertAtCursor() {
var cursor = DocumentApp.getActiveDocument().getCursor();
if (cursor) {
var date = Utilities.formatDate(new Date(), "GMT+5:30", " MMMMM,dd \nhh:mm a \n");
var element = cursor.insertText(date);
if (element) {
element.setBold(true).setItalic(true).setForegroundColor("#A32929");
element.setFontSize(16).setFontFamily('Cambria');
} else {
DocumentApp.getUi().alert('Cannot insert text at this cursor location.');
}
} else {
DocumentApp.getUi().alert('Cannot find a cursor in the document.');
}
}
Upvotes: 0
Views: 577
Reputation: 62
If you want your cursor to go the next line then somewhere in your code you have to assign a new position to the cursor. You do this with .setCursor(Position). Read more on that here.
The reason your formatting does not change is that can only run one formatting execution per line.
function insertAtCursor() {
var cursor = DocumentApp.getActiveDocument().getCursor();
if (cursor) {
var date = Utilities.formatDate(new Date(), "GMT+5:30", " MMMMM,dd \nhh:mm a \n");
var element = cursor.insertText(date);
if (element) {
element.setBold(true);
element.setItalic(true);
element.setForegroundColor("#A32929");
element.setFontSize(16);
element.setFontFamily('Cambria');
} else {
DocumentApp.getUi().alert('Cannot insert text at this cursor location.');
}
} else {
DocumentApp.getUi().alert('Cannot find a cursor in the document.');
}
var position = doc.newPosition('your new position');
doc.setCursor(position);
}
Hope this helps.
Upvotes: 1