In our previous articles (Episodes #51 to #58), we walked through how to automate invoice generation for the Sapporo office using Google Docs—covering text replacement, heading setup, font styling, detail tables, and even inserting company seal images.
While our invoice body is now nearly complete, there is one more essential element required for official business documents: the header (the top margin area of the page) and the footer (the bottom margin area)!
“I want to display the company name and support contact at the top or bottom of every page.” “I want to automatically insert page numbers like ‘Page 1 of 2’ into the footer.”
Entering these details manually on every single page is tedious and easily leads to misaligned page numbers whenever the document length changes.
In this 59th installment, we will take a deep dive into Document.addHeader() and Document.addFooter()—the must-know Google Apps Script methods to automatically create header/footer sections in Google Docs and insert contact information alongside dynamic page numbers!
We’ll cover everything beginner developers need to know, including common error workarounds when a header already exists, right down to techniques for displaying dynamic page counts clearly and step by step.
1. What Are Document.addHeader() and addFooter()?
Document.addHeader() and Document.addFooter() are methods used to create and retrieve the HeaderSection and FooterSection areas across an entire Google Document.
Understanding Document Structure: The House, Room, and Furniture Analogy
Let’s organize the structure of a Google Document using our familiar “House, Room, and Furniture” analogy from this series.
- [The House] = The Entire Document (Document)
- The entire document file opened with
DocumentApp.openById().
- The entire document file opened with
- [The Rooms] = Area Sections (Body / HeaderSection / FooterSection)
- Body Area (Body): The primary room where paragraphs, tables, and images reside.
- Header Room (HeaderSection): A specialized room positioned in the top margin of the page. ★ Today’s star!
- Footer Room (FooterSection): A specialized room positioned in the bottom margin of the page. ★ Today’s star!
- [The Furniture] = Paragraphs, Text, and Page Numbers
- The content placed inside each room, such as sentences, logo images, and page numbers.
Methods like body.appendParagraph() that we usually work with are actions performed inside the “Body” room. Calling addHeader() or addFooter() is like adding brand-new dedicated auxiliary rooms at the very top and bottom of the entire house (Document).
Basic Syntax for Headers and Footers
// 1. Open the document (the house)
var doc = DocumentApp.openById("DOCUMENT_ID");
// 2. Create and get the header area (top room)
var header = doc.addHeader();
// 3. Create and get the footer area (bottom room)
var footer = doc.addFooter();
Once created, header and footer work almost identically to the standard body object: you can append text using .appendParagraph(), adjust font sizes, and change alignment (left, right, or center).
2. STEP 1: Preparation! Create the Sapporo Office Invoice Document
First, let’s prepare a practice document to manipulate with GAS.
If you already have the “Sapporo Office Invoice Template” built during Episodes #51 through #58, feel free to use it. If not, follow these quick steps to create a new one.
Steps
- Create a new Google Doc in Google Drive and name it “[Sapporo Office] Invoice Template”.
- Enter some simple sample text into the body like this:
INVOICE
Issue Date: September 23, 2026
Billed To: Hokkaido Solutions Inc.
Total Amount Due: $1,540.00 (Tax Included)
Thank you for your business. Please find the details of our invoice below.
(* Imagine the breakdown table and company seal from Episodes #56-#58 placed here)
- Get the Document ID: Copy the long alphanumeric string between
/d/and/editfrom your browser’s address bar.
https://docs.google.com/document/d/[YOUR_DOCUMENT_ID_HERE]/edit
3. STEP 2: [Hands-on] Run a Script to Add a Header and Footer!
Now that your document is ready, open the Apps Script editor and let’s write some code!
In this exercise, we will automatically apply two elements to our Sapporo office invoice:
- Header (Top): Right-aligned label reading
[Sapporo Office Official Invoice] - Footer (Bottom): Center-aligned contact info reading
Sapporo Office Contact Desk: 011-XXX-XXXX | support@sapporo.example.com
1. Enter the Code
Open your bound script editor or a standalone project at script.google.com, and paste the following script. * Make sure to replace YOUR_DOCUMENT_ID with the ID you copied in STEP 1.
function addInvoiceHeaderAndFooter() {
// 1. Open the file (house) by specifying the Document ID
var docId = "YOUR_DOCUMENT_ID"; // * Replace with your Document ID
var doc = DocumentApp.openById(docId);
// 2. Retrieve header section (or create if none exists)
var header = doc.getHeader();
if (!header) {
header = doc.addHeader();
} else {
header.clear(); // Clear existing content if it already exists
}
// 3. Append text to header, set right alignment and font styling
var headerPara = header.appendParagraph("[Sapporo Office Official Invoice]");
headerPara.setAlignment(DocumentApp.HorizontalAlignment.RIGHT);
headerPara.setFontSize(9);
headerPara.setForegroundColor("#666666"); // Gray text
// 4. Retrieve footer section (or create if none exists)
var footer = doc.getFooter();
if (!footer) {
footer = doc.addFooter();
} else {
footer.clear(); // Clear existing content if it already exists
}
// 5. Append contact text to footer and center-align it
var footerPara = footer.appendParagraph("Sapporo Office Contact Desk: 011-XXX-XXXX | support@sapporo.example.com");
footerPara.setAlignment(DocumentApp.HorizontalAlignment.CENTER);
footerPara.setFontSize(9);
footerPara.setForegroundColor("#333333");
// 6. Output completion log
Logger.log("Header and footer added successfully!");
}
2. Step-by-Step Code Breakdown
Let’s break down the key parts of the code so everyone can follow along comfortably:
var header = doc.getHeader(); if (!header) { header = doc.addHeader(); }- This is an essential production-grade pattern!
- In Google Apps Script, executing
doc.addHeader()on a document that already has a header causes an immediate runtime error: “Header already exists”. - To prevent failures, we first verify whether a header exists using
getHeader(). If it does not, we create it viaaddHeader(); if it already exists, we safely wipe previous content withheader.clear().
header.appendParagraph("[Sapporo Office Official Invoice]");- Appends a new paragraph (furniture) inside the header section (room) and writes our label text.
headerPara.setAlignment(DocumentApp.HorizontalAlignment.RIGHT);- Sets text alignment to the right. (Use
CENTERfor centered alignment, orLEFTfor left-aligned text.)
- Sets text alignment to the right. (Use
headerPara.setFontSize(9);/setForegroundColor("#666666");- Applies our Episode #55 styling skills by setting the text to a modest 9pt font in subtle gray, keeping it elegant without distracting from the main invoice body.
3. Save and Run
- Click the Save icon (floppy disk) in the Apps Script toolbar.
- Ensure the selected function dropdown is set to
addInvoiceHeaderAndFooter, then click Run. - If this is your first execution, an authorization dialog will appear. Follow the prompts to grant document permissions (see Episode #2 for details).
[Verify the Results] Switch over to your Google Doc to view the changes!
- A subtle, gray, right-aligned label
[Sapporo Office Official Invoice]appears in the top margin area! - A centered line
Sapporo Office Contact Desk: 011-XXX-XXXX | support@sapporo.example.comappears in the bottom margin area!
Without disrupting any text or tables in the body, your document margins now display clean, well-aligned branding and contact info!
4. STEP 3: Advanced Real-World Header and Footer Techniques
Beyond static text, let’s explore three practical techniques commonly required in professional production workflows.
Technique 1: Insert Dynamic Page Numbers with appendPageNumber()
Multi-page invoices, contracts, and proposals almost always require accurate page numbers (such as “Page 1 of 2”).
Google Apps Script provides dedicated methods—appendPageNumber() and appendPageCount()—specifically for outputting dynamic page numbers!
function addPageNumberToFooter() {
var doc = DocumentApp.openById("YOUR_DOCUMENT_ID");
// Retrieve or create footer
var footer = doc.getFooter() || doc.addFooter();
footer.clear(); // Clear existing content
// Create paragraph (center-aligned)
var para = footer.appendParagraph("");
para.setAlignment(DocumentApp.HorizontalAlignment.CENTER);
para.setFontSize(9);
// 1. Add literal text "Page "
para.appendText("Page ");
// 2. Insert current page number (1, 2, 3...) dynamically!
para.appendPageNumber();
// 3. Add separator " of "
para.appendText(" of ");
// 4. Insert total page count (e.g., 2) dynamically!
para.appendPageCount();
}
Why This Matters!
If you simply write para.appendText("1"), every single page will display a hardcoded “1”. Elements inserted via para.appendPageNumber(), however, are treated as dynamic fields computed automatically by Google Docs. As a result, page 2 displays “2” and page 3 displays “3” without any extra manual work!
Technique 2: Split Left and Right Content Using a Borderless Table
A common design requirement is placing contact info on the left side of the footer while right-aligning page numbers on the same line.
Normally, a single paragraph can only be either left-aligned or right-aligned. The pro secret to solving this layout puzzle is to insert a 1-row, 2-column borderless table into the footer!
function addTwoColumnFooter() {
var doc = DocumentApp.openById("YOUR_DOCUMENT_ID");
var footer = doc.getFooter() || doc.addFooter();
footer.clear();
// Create a 1-row, 2-column table in the footer
var table = footer.appendTable([
["Sapporo Office Contact Desk: 011-XXX-XXXX", ""]
]);
// Set border width to 0 to make borders invisible
table.setBorderWidth(0);
// Configure left cell (column 0)
var leftCell = table.getCell(0, 0);
leftCell.getChild(0).asParagraph().setFontSize(8).setForegroundColor("#666666");
// Configure right cell (column 1) with right-aligned page numbering
var rightCell = table.getCell(0, 1);
var rightPara = rightCell.getChild(0).asParagraph();
rightPara.setAlignment(DocumentApp.HorizontalAlignment.RIGHT);
rightPara.setFontSize(8);
rightPara.setForegroundColor("#666666");
rightPara.appendText("Page ");
rightPara.appendPageNumber();
rightPara.appendText(" of ");
rightPara.appendPageCount();
}
Running this script neatly positions your contact information along the left margin and Page 1 of 2 along the right margin. The table manipulation skills we practiced in Episodes #56 and #57 prove useful here as well!
Technique 3: Add a Divider Line Under the Header
Drawing a subtle horizontal rule beneath your header text gives your document an instant polish and structure.
function addHeaderWithHorizontalLine() {
var doc = DocumentApp.openById("YOUR_DOCUMENT_ID");
var header = doc.getHeader() || doc.addHeader();
header.clear();
// Add header text
var para = header.appendParagraph("Sapporo Office Official Document");
para.setFontSize(9).setForegroundColor("#444444");
// Append horizontal rule to bottom of header
header.appendHorizontalRule();
}
Calling header.appendHorizontalRule() automatically draws a crisp divider separating the header space from the main document body.
5. 5 Common Pitfalls Beginners Face and How to Solve Them
When working with Document.addHeader() and addFooter(), beginners often encounter a few recurring traps. Let’s review them and keep your scripts error-free!
Trap 1: The Program Crashes with Exception: Header already exists
[Cause]
Attempting to call doc.addHeader() on a document that already contains a header triggers a built-in GAS exception.
[Solution]
As demonstrated earlier, write defensive code by checking for an existing header with getHeader() before invoking addHeader()!
// Safe and recommended approach
var header = doc.getHeader() || doc.addHeader();
Trap 2: Calling body.addHeader() Results in a TypeError
[Cause]
Trying to execute addHeader() or addFooter() against the body object rather than the root document.
// Incorrect usage resulting in an error
var body = doc.getBody();
var header = body.addHeader(); // TypeError: body.addHeader is not a function
[Solution]
Headers and footers belong to the document as a whole. Always call these methods directly on the doc (Document object).
// Correct usage
var header = doc.addHeader();
Trap 3: Repeated Executions Duplicate Header Content
[Cause]
Calling .appendParagraph() repeatedly without clearing previous elements leaves old paragraphs intact, appending new text underneath them on each run.
[Solution]
Whenever you update a header or footer, call header.clear() or footer.clear() first to wipe old nodes before adding new content!
Trap 4: The Page Number Shows “1” Everywhere, Even on Page 2
[Cause]
Accidentally appending a static text string like “1” instead of a dynamic field.
// Incorrect usage (static text)
para.appendText("Page 1");
[Solution]
To generate real-time calculated page numbers, always use the dedicated para.appendPageNumber() method.
Trap 5: Unable to Hide the Header or Footer on the First Page (Cover Sheet)
In contracts or formal reports, you often want to omit headers and footers from the cover page and start displaying them on page 2.
Google Docs has a built-in “Different first page” setting. You can configure this programmatically in GAS using the following method:
// Enable a unique header/footer configuration for the first page
doc.setDifferentFirstPageHeaderFooter(true);
Adding this single line isolates the first page’s header and footer, keeping your cover page layout clean.
6. Summary and What’s Next
In this tutorial, we covered how to add headers, footers, and dynamic page numbering to Google Docs using Document.addHeader() and addFooter().
Key Takeaways
- Call
addHeader()andaddFooter()on the document object (doc), not onbody - Prevent runtime errors by using the safe pattern:
doc.getHeader() || doc.addHeader() - Reset previous content with
header.clear()before appending updated text - Insert dynamic numbering using
appendPageNumber()andappendPageCount() - Use borderless tables inside footers to split content between left and right margins
With these techniques, our Sapporo office invoice template now meets professional enterprise document standards in both visual presentation and layout!
What’s Next?
Episode #60 marks the exciting grand finale of our Google Docs automation track (Phase 6)!
Our final topic will be Document.getAs('application/pdf'): Automatically Converting Invoices to PDF and Saving to Google Drive!
We will complete our end-to-end pipeline by converting our generated Google Docs invoices into non-editable PDF files and automatically organizing them into designated Google Drive folders. Stay tuned!
