6

I want to add the current date to a document footer automatically in Google Docs.

All I found was this script:

/**
 * The onOpen function runs automatically when the Google Docs document is
 * opened. Use it to add custom menus to Google Docs that allow the user to run
 * custom scripts. For more information, please consult the following two
 * resources.
 *
 * Extending Google Docs developer guide:
 *     https://developers.google.com/apps-script/guides/docs
 *
 * Document service reference documentation:
 *     https://developers.google.com/apps-script/reference/document/
 */
function onOpen() {
  // Add a menu with some items, some separators, and a sub-menu.
  DocumentApp.getUi().createMenu('Utilities')
      .addItem('Insert Date', 'insertAtCursor')
      .addToUi();
}

/**
 * Inserts the date at the current cursor location in boldface.
 */
function insertAtCursor() {
  var cursor = DocumentApp.getActiveDocument().getCursor();

  if (cursor) {
    // Attempt to insert text at the cursor position. If insertion returns null,
    // then the cursor's containing element doesn't allow text insertions.
    var date = Utilities.formatDate(new Date(), "GMT", "'Atualizado em: 'dd-MM-yyyy' 'HH:mm:ss"); // "yyyy-MM-dd'T'HH:mm:ss'Z'"
    var element = cursor.insertText(date);
    if (element) {
      element.setBold(true);
    } else {
      DocumentApp.getUi().alert('Cannot insert text at this cursor location.');
    }
  } else {
    DocumentApp.getUi().alert('Cannot find a cursor in the document.');
  }
}

But I have to press a button in the menu it creates, and the date is added to the cursor location.

What I want is to add it to the footer every time the doc is opened.

1

1 Answer 1

5

I was really surprised Google doesn't have an add date feature. This would work. Do note that it clears the footer and adds the current date every time you open the document for editing. It should run with simple triggers, but you may have to run it from the scripts interface the first time to give it permissions.

function onOpen() {
  var doc = DocumentApp.getActiveDocument();
  var footer = doc.getFooter();  //gets the footer
  footer.clear();  //clears all data in footer

  //Get date
  var date = new Date();
  var month = date.getMonth()+1;
  var day = date.getDate();
  var year = date.getFullYear();
  var hour = date.getHours()+1;
  var minute = date.getMinutes()+1;

  footer.appendParagraph(month+'/'+day+'/'+year);  //adds date to footer
 }
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.