HighHopes
HighHopes

Reputation: 2102

How to insert and center text in Google Docs with script

I want to make a script that inserts text like this at the end of my document:

                            February 18, 2015
                                  Title
   Entry

Where the first two lines are centered and the last line is indented with a tab.

This is what I have so far:

  function addJournalTemplate(){
  var currDate = new Date();
  var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
  var dateString = months[currDate.getMonth()] + ' ' + (currDate.getDate() < 10 ? '0' + currDate.getDate() : currDate.getDate()) + ', ' + currDate.getYear(); 
  var doc = DocumentApp.getActiveDocument();
  var dateText = doc.getBody().editAsText().appendText(dateString);

  var title = doc.getBody().insertParagraph(1, 'Title');
  title.setAlignment(DocumentApp.HorizontalAlignment.CENTER);
}

And that code doesn't work at all. I am lost and have been searching developers.google.com for about an hour now.

How can I do this?

Upvotes: 1

Views: 4861

Answers (1)

Hann
Hann

Reputation: 713

i modified your script.

your prob :

var dateText = doc.getBody().editAsText().appendText(dateString);

You can't center with this method, it's better to use the method ( insertParagraph() )

function addJournalTemplate(){
  var currDate = new Date();
  var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
  var dateString = months[currDate.getMonth()] + ' ' + (currDate.getDate() < 10 ? '0' + currDate.getDate() : currDate.getDate()) + ', ' + currDate.getYear(); 

  var doc = DocumentApp.openById('myid');
  var dateText = doc.getBody().insertParagraph(1,dateString);
  dateText.setAlignment(DocumentApp.HorizontalAlignment.CENTER);

  var title = doc.getBody().insertParagraph(2, 'Title');
  title.setAlignment(DocumentApp.HorizontalAlignment.CENTER);
  return doc;
}

Upvotes: 3

Related Questions