How to get multiple headers/footers in a document with Google Apps Script

2.9k Views Asked by At

Im trying to replace a text in a Google Document header which has "Different first page Header/Footer" active. I succesfully replace text in any other page header except on first page. ...

var something = "Some string.";
var copyId = DriveApp.getFileById(docTemplate).makeCopy(name).getId();
var copyDoc = DocumentApp.openById(copyId);
var copyHeader = copyDoc.getHeader();
copyHeader.replaceText('keySomething', something);

...

I looked at the documentation but didn't see how to do it. I even tried with "getHeaders()" (in plural) but that class doesn't exist. How I can replace the text in the first page header/footer?

Thanks,

Iván

2

There are 2 best solutions below

0
On BEST ANSWER
copyHeader.getParent().getChild(2); //I'm using your variable

This will point to the header on the first page. The "2" in getChild(2) may or may not vary but I have added a function, seeChildren(), on the third block of code in this answer.

If you are trying to replace all instances of a string in the document, use this with replaceText()

copyHeader.getParent(); /*this points to the whole document (unless the 
                          header's parents is not the whole)*/
//getbody(), getfooter(), etc (i.e. siblings of header) should work

If you want to know the x of getChild(x) for the footer,

function seeChildren(){
  var doc = DocumentApp.getActiveDocument();
  var bod = doc.getBody();
  var fol = bod.getParent();
  for (i = 0; i<fol.getNumChildren(); i++){
    var child = fol.getChild(i);
    bod.appendParagraph(child + ": Index " + fol.getChildIndex(child));
  }
}

This will append the names of the document's children (DocumentBodySection, HeaderSection, HeaderSection, FooterSection, FooterSection, etc) and their respective indices on the body section (0,1,2,...,number of children minus 1). Also, note that this uses getActiveDocument(), the file must be open for the function to work.

0
On
copyHeader.getParent().getChild(3).replaceText('current text','new text');

This will point to the header on the first different page.