Monday, June 10, 2013

Google Docs - Inserting Date in the Footer

Now that Google Drive Documents support scripts, it is possible to, say, create a footer that contains the date that the document was last accessed.

In your Google Doc, click Tools | Script Editor.

Copy/paste the code below, and save the script.


/**
 * The onOpen function runs automatically when the Google Docs document is
 * opened. It will add a "Tools" menu with an "Update Footer" option. It also
 * (automatically) updates the date in the footer as soon as the documents is
 * opened. (WARNING: Any footer content will be removed/deleted.)
 */
function onOpen() {
  // Add a menu with some items, some separators, and a sub-menu.
  DocumentApp.getUi().createMenu('Scripts')
      .addItem('Update Footer', 'onEdit')
      .addToUi();
  onEdit();
};
function onEdit() {
  var doc = DocumentApp.getActiveDocument();
  var footer = (doc.getFooter()) ? doc.getFooter() : doc.addFooter(); // Thanks, Martin!
  footer.setText("");
  var divider = footer.appendHorizontalRule();
  var footerText = footer.appendParagraph('Confidential and Proprietary - Accessed ' + new Date());
  footerText.setFontSize(9);
  footerText.setForegroundColor('#4a86e8');
  footerText.setAlignment(DocumentApp.HorizontalAlignment.RIGHT);
  return doc;
};


Return to your document, and reload it; the footer will automatically be created.  (NOW it will! Thanks, Martin!)  If you want to update the footer, you can click the Script | Update Footer menu item.

That I know of, there isn't yet an "onSave" or "onEdit" trigger in Google Documents - but, if that comes about, this will be an even more awesome tool! (*hint,hint, Google!)  You CAN, however, use a "clock tick event" but I haven't gone there yet.

8 comments :

  1. Nice. A slight modification to your code to addFooter if not already there could be

    var footer = (doc.getFooter()) ? doc.getFooter() : doc.addFooter();

    https://gist.github.com/mhawksey/9659908

    ReplyDelete
    Replies
    1. Great point, Martin! I had said that the footer would be created, but your code makes that happen. Thanks for the tip!

      Delete
  2. Thanks for this, this was useful.

    ReplyDelete
  3. Hello I need the same, but with the date of last edit.
    thank uuuu

    ReplyDelete
  4. Without fail, your writing style is top professional; even your website also looks amazing thank you for posting. Binary Today

    ReplyDelete