Search code examples
google-apps-scriptgoogle-docs

Header not clearing in Google Apps script


I am working on making a document template that outputs the name of the document in the header. For some reason it is outputting the name of the document twice. The problem I am having is weird and I will try my best to describe it. When I run my code on a blank document it works fine, but when I run it again on that same document to update it, the name appears twice like in the picture, the same happens for any other time after that even what starting with two names on the page. This only happens when I open/refresh the document but not when I run the onOpen function in the script editor.

function onOpen(){
    var doc = DocumentApp.getActiveDocument();
    var name = doc.getName();
    var header= doc.getHeader() || doc.addHeader();
    var footer = doc.getFooter() || doc.addFooter();
  
    //Clear Header
    try {
       header.clear();         
      } catch (e) {
       // case last element in header is partial and can't be cleared
       header.appendParagraph(" ");
       header.clear();
      }
    //Clear Footer
    try { 
      footer.clear();  
      } catch (e) {
       // case last element in footer is partial and can't be cleared
       footer.appendParagraph(" ");
       footer.clear();
      }
  
  
    //create style for header
    var headStyle = {};
    headStyle[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.LEFT;
    headStyle[DocumentApp.Attribute.FONT_FAMILY] = 'Georga';
    headStyle[DocumentApp.Attribute.FONT_SIZE] = 14;
    headStyle[DocumentApp.Attribute.VERTICAL_ALIGNMENT] = DocumentApp.VerticalAlignment.CENTER;
    //output header
    var headerPar = header.appendParagraph(name + " ");
    //set style to header
    headerPar.setAttributes(headStyle);
}

Here is a picture of the output

Thanks for the help!


Solution

  • Hmmm - I just ran your code and it worked great, only returned 1 header.

    Before I ran it, I thought the problem would be that you are calling .appendParagraph() twice - on definition, and also on setAttributes().

    You could try one of these two edits:

    //output header & set style to header
        var headerPar = header.appendParagraph(name + " ").setAttributes(headStyle);

    or

    //output header
      var headerPar = header.appendParagraph(name + " ");
    //set style to header
      header.setAttributes(headStyle);