In our previous session (Episode 53), we learned how to use Body.appendParagraph() to dynamically insert new paragraphs—such as bank account details and special notes—at the bottom of our “Sapporo Office Invoice” template!
Once you start generating text automatically in Google Docs, the next challenge you will quickly face is styling and readability: organizing document structure and visual hierarchy.
If every line of text shares the exact same font size and weight, it becomes hard to distinguish where the “Billing Details” end and the “Bank Transfer Information” begins at a glance.
That is why in Episode 54, we are diving deep into Paragraph.setHeading(), an essential Google Apps Script method that allows you to instantly apply heading styles like Heading 1, Heading 2, and Title to your paragraphs!
Using our “Sapporo Office Invoice” generator as an example, we will walk through practical code snippets, useful automation patterns, and common beginner pitfalls with step-by-step guidance!
1. What Is Paragraph.setHeading()?
Paragraph.setHeading() is a Google Apps Script method used to assign or update the heading style of a specific paragraph object (Paragraph) in a Google Doc.
Understanding the Hierarchy: The “House, Room, Furniture” Analogy
Let’s review our familiar “House, Room, and Furniture” hierarchy adapted for Google Docs:
- 【Entire House】= The Document File (
DocumentApp.openById()) - 【Room】= Document Body Area (
Document.getBody()) - 【Furniture / Shelves】= Paragraphs (
Body.getParagraphs()orBody.appendParagraph()) - 【Labels / Signs on Furniture】= Heading Styles (
Paragraph.setHeading()) ★ Today’s spotlight!
Using Paragraph.setHeading() is like placing a clear, visible label on your furniture (paragraph) to organize the room and make the structure instantly recognizable.
Basic Syntax
// 1. Get or create the paragraph you want to modify
var paragraph = body.appendParagraph("Billing Details");
// 2. Set the paragraph heading style (Heading 2)
paragraph.setHeading(DocumentApp.Heading.HEADING2);
Just like when working with spreadsheets in earlier episodes, Google Apps Script uses dot notation (.) to navigate down the hierarchy and execute commands on targeted elements.
DocumentApp.Heading Enum Reference List
Inside setHeading(), you pass an enum value predefined by Google Apps Script: DocumentApp.Heading.
Here are the main heading styles you can use:
| Enum Constant (GAS Code) | Google Docs Style | Typical Use Case |
DocumentApp.Heading.TITLE | Title | Top-level title of the document (e.g., Invoice, Project Proposal) |
DocumentApp.Heading.SUBTITLE | Subtitle | Subheading immediately below the title (e.g., Issued September 2026) |
DocumentApp.Heading.HEADING1 | Heading 1 | Major sections / chapters (e.g., 1. Overview, 2. Billing Summary) |
DocumentApp.Heading.HEADING2 | Heading 2 | Mid-level sections (e.g., Billing Details, Bank Transfer Information) |
DocumentApp.Heading.HEADING3 | Heading 3 | Sub-sections (e.g., Special Notes & Terms) |
DocumentApp.Heading.HEADING4 to HEADING6 | Heading 4 to 6 | Deep nested structural sections |
DocumentApp.Heading.NORMAL | Normal text | Removes headings and resets paragraph to standard body text |
2. STEP 1: Preparation – Create the Sapporo Office Invoice Template
First, let’s prepare a test Google Doc to automate with GAS. If you already have the document created in Episodes 51–53, you can reuse it directly!
Setup Steps
- Open Google Drive and create a new Google Document.
- Name the document “Sapporo Office Invoice Template”.
- Paste the following sample text into the body:
Invoice
Sapporo Soup Curry Honpo
Thank you very much for your valued business.
Please find the billing details below.
Billing Details
1. Sapporo Clock Tower Building Network Maintenance Fee (Sept) 50,000 JPY
2. Cloud Server Operations Management Fee 30,000 JPY
Bank Transfer Information
Hokkaido Bank, Sapporo Ekimae Branch, Regular Account 1234567 Digital Wonderland Inc.
- Copy the Document ID from your browser’s address bar (the long alphanumeric string between
https://docs.google.com/document/d/and/edit).
3. STEP 2: Hands-on Practice – Apply Heading 2 to Billing Sections
Now that your document is ready, open the Apps Script editor and write your script.
Combining openById() from Episode 51 and appendParagraph() concepts from Episode 53, we will automatically set “Billing Details” and “Bank Transfer Information” to Heading 2, and the main “Invoice” text to Title style!
1. Enter the Script
Open the Script Editor and paste the code below (replace YOUR_DOCUMENT_ID with your actual Document ID).
function formatInvoiceHeadings() {
// 1. Open the target document and get the Body area
var docId = "YOUR_DOCUMENT_ID"; // <-- Replace with your own Document ID
var doc = DocumentApp.openById(docId);
var body = doc.getBody();
// 2. Retrieve all paragraphs within the document body
var paragraphs = body.getParagraphs();
// 3. Loop through each paragraph and set headings for matching text
for (var i = 0; i < paragraphs.length; i++) {
var p = paragraphs[i];
var text = p.getText();
// Set "Billing Details" and "Bank Transfer Information" to Heading 2
if (text === "Billing Details" || text === "Bank Transfer Information") {
p.setHeading(DocumentApp.Heading.HEADING2);
} else if (text === "Invoice") {
// Set the top "Invoice" line to Title style
p.setHeading(DocumentApp.Heading.TITLE);
}
}
// 4. Save changes and log completion
doc.saveAndClose();
Logger.log("Heading styles have been automatically applied!");
}
2. Step-by-Step Code Breakdown
Let’s review the key operations line by line:
var doc = DocumentApp.openById(docId);- Opens the Google Doc matching the provided ID.
var paragraphs = body.getParagraphs();- Retrieves every paragraph in the document body as an array (ordered list).
for (var i = 0; i < paragraphs.length; i++)- Loops through each paragraph from the beginning of the document to the end.
if (text === "Billing Details" || text === "Bank Transfer Information")- Checks if the plain text of the paragraph matches the target strings.
p.setHeading(DocumentApp.Heading.HEADING2);- Calls
.setHeading()on the paragraph objectpto apply Heading 2 formatting.
- Calls
3. Inspecting the Execution Result
Save your script and click the “Run” button.
Once the execution finishes, open your Google Doc to verify the changes.
【Verification Checklist】
- “Invoice” is now formatted in the prominent Title style!
- “Billing Details” and “Bank Transfer Information” are styled as clean Heading 2 sections!
- Open the Document Outline panel on the left side of Google Docs, and you will see “Billing Details” and “Bank Transfer Information” automatically listed like an interactive table of contents!
What used to be a wall of plain text is now structured into a clean, professional business document in seconds!
4. STEP 3: 3 Advanced setHeading() Patterns for Real-World Workflows
Beyond modifying existing paragraphs, let’s explore three practical patterns frequently used in production automation!
Pattern 1: Method Chaining with appendParagraph()
appendParagraph() returns the newly created Paragraph object. This allows you to chain methods together on a single line using dot notation:
function appendHeadingDirectly() {
var doc = DocumentApp.openById("YOUR_DOCUMENT_ID");
var body = doc.getBody();
// Add a paragraph and apply heading style in a single line!
body.appendParagraph("Special Notes & Cancellation Policy")
.setHeading(DocumentApp.Heading.HEADING3);
doc.saveAndClose();
}
This keeps your code concise and makes dynamically inserting sections into templates seamless.
Pattern 2: Auto-Formatting Headings Based on Prefix Symbols
In business environments, team members often draft documents using bullet marks or symbols, such as “■ Billing Amount” or “■ Payment Due Date”. You can detect these markers and automatically turn those lines into headings.
Using JavaScript’s .indexOf() or .startsWith() makes this easy to automate:
function autoHeadingBySymbol() {
var doc = DocumentApp.openById("YOUR_DOCUMENT_ID");
var body = doc.getBody();
var paragraphs = body.getParagraphs();
for (var i = 0; i < paragraphs.length; i++) {
var p = paragraphs[i];
var text = p.getText();
// Automatically set paragraphs starting with "■" to Heading 2
if (text.indexOf("■") === 0) {
p.setHeading(DocumentApp.Heading.HEADING2);
}
}
doc.saveAndClose();
}
With this script, authors only need to write standard text with marker symbols, and GAS will handle the full document hierarchy automatically.
Pattern 3: Removing Headings and Reverting to Normal Text
If a paragraph was formatted as a heading by mistake or you want to reset template styling, pass DocumentApp.Heading.NORMAL:
// Clear heading style and revert to regular body text
paragraph.setHeading(DocumentApp.Heading.NORMAL);
5. 5 Common Pitfalls with setHeading() and How to Solve Them
Here are five common traps that beginners frequently encounter when working with Paragraph.setHeading(), along with their solutions!
Trap 1: Typo in DocumentApp.Heading.HEADING2
This is the single most common syntax mistake:
// ✕ Incorrect (will cause an error)
p.setHeading(DocumentApp.Heading.HEADING_2); // No underscore needed
p.setHeading(DocumentApp.Heading.Heading2); // Must be in all caps
// ◯ Correct
p.setHeading(DocumentApp.Heading.HEADING2);
Enum constants like HEADING1 and HEADING2 must be written in uppercase without underscores. Misspelling them will trigger runtime errors like Cannot read property of undefined.
Trap 2: Calling body.setHeading() and Triggering a TypeError
// ✕ Error-producing code
body.setHeading(DocumentApp.Heading.HEADING1);
// Error message: TypeError: body.setHeading is not a function
setHeading() belongs to the Paragraph object (furniture), not the Body object (room)! Always extract paragraphs first using body.getParagraphs() or body.appendParagraph() before invoking setHeading().
Trap 3: Passing Strings like "HEADING2" Instead of Enums
// ✕ Error (passed as a string)
p.setHeading("HEADING2");
Passing a raw string like "HEADING2" inside quotes will cause a type mismatch error. Always supply the exact enum reference: DocumentApp.Heading.HEADING2.
Trap 4: Font Size Doesn’t Change After Running setHeading()?
If a paragraph previously had manual font sizing applied (e.g., 20 pt set directly to specific characters), direct inline styles take precedence over heading style presets.
If that happens, clear individual text styling or use setFontSize(null) to allow the default heading styles to show through properly.
Trap 5: Outline and Table of Contents Integration Rules
In Google Docs, headings formatted via setHeading() (HEADING1 through 6) are automatically synced with the Document Outline and Table of Contents.
Simply making Normal text larger or bolder will not register it in the document outline. Using setHeading() is best practice for maintaining navigable, accessible documents!
6. Summary & What’s Next
Today, we covered how to master document structuring in Google Docs using Paragraph.setHeading()!
Key Takeaways
Paragraph.setHeading()applies heading styles to paragraph elements.- Pass enum constants like
DocumentApp.Heading.HEADING2as the argument. - Call the method on
Paragraphobjects, not onBody. - Heading styles automatically sync with Google Docs outlines and tables of contents.
You can now turn unstructured text into clean, organized invoices and reports with just a few lines of script!
Once your headings are set, the next thing you’ll want to do is make key information pop—like enlarging total invoice amounts and highlighting them in accent colors!
In our next lesson (Episode 55), we will explore text styling with Paragraph.setFontSize() and setForegroundColor()!
Get ready to make your invoice totals stand out with bold sizes and custom colors. See you next time!
