Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

Thanks,

Iván

like image 727
iDevFS Avatar asked Oct 20 '25 09:10

iDevFS


2 Answers

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.

like image 189
Jose Luis Santos Blaquera Avatar answered Oct 21 '25 22:10

Jose Luis Santos Blaquera


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

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

like image 43
Franz Joseph Avatar answered Oct 21 '25 23:10

Franz Joseph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!