0
votes

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!

1
Your code works for me. Try manually clearing your header and then reloading it multiple times? - J. G.
Although I'm not sure whether this is the direct reason of your issue, I thought that in your situation, I'm worry about that you might install the function of onOpen as the installable event trigger. If it's so, the function onOpen is run 2 times by the simple trigger and the installable trigger. So such issue occurs. Can you confirm about this? If you have installed the function of onOpen as the installable trigger, please remove the trigger. By this, onOpen is run one time as the simple trigger. - Tanaike

1 Answers

0
votes

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);