Internet & Technology

Google Documents – How to Replace Text in Header and Footer

How to find and replace text in the Word document’s header and footer section using the Google Document API.

Published in: Google DocsGoogle Apps Script

The upcoming release of Document Studio includes support for adding markers in the header, footer and the footnotes section of your Microsoft Word template. The add-on will automatically replace this placeholder text with actual values sourced from Google Sheets or Google Forms.

This Apps Script snippet uses the Google Docs API to find and replace multiple blocks of text in the header and footer section of your Google Document. The header and footer sections are children of the parent DOCUMENT section.

const replaceHeaderFooter = () => {
  const doc = DocumentApp.openById("DOCUMENT ID");

  const parent = doc.getHeader().getParent();

  for (let i = 0; i < parent.getNumChildren(); i += 1) {
    const child = parent.getChild(i);

    const childType = child.getType();

    if (childType === DocumentApp.ElementType.HEADER_SECTION) {
      child.asHeaderSection().replaceText("{{Company}}", "Digital Inspiration");
    } else if (childType === DocumentApp.ElementType.FOOTER_SECTION) {
      child.asFooterSection().replaceText("{{Copyright}}", "© Amit Agarwal");


If the current document doesn’t include an header section, the getHeader() function will return null so you may wish to include additional checks to determine whether a document has an header or footer.

Source link

Comment here