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

笑着哭i 提交于 2019-12-11 10:39:52

问题


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


回答1:


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.




回答2:


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

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



来源:https://stackoverflow.com/questions/30877330/how-to-get-multiple-headers-footers-in-a-document-with-google-apps-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!