[GAS Beginner Series #55] Make Invoice Amounts Stand Out: How to Style Google Docs with Paragraph.setFontSize() and setForegroundColor()

In our previous lesson (Lesson 54), we learned how to use Paragraph.setHeading() to turn specific text (like “Billing Statement”) into headings, establishing a clean document structure.

When building business documents like invoices and estimates, the next step after setting up the structure is visual emphasis: styling and highlighting your most crucial data!

On an invoice, the single piece of information clients and accounting teams scrutinize the most is the “Total Amount Due.” If this remains in standard black text at default body size, it easily gets lost among other details—which can lead to missed payments or billing oversights.

That brings us to Lesson 55! Today, we’ll dive deep into Paragraph.setFontSize() to freely adjust font sizes, and Paragraph.setForegroundColor() to customize text colors in Google Docs using Google Apps Script (GAS)!

Using our automated invoice generator for the Sapporo office as a project, let’s master practical techniques to make the total amount bold, large, and vividly highlighted!

1. What Are setFontSize() and setForegroundColor()?

These two methods are fundamental tools in Google Apps Script for programmatically applying rich-text styling to Google Docs content.

Let’s first review their roles and basic syntax.

① setFontSize(fontSize) (Changing Font Size)

Changes the font size of a specified Paragraph or Text element in points (pt).

// Set the paragraph font size to 20pt (extra large)
paragraph.setFontSize(20);
  • Argument: An integer. For example: 12, 18, 24, etc. (Note: Passing a string like "20" will cause an error, so make sure to pass a numeric value).

② setForegroundColor(color) (Changing Text / Foreground Color)

Changes the text color (foreground color) of a specified Paragraph or Text element.

// Change the paragraph text color to a vibrant red (color code: #C00000)
paragraph.setForegroundColor("#C00000");
  • Argument: A color string (a CSS-style hex code like "#RRGGBB" or standard color names like "red").
  • 💡 What is Foreground Color?: It’s the counterpart to Background Color and simply refers to the color of the text characters themselves.

Understanding the Hierarchy: House, Room, Furniture, and Paint

Let’s apply our familiar architectural analogy to Google Docs!

Concept Google Docs Element GAS Class / Object Real-World Analogy
Entire File Entire Document File DocumentApp.openById() A Detached House
Body Main Body Area Document.getBody() A Room
Paragraph Paragraph (Block) Body.appendParagraph() / Paragraph Furniture (Sofa, Shelf)
Styling Font Size & Text Color setFontSize() / setForegroundColor() Painting & Cushion Styling

After placing your furniture (a paragraph), painting it a vibrant red and swapping it out for an extra-large model is exactly what we’re accomplishing today!

2. Two Approaches: Entire Paragraph or Specific Characters?

When manipulating text styles in Google Docs via GAS, there are broadly two approaches. Knowing how to choose between them takes your coding skills to a professional level!

[Pattern A: Style the entire paragraph at once]
 paragraph.setFontSize(20).setForegroundColor("#C00000");
 ➡ Every character in "Total Amount Due: $1,540.00 (tax incl.)" becomes 20pt & red

[Pattern B: Pinpoint styling for specific characters inside a paragraph]
 paragraph.editAsText().setFontSize(18, 26, 24).setForegroundColor(18, 26, "#C00000");
 ➡ "Total Amount Due:" stays standard black, while only "$1,540.00" becomes 24pt & red
  • Pattern A (Our main focus today): Call methods directly on the entire Paragraph object. The code is concise and straightforward for beginners.
  • Pattern B (Advanced technique below): Use paragraph.editAsText() with character start and end offsets to style targeted segments.

In this guide, we’ll first master the essentials with Pattern A, followed by the pinpoint styling technique in Pattern B as an advanced exercise!

3. STEP 1: Preparation! Open the “Sapporo Office Invoice Document”

First, let’s prepare the Google Doc we want to automate. If you’ve been following along from Lessons 51 to 54, you can reuse the document you previously created.

Steps

  1. Create a new Google Doc (or open your existing file)
    • Set the document title to “Sapporo Office Invoice Template”.
  2. Copy your Document ID from the URL
    • Check the URL in your browser’s address bar.
    • https://docs.google.com/document/d/[YOUR_DOCUMENT_ID_HERE]/edit
    • Keep this ID handy for your code.

4. STEP 2: [Hands-On] Enlarge and Highlight the Invoice Total in Red!

Now let’s jump into the GAS editor and write some code!

We’ll append a paragraph reading “Total Amount Due: $1,540.00 (tax incl.)” to the bottom of the invoice, enlarge its size to 20pt, apply a rich corporate red (#C00000), and add bold styling with setBold(true).

1. Enter the Code

Open the script editor (from a linked Google Sheet or as a standalone script) and paste the following snippet.

(Be sure to replace YOUR_DOCUMENT_ID with your actual document ID.)

function formatInvoiceTotalAmount() {
  // 1. Open the file using the Document ID (Review from Lesson 51)
  var docId = "YOUR_DOCUMENT_ID"; // Enter your own document ID
  var doc = DocumentApp.openById(docId);
  var body = doc.getBody();
  
  // 2. Append the total amount paragraph to the document body (Review from Lesson 53)
  var totalParagraph = body.appendParagraph("Total Amount Due: $1,540.00 (tax incl.)");
  
  // 3. Enlarge font size to 20pt
  totalParagraph.setFontSize(20);
  
  // 4. Change font color to corporate red (#C00000)
  totalParagraph.setForegroundColor("#C00000");
  
  // 5. Add bold formatting for extra emphasis!
  totalParagraph.setBold(true);
  
  // 6. Log completion message
  Logger.log("Total invoice amount styling complete: enlarged, colored, and bolded!");
}

2. Code Breakdown

Let’s review the key operations step by step:

  • body.appendParagraph("...")
    • Appends a new paragraph to the end of the document body and stores the resulting Paragraph object in the totalParagraph variable.
  • totalParagraph.setFontSize(20)
    • Updates the font size across the entire paragraph from the default (typically 11pt) up to 20pt.
  • totalParagraph.setForegroundColor("#C00000")
    • Sets the font color for the entire paragraph to #C00000 (deep corporate red).
  • totalParagraph.setBold(true)
    • Applies bold formatting. Combining increased size, vivid color, and bold weight delivers outstanding visibility!

3. Verify the Results

Save your script, click “Run”, and check your Google Doc.

If you see “Total Amount Due: $1,540.00 (tax incl.)” displayed clearly in large, bold red letters at the bottom of the document, it’s a complete success!

With this styling, anyone reviewing the invoice can instantly locate the required payment amount without searching!

5. STEP 3: [Advanced] Make Only the Numerical Amount Extra-Large and Red!

“Styling the whole line red is nice, but what if I want the label ‘Total Amount Due:’ to stay normal black text at 12pt, and only the number ‘$1,540.00’ to be extra-large (24pt) and red?“

In professional document design, this kind of balanced visual hierarchy is very common.

To accomplish this, we combine Paragraph.editAsText() with character offset ranges!

Understanding Character Offsets

Starting from index 0 for the first character, we count which characters to style by index number.

Characters: T o t a l   A m o u n t   D u e :   $  1  5  4  ,  0  0  0  .  0  0     ( t a x   i n c l . )
Index:      0 1 2 3 4 5 6 7 8 9 ...          18 19 20 21 22 23 24 25 26 27 28
                                              └─── Range: Indices 18 to 26 ───┘

In the string Total Amount Due: $1,540.00 (tax incl.), the currency amount $1,540.00 starts at index 18 and ends at index 26.

1. Add the Advanced Code

Add the following function to your editor and run it:

function formatPartialAmountText() {
  var docId = "YOUR_DOCUMENT_ID"; // Enter your own document ID
  var doc = DocumentApp.openById(docId);
  var body = doc.getBody();
  
  // Append a new paragraph
  var p = body.appendParagraph("Total Amount Due: $1,540.00 (tax incl.)");
  
  // 1. Initialize the whole paragraph to 12pt, black, normal weight
  p.setFontSize(12);
  p.setForegroundColor("#000000");
  p.setBold(false);
  
  // 2. Put the paragraph into text editing mode using editAsText()
  var textObj = p.editAsText();
  
  // 3. Target only the amount "$1,540.00" (indices 18 to 26)
  var startOffset = 18; // Index of "$"
  var endOffset = 26;   // Index of the final "0"
  
  // Set the specific range to 24pt
  textObj.setFontSize(startOffset, endOffset, 24);
  
  // Set the specific range color to red (#C00000)
  textObj.setForegroundColor(startOffset, endOffset, "#C00000");
  
  // Make the specific range bold
  textObj.setBold(startOffset, endOffset, true);
  
  Logger.log("Targeted styling on the amount segment completed!");
}

Execution Results

When you execute this script:

  • “Total Amount Due: ” ➡ 12pt, standard black
  • “$1,540.00” ➡ 24pt, red, bold
  • ” (tax incl.)” ➡ 12pt, standard black

You instantly get a polished, professionally formatted total amount callout generated entirely with code!

6. Quick Reference: Useful Hex Color Codes for Business Documents

Here is a handy reference of common hexadecimal color codes you can pass to setForegroundColor(). Pick colors that match your company’s branding and document style:

Color Impression Hex Code Recommended Use Cases
Vivid Alert Red "#FF0000" Critical alerts, overdue notices
Deep Corporate Red "#C00000" Highlighting invoice totals (Highly recommended!)
Dark Navy Blue "#002060" Authoritative headings, title banners
Forest Green "#008000" Approval statuses, success messages
Subtle Charcoal Gray "#595959" Supporting notes, footnotes like “(tax incl.)”

7. 4 Common Pitfalls for Beginners and How to Solve Them

Here are four frequent gotchas developers encounter when working with setFontSize() and setForegroundColor(), along with their solutions.

Pitfall 1: Forgetting the # in Hex Color Codes

// ✕ Incorrect (missing the pound/hash symbol)
paragraph.setForegroundColor("C00000");

// ◯ Correct (properly formatted with #)
paragraph.setForegroundColor("#C00000");

[Symptom] You receive an Invalid argument exception or the color is ignored.

[Fix] Always prefix hexadecimal color values with a half-width # and enclose the string in double quotes "".

Pitfall 2: Passing a String Instead of a Number to setFontSize()

// ✕ Incorrect (passed as a string)
paragraph.setFontSize("20");

// ◯ Correct (passed as an integer value)
paragraph.setFontSize(20);

[Symptom] A type mismatch or argument error occurs.

[Fix] When setting font size, always provide a numeric literal like 20 rather than a string "20".

Pitfall 3: Offset Miscalculations Affecting the Wrong Characters

When providing range parameters to textObj.setFontSize(start, end, size), remember that indices are zero-indexed (0-based).

  • Character 1 = Index 0
  • Character 7 = Index 6

A reliable pro-tip to avoid counting errors is to locate targets dynamically using JavaScript search methods, such as textObj.getText().indexOf("$"). That way, your code adjusts automatically even if surrounding text changes!

Pitfall 4: Script Runs Successfully, but the Open Doc Doesn’t Update Immediately

Occasionally, when running style updates from GAS while viewing the document in another tab, changes don’t appear on screen right away.

This is typically due to browser view caching. Refreshing the tab (F5 or Ctrl + R / Cmd + R) will display updates. You can also append doc.saveAndClose(); at the end of your script to explicitly force and commit all pending modifications.

8. Summary & What’s Next

In this lesson, we explored how to make Google Docs content visually impactful using Paragraph.setFontSize() and Paragraph.setForegroundColor().

Key Takeaways

  • Use setFontSize(20) with numeric values (pt) to scale text size.
  • Use setForegroundColor("#C00000") with hex strings to apply vibrant custom colors.
  • Choose between styling whole paragraphs at once or applying pinpoint edits via editAsText().
  • Avoid syntax pitfalls by including the # symbol on hex colors and passing numbers for font sizes.

Now that your invoice totals are generated automatically in prominent, bold red lettering, our Sapporo office automated invoice generation system is looking truly professional!

In our next tutorial (Lesson 56), we’ll tackle an essential component of any invoice: neatly arranging line items using Body.appendTable()!

We’ll walk through generating clean, structured data tables from scratch, so stay tuned!