In our previous tutorial (Lesson #57), we learned how to dynamically inject work logs into table cells (TableCell) and style header row backgrounds in Google Docs invoice templates. Now that dynamic table entry is mastered, our automated documents look much more authentic and professional!
However, when finishing business documents such as invoices, quotes, or contracts, there is one final, indispensable step: affixing the official company seal (stamp) or personal approval seal!
Have you ever felt frustrated because, despite automating all the text and table generation, you still had to open each Google Doc by hand just to drag, drop, and resize the company seal image?
In this 58th lesson, we will thoroughly explore Body.appendImage(), an essential Google Apps Script (GAS) method that allows you to automatically insert images into the body of a Google Doc with pure code!
Using the Sapporo Office invoice automation project as our practical example, we will cover everything from retrieving image data and calculating proportional resizing to real-world techniques for placing the seal right inside a table cell. Let’s dive in!
1. What Exactly Is Body.appendImage()?
Body.appendImage() is a Google Apps Script method used to automatically append specified image data (as a Blob) to the very end of a Google Doc’s main body area (Body).
Reviewing Document Structure: The House, Room, and Furniture Analogy
Let’s review the internal structure of Google Docs using our familiar “House, Room, and Furniture” analogy from this series.
- 【House / Building】 = Document (The entire document)
- The entire file opened via
DocumentApp.openById(), which we covered in Lesson #51.
- The entire file opened via
- 【Room】 = Body (The main document body)
- The primary workspace holding text and tables, retrieved via
doc.getBody()as learned in Lessons #52 and #53.
- The primary workspace holding text and tables, retrieved via
- 【Furniture / Decor】 = Paragraph, Table, InlineImage (Image) ★ Today’s star!
- The concrete elements placed inside the room.
Calling Body.appendImage() corresponds directly to hanging a new painting or photograph (an InlineImage) at the far end of the room (at the very bottom of the document body).
Basic Code Syntax
// 1. Get the document body (the room) var body = doc.getBody(); // 2. Insert image data (Blob) at the end of the body var image = body.appendImage(imageBlob);
The returned value stored in image is an InlineImage object in GAS. By working with this InlineImage object, you can freely modify the width and height of your inserted image later in your script!
2. What Is a “Blob”? How GAS Handles Image Data
When working with appendImage(), the first hurdle beginners often run into is the concept of a “Blob” passed into the argument.
Think of a “Blob” as an Envelope Holding Your Letter!
Passing a local file path or file name string directly, such as body.appendImage("C:\mypicture.png"), will not work in GAS.
To handle images in Google Apps Script, you must convert the image file into a Blob (Binary Large Object)—a raw data format (like an envelope containing binary data) that the script engine can read and process.
In business scenarios, there are two common pathways to retrieve image data:
【Pattern A: Retrieve from Google Drive】 DriveApp.getFileById("FILE_ID") ──> .getBlob() ──> Pass to appendImage() 【Pattern B: Retrieve from a Web URL】 UrlFetchApp.fetch("IMAGE_WEB_URL") ──> .getBlob() ──> Pass to appendImage()
In this guide, we will focus on Pattern A, which is the most reliable and widely used method in corporate workflows: fetching a company seal image stored in Google Drive and inserting it into your document!
3. STEP 1: Preparation! Set Up the “Sapporo Office Invoice” and “Company Seal Image”
First, let’s prepare the practice files we need before writing our script.
Step 1: Upload the Company Seal Image to Google Drive
- Prepare a sample image on your computer (a transparent PNG seal stamp image, company logo, etc.).
- Open Google Drive and upload the image file via drag-and-drop.
- Double-click the uploaded file to preview it, click the three vertical dots (⋮) in the upper right, and choose “Open in new window”.
- Examine the URL in the address bar and copy the alphanumeric ID string located between
d/and/view(shown in bold below). This is your Image File ID.
https://drive.google.com/file/d/1a2b3c4d5e6f7g8h9i0j-XXXXX/view
Step 2: Create a Practice Google Doc
- In Google Drive, click “New” > “Google Docs”.
- Rename the document to “Sapporo Office Invoice_Test”.
- Add sample text in the body, such as “Invoice” or “To: Sapporo Soup Curry Honpo Co., Ltd.”.
- Just like with Google Sheets, copy the Document ID from the URL in your address bar (the string between
d/and/edit).
4. STEP 2: [Hands-on] Insert the Company Seal Image into the Document!
With our preparation complete, let’s open the Apps Script editor and write some code!
1. Enter the Code
Open the Apps Script editor from any Google Sheet or as a standalone project, clear any default template code, and paste the snippet below (make sure to replace the placeholder IDs with your own):
function addCompanySeal() { // 1. Specify Document ID and Image File ID var docId = "YOUR_DOCUMENT_ID_HERE"; // Enter your Document ID var imageFileId = "YOUR_IMAGE_FILE_ID_HERE"; // Enter your Image File ID // 2. Retrieve Document (house) and Body (room) (See Lesson #51) var doc = DocumentApp.openById(docId); var body = doc.getBody(); // 3. Retrieve the image file from Google Drive and convert to a Blob (raw data) var imageFile = DriveApp.getFileById(imageFileId); var imageBlob = imageFile.getBlob(); // 4. Automatically insert the image at the end of the body! var inlineImage = body.appendImage(imageBlob); // 5. Output the execution result to the log (See Lesson #1) Logger.log("Company seal image inserted successfully!"); }
2. Authorize Permissions on First Run
Save your script and click the “Run” button.
On your first run, an authorization dialog will appear requesting access to DocumentApp and DriveApp (Drive file operations).
Follow the same verification steps covered in Lesson #2: click “Review permissions” > choose your Google account > “Advanced” > “Go to Untitled project (unsafe)” > “Allow”.
3. Check the Result
Switch over to your Google Doc to verify the outcome!
If your chosen company seal image has automatically appeared at the very end of the document body, your script executed with flying colors!
5. STEP 3: Essential! Resize Images with setWidth() and setHeight()
While our image was successfully placed, you might look at your document and think: “Wait, why is this image gigantic and overflowing onto the next page?” or “Our neat seal stamp is now dominating the entire page!”
By default, images inserted via appendImage() are rendered at their original pixel resolution without any downscaling.
For an invoice seal stamp, a compact footprint of roughly 60 to 80 pixels is standard and visually balanced. Let’s master the resizing methods needed to achieve the perfect fit!
Methods to Adjust Image Width and Height
The InlineImage object returned by appendImage() includes built-in methods for adjusting dimensions:
// Set width to 80 pixels inlineImage.setWidth(80); // Set height to 80 pixels inlineImage.setHeight(80);
Pro Formula: Proportional Resizing Without Distorting the Aspect Ratio!
If your seal image is a perfect square, calling setWidth(80); setHeight(80); is completely fine. However, for rectangular assets like corporate logos, entering arbitrary dimensions will stretch or squash the graphic unnaturally.
Here is the professional formula to automatically calculate height based on target width while preserving the original aspect ratio:
function addResizedCompanySeal() { var doc = DocumentApp.openById("YOUR_DOCUMENT_ID_HERE"); var body = doc.getBody(); var imageFile = DriveApp.getFileById("YOUR_IMAGE_FILE_ID_HERE"); var imageBlob = imageFile.getBlob(); // 1. Insert the image var image = body.appendImage(imageBlob); // 2. Get the original image dimensions (width and height) var originalWidth = image.getWidth(); var originalHeight = image.getHeight(); // 3. Define the desired target width in pixels (e.g., 80px) var targetWidth = 80; // 4. Calculate the scaling ratio var ratio = targetWidth / originalWidth; // 5. Calculate the proportional height based on the ratio var targetHeight = originalHeight * ratio; // 6. Apply the calculated proportional dimensions! image.setWidth(targetWidth); image.setHeight(targetHeight); Logger.log("Image resized while preserving aspect ratio! (Width: " + targetWidth + "px, Height: " + targetHeight + "px)"); }
With this scaling logic in place, any image—regardless of its dimensions—will scale down cleanly without any distortion!
6. STEP 4: Advanced Practical Tip! Place the Seal Inside an Issuer Table Cell
In actual business invoices, you rarely want the seal stamp sitting at the very end of the document body. Instead, you need it positioned neatly beside or over the issuer information block (Sapporo Office details) in the top-right or bottom-right quadrant.
By inserting the image directly into a specific cell (TableCell) of a table—techniques we mastered in Lessons #56 and #57—your seal will remain locked into an immaculate layout!
function addSealToTable() { var doc = DocumentApp.openById("YOUR_DOCUMENT_ID_HERE"); var body = doc.getBody(); // Retrieve the first table in the document var table = body.getTables()[0]; // Retrieve row 1, column 2 (the right-hand cell) of the table (See Lesson #57) // * Assuming the right-hand cell contains "Issuer: Sapporo Soup Curry Honpo Co., Ltd..." var cell = table.getCell(0, 1); // Retrieve the company seal image var imageBlob = DriveApp.getFileById("YOUR_IMAGE_FILE_ID_HERE").getBlob(); // [Key Point] Call appendImage() on the TableCell instead of Body! var sealImage = cell.appendImage(imageBlob); // Resize to standard seal dimensions (70px) sealImage.setWidth(70); sealImage.setHeight(70); Logger.log("Company seal stamped into the invoice issuer cell successfully!"); }
As demonstrated, by taking advantage of cell.appendImage() or paragraph.appendImage() in addition to body.appendImage(), you can programmatically place images at exact target coordinates inside your document!
7. Five Common Traps Beginners Face and How to Solve Them
Here are five common pitfalls and errors developers encounter when working with Body.appendImage(), along with proven troubleshooting techniques to resolve them quickly:
Trap 1: Forgetting .getBlob() and Triggering Exception: Invalid argument
// INCORRECT: Passing the File object directly causes an error var file = DriveApp.getFileById(id); body.appendImage(file); // CORRECT: Always convert to a Blob first var blob = DriveApp.getFileById(id).getBlob(); body.appendImage(blob);
appendImage() cannot process a raw file container (File object); it only accepts binary image data (Blob). Make it a firm habit to append .getBlob() whenever grabbing files from Drive!
Trap 2: The Image Is Huge and Spills Onto Page 2
If running your script unexpectedly adds an extra page to your document, the unscaled image has exceeded the page boundaries.
Always make it standard practice to execute image.setWidth() and image.setHeight() immediately after inserting any graphic.
Trap 3: Typos Such as Cannot find method getTables
Method names in Google Apps Script are strictly case-sensitive.
- ✕
body.appendimage()(lowercase i) - ✕
body.AppendImage()(uppercase A) - ◯
body.appendImage()(capital I only)
To prevent manual typos, make frequent use of the code autocomplete feature by pressing Ctrl + Space (or Option + Esc on macOS).
Trap 4: Image Cannot Be Placed Behind Text or Floated Freely
Under Google Docs specifications, graphics inserted via appendImage() are treated as in-line images (InlineImage).
Because GAS has limited native support for floating styles (such as “Behind text” or “Wrap text”), the enterprise best practice is to use borderless table cells to structure your document layout cleanly.
Trap 5: Exception: Attribute provided… When Fetching From a Web URL
When fetching an image via UrlFetchApp.fetch(url).getBlob(), passing an HTML webpage URL rather than a direct image link will trigger an error.
Always confirm that your URL is a direct link ending in a valid image extension such as .png or .jpg.
8. Summary and What’s Next
In this lesson, we explored how to automatically insert images into Google Docs using Body.appendImage(), along with essential techniques for proportional resizing and precise cell placement!
Key Takeaways
body.appendImage(blob)appends anInlineImageto the very end of the document body.- When using Drive images, always convert them to a Blob using
DriveApp.getFileById().getBlob(). - Default images insert at native resolution; always resize them with
setWidth()andsetHeight()(around 60–80px for seals). - Calculate ratios with
targetWidth / originalWidthto resize smoothly without distorting aspect ratios. - Call
TableCell.appendImage()to place seal images accurately inside invoice tables.
With text replacement (Lesson #52), dynamic table generation (Lessons #56 & #57), and automated seal stamping (Lesson #58), our automated invoice pipeline is looking complete!
In Lesson #59, we will dive into Document.addHeader() / addFooter() to elevate document quality even further!
We will learn how to automatically append Sapporo Office contact channels and dynamic page numbers into running footers. Stay tuned!
