如何使用 Google Apps 脚本在文档中获取多个 headers/footers

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

我正在尝试替换 Google 文档页眉中的文本,其中 "Different first page Header/Footer" 处于活动状态。我成功地替换了除第一页以外的任何其他页眉中的文本。 ...

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

...

我查看了文档,但没有看到如何操作。我什至尝试使用 "getHeaders()"(复数形式),但 class 不存在。 如何替换第一页中的文字 header/footer?

谢谢,

伊万

copyHeader.getParent().getChild(2); //I'm using your variable

这将指向第一页页眉getChild(2) 中的“2”可能有所不同,但我在此答案的第三个代码块中添加了一个函数 seeChildren()

如果您要替换文档中某个字符串的所有实例,请将其与 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

如果您想知道 页脚 getChild(x) 的 x,

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

这将附加文档子项的名称(DocumentBodySection、HeaderSection、HeaderSection、FooterSection、FooterSection 等)及其在正文部分的各自索引(0、1、2、...、子项数减去1).另请注意,这使用 getActiveDocument(),文件必须打开才能使函数工作。

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

这将指向第一个不同页面上的页眉。