iDevFS iDevFS - 2 years ago 141
Javascript Question

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

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?



Answer Source
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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download