Throughout this series, we have explored how to manipulate Google Sheets, integrate with Gmail, and manage files in Google Drive.
Starting with this lesson, we are finally diving into Phase 6: Google Docs Automation!
Google Docs is an indispensable tool in our daily workflow for drafting reports, contracts, invoices, specifications, and manuals.
By leveraging Google Apps Script (GAS), you can achieve complete document automation—such as opening a Google Docs template, replacing text dynamically, converting the result to a PDF, and emailing it directly to clients.
As the foundational first step in Episode 51, we will explore the essential method to open a specific document via code: DocumentApp.openById()!
Furthermore, we will break down the structural hierarchy of Google Docs (the relationship between Document, Body, Paragraph, and more)—a concept you must understand to manipulate documents effortlessly—using an intuitive “House, Rooms, and Furniture” analogy.
Let’s dive into practical coding using our “Sapporo Office Invoice Template” sample!
1. What Is DocumentApp.openById() in Google Apps Script?
When working with spreadsheets in earlier articles, we relied heavily on SpreadsheetApp.
When automating Google Docs, the top-level service class switches to DocumentApp.
The dedicated method used to open a specific Google Doc using its unique identifier is DocumentApp.openById().
DocumentApp.openById("ENTER_DOCUMENT_ID_HERE");
Breaking Down the Syntax
DocumentApp
The root service class that manages Google Docs capabilities in Google Apps Script. It signals to GAS: “We are about to perform operations on Google Docs!”.openById(id)
A core method onDocumentApp. By passing the document’s string ID into the parameter, it locates that specific Google Doc file and loads it into your script runtime.
Differences Between getActiveDocument() and openById()
Think back to our work with spreadsheets.
In Google Sheets, we had SpreadsheetApp.getActiveSpreadsheet() to fetch whichever file was currently active on screen.
Google Docs provides a similar method: DocumentApp.getActiveDocument().
However, in practical business automation, openById() is used far more frequently.
| Method | Characteristics | Primary Use Case |
getActiveDocument() |
Used within container-bound scripts (created via Extensions > Apps Script inside a Doc) to access the currently open document itself. | Triggering actions from custom menus or sidebars directly inside that Google Doc. |
openById(id) |
Opens a specific Google Doc externally by supplying its unique ID string. | Generating invoices automatically in Docs from customer records stored in a Google Sheet. |
The most common business scenario involves generating Docs invoices or contracts based on records in Google Sheets. Because the script originates in Sheets (or a standalone script), openById() is absolutely essential!
How to Find Your Document ID
You can locate any Google Doc ID directly in your web browser’s address bar (URL).
When you open a Google Doc, the URL structure looks like this:
https://docs.google.com/document/d/1A2B3C4D5E6F7G8H9I0J_ExampleID_1234567/edit
The long alphanumeric string sandwiched between /d/ and /edit (in the example above, 1A2B3C4D5E6F7G8H9I0J_ExampleID_1234567) is the unique Document ID.
Copy this ID and pass it into openById("YOUR_ID") so GAS can accurately access that exact document.
2. Understanding the Google Docs Object Hierarchy: Document, Body, and Paragraph
Before writing more code, let’s understand how Google Docs is structured internally. Master this hierarchy now, and you will save yourself countless hours debugging document manipulation errors later!
Let’s compare it to Google Sheets using our familiar “House, Room, Furniture” analogy.
Comparing Hierarchies: Google Sheets vs. Google Docs
| Concept | Google Sheets (SpreadsheetApp) | Google Docs (DocumentApp) ★ Today | Real-World Analogy |
| Service | SpreadsheetApp |
DocumentApp |
Real estate agency |
| File | Spreadsheet (entire spreadsheet) |
Document (entire document) |
House (entire building) |
| Area / Room | Sheet (individual tab) |
Body (main content area)(Also Header / Footer, etc.) |
Rooms (living room, etc.) |
| Elements | Range (cells/grid) |
Paragraph (paragraphs)Table (tables)Image (inline images) |
Furniture (drawers, shelves) |
| Raw Data | .getValue() / .setValue() |
Text (text strings) |
Notes or books inside furniture |
[Google Docs Structural Hierarchy]
Document (Entire document file = The House)
│
├── Body (Main text area = Primary Room) ★ Main area for text and tables
│ ├── Paragraph (Paragraph 1 = Furniture) ── Text ("Sapporo Office Invoice")
│ ├── Paragraph (Paragraph 2 = Furniture) ── Text ("Total Amount: $1,000")
│ ├── Table (Itemized Table = Furniture)
│ └── InlineImage (Company Stamp = Furniture)
│
├── Header (Header section = Attic room)
└── Footer (Footer section = Basement room)
Why Is Understanding Body and Paragraph So Critical?
A common beginner pitfall is assuming: “I opened the Document, so I can immediately edit the text directly on it!”
For instance, trying to execute doc.replaceText() or doc.getText() right after opening the document will fail with an error or not behave as expected.
This happens because Google Docs separates its content into distinct structural zones: the main Body, the Header, and the Footer.
Document: Represents the document file wrapper (renaming, saving, permissions, file-level metadata).Body: The central editable area where paragraphs, lists, and tables reside.Paragraph: An individual paragraph element (a block of text delimited by line breaks) inside the Body.
In short, you must navigate downward in sequence: Open File (Document) ➡ Enter Main Area (Body) ➡ Access Elements (Paragraph / Text)!
3. STEP 1: Preparation! Create the Sapporo Office Invoice Template
Let’s create a sample Google Doc that we can manipulate using Google Apps Script.
For this exercise, we will set up a mock invoice template used at our Sapporo Office.
Step-by-Step Instructions
- Open Google Drive
Navigate to Google Drive in your browser, click “New” > “Google Docs” to create a blank document. - Rename the File
Click “Untitled document” in the upper-left corner and name itSapporo Office Invoice Template. - Add Sample Body Text
In the document body, enter sample lines such as the following:
Invoice
To: Sapporo Soup Curry Honpo Co., Ltd.
Thank you for your continued partnership.
Sapporo Office hereby submits the system maintenance fee invoice for this month. - Copy the Document ID
From the URL in your browser’s address bar, copy the Document ID string located between/d/and/edit.
Example: https://docs.google.com/document/d/ [1abc123456XYZ_thisIsMyDocumentID] /edit
↑ Copy this section!
4. STEP 2: [Hands-On] Open and Inspect the Document Structure with GAS
Now that our template document is ready, let’s write our Apps Script code!
You can use either a container-bound script or a standalone script for this tutorial.
Open the script editor via “Extensions” > “Apps Script” from any familiar Google Sheet, or create a new script from Google Drive via “New” > “More” > “Google Apps Script”.
1. Enter the Code
Clear any placeholder code in the editor and paste the following snippet.
Replace YOUR_DOCUMENT_ID_HERE with the Document ID you copied earlier (be sure to keep the double quotes ""!).
function openAndAnalyzeDoc() {
// 1. Specify your copied Document ID
var docId = "YOUR_DOCUMENT_ID_HERE";
// 2. Open the document file (House) using DocumentApp.openById()
var doc = DocumentApp.openById(docId);
// 3. Retrieve and log the document title (file name)
var docName = doc.getName();
Logger.log("File Name: " + docName);
// 4. Retrieve the main content area (Body) of the document
var body = doc.getBody();
// 5. Retrieve all paragraphs within the Body as an array
var paragraphs = body.getParagraphs();
Logger.log("Total Paragraphs: " + paragraphs.length);
// 6. Iterate through each paragraph and log its text content
for (var i = 0; i < paragraphs.length; i++) {
var text = paragraphs[i].getText();
// Log only non-empty paragraphs
if (text !== "") {
Logger.log(" - Paragraph " + (i + 1) + ": " + text);
}
}
}
2. Line-by-Line Code Explanation
var doc = DocumentApp.openById(docId);
The star of today’s lesson. This opens the document matching the specified ID and assigns the returnedDocumentobject to the variabledoc.var docName = doc.getName();
Calls the.getName()method on theDocumentobject to retrieve its file name (“Sapporo Office Invoice Template”).var body = doc.getBody();
Extracts theBodyobject (main content section) fromDocument. When inserting, deleting, or replacing text and tables, you call methods on thisbodyobject.var paragraphs = body.getParagraphs();
Collects every paragraph (Paragraphobject) contained inside theBodyinto a JavaScript array (list).paragraphs[i].getText()
Calls.getText()on an individual paragraph element to extract the actual string characters stored within it.
3. Handling the Initial Authorization Prompt
Once your code is pasted, click the Save (disk icon) button, then click Run.
Just like when connecting to Google Sheets or Gmail for the first time, Google’s authorization flow will display a permission modal.
- Click Review permissions.
- Select your Google account.
- If you see “Google hasn’t verified this app”, click Advanced in the bottom-left corner.
- Click Go to … (unsafe).
- Click Allow on the final screen.
*This is Google’s standard security verification for custom scripts, as detailed in Episode 2. You can proceed with confidence!
4. Reviewing the Execution Log
Once authorized, your function runs. Open the Execution Log panel at the bottom of the editor to inspect the results!
Info File Name: Sapporo Office Invoice Template
Info Total Paragraphs: 5
Info - Paragraph 1: Invoice
Info - Paragraph 2: To: Sapporo Soup Curry Honpo Co., Ltd.
Info - Paragraph 3: Thank you for your continued partnership.
Info - Paragraph 4: Sapporo Office hereby submits the system maintenance fee invoice for this month.
GAS successfully opened your designated Google Doc and parsed the file name and paragraph contents cleanly!
5. 5 Common Beginner Traps and How to Fix Them
When starting out with DocumentApp.openById() and Docs automation, here are five frequent snags developers encounter—and how to easily resolve them.
Trap 1: Passing the Entire URL into openById()
// INCORRECT: Passing the complete URL string
var doc = DocumentApp.openById("https://docs.google.com/document/d/1abc12345/edit");
// CORRECT: Passing only the extracted ID string
var doc = DocumentApp.openById("1abc12345");
openById() expects only the ID string found between /d/ and /edit. Supplying the full URL triggers an error: “Document is missing or the ID is invalid”.
Trap 2: Calling doc.getText() or doc.replaceText() Directly on Document
// INCORRECT: Attempting text methods directly on the Document instance
var text = doc.getText(); // TypeError: doc.getText is not a function
// CORRECT: Access the Body object first, then call text methods
var body = doc.getBody();
var text = body.getText();
As explained in our hierarchy chart, text manipulation methods such as getText() and replaceText() are methods on the Body class, not the Document class.
Always obtain the body via doc.getBody() before manipulating content.
Trap 3: Calling .getText() Directly on the getParagraphs() Array
// INCORRECT: Calling getText() directly on the array of paragraphs
var paragraphs = body.getParagraphs();
var text = paragraphs.getText(); // TypeError: paragraphs.getText is not a function
// CORRECT: Access an index like [0] or loop through elements
var firstParagraphText = paragraphs[0].getText();
Notice the plural form in getParagraphs(): it returns an array of objects. Because it is a collection, you cannot call .getText() on the array container itself. Access elements using an index like paragraphs[0] or iterate through them in a loop.
Trap 4: Case Sensitivity Typos (DocumentApp and openById)
- Incorrect:
documentApp.openById()(lowercase “d”) - Incorrect:
DocumentApp.openByID()(capitalized “ID”) - Correct:
DocumentApp.openById()(capitalized “A” in App, “B” in By, “I” in Id)
GAS is strictly case-sensitive. To eliminate typos, type DocumentApp. and use the auto-complete popup by pressing Tab or Enter to select the intended method.
Trap 5: Lacking Permissions to the Target Document ID
If you reference a Document ID that your currently executing Google account does not have permission to view or edit, GAS throws an error: Exception: You do not have permission to access the requested document.
Ensure that the file exists in your Google Drive or that edit/view sharing access has been granted to your account.
6. Summary and What’s Coming Next
In this lesson, we kicked off Google Docs automation by mastering DocumentApp.openById() and the Google Docs element hierarchy.
Key Takeaways
DocumentApp.openById("ID")opens an external Google Doc using its unique identifier.- The Document ID is the long alphanumeric string located between
/d/and/editin the document URL. - Google Docs follows a clear hierarchy:
Document(House) ➡Body(Room) ➡Paragraph(Furniture / Text block). - To read or modify document text, you must access the content layer via
doc.getBody().
What’s Next?
Now that you know how to open documents and navigate the Body hierarchy, we are ready for a high-impact automation technique: dynamically replacing template placeholders!
In Episode 52, we will cover Body.replaceText(): Batch Replacing Placeholders like “{Company Name}” and “{Invoice Date}”.
We will replace placeholder tokens in our “Sapporo Office Invoice Template” with actual customer names and billing amounts in seconds using GAS. Stay tuned!
