Converting Files in Google Apps Script – From Lightweight Workarounds to Drive API Libraries

File format conversion in Google Apps Script ranges from simple string manipulations to multi-stage pipeline workflows. Depending on your source format and required output, the optimal solution might be a quick service workaround, a native Drive API call or a dedicated library capable of handling indirect conversions and OCR.

The Lightweight Approach: Converting HTML to Plain Text

At the simplest end of the spectrum, you can convert markup into plain text without writing custom regular expressions or importing heavy third-party parsers.

A clever technique shared by Kanshi Tanaike in his guide on converting HTML to plain text uses the Gmail Service. You pass the HTML string into GmailApp.createDraft() and retrieve the formatted plain text using getPlainBody().

Code Example: HTML Conversion via Temporary Gmail Draft

/**
 * Converts an HTML string to plain text using a temporary Gmail draft.
 */
function convertHtmlToPlainText() {
  const htmlContent = '<div><h1>Quarterly Summary</h1><p>Project completed on <b>Schedule</b>.</p></div>';
  
  // Create a temporary draft to utilise Gmail's HTML parser
  const draft = GmailApp.createDraft('', '', '', { htmlBody: htmlContent });
  const plainText = draft.getMessage().getPlainBody();
  
  // Immediately delete the draft to clean up
  draft.deleteDraft();
  
  Logger.log(plainText);
  // Output:
  // Quarterly Summary
  // Project completed on Schedule.
}

This clever workaround executes quickly and avoids manual string parsing. It is ideal when cleaning up web scraper output, preparing logs or stripping HTML tags from user input but comes with the downside of requiring a Gmail authorisation scope.

Direct Drive API Conversions

The Drive API provides a direct conversion mechanism. For example, by passing an HTML blob to Drive.Files.create(), Google Drive can convert this into a fully formatted Google Doc. You can then open the generated document using DocumentApp to extract clean text or manipulate document elements before trashing the temporary file.

Code Example: Converting HTML to a Doc and Extracting Text

To use this method, enable the Drive API under Services in the Apps Script editor (using Drive API v3).

/**
 * Converts an HTML string into a Google Doc via Drive API,
 * extracts the plain text from the Doc body, and trashes the file.
 */
function convertHtmlToDocAndExtractText() {
  const htmlContent = '<h1>Project Summary</h1><p>The roll-out was successful across all regions.</p>';
  const blob = Utilities.newBlob(htmlContent, MimeType.HTML);
  
  const fileMetadata = {
    name: 'Temporary Converted Doc',
    mimeType: MimeType.GOOGLE_DOCS
  };

  // Create a Google Doc from the HTML blob using Drive API v3
  const file = Drive.Files.create(fileMetadata, blob, { supportsAllDrives: true });
  
  // Open the created Doc and extract text content
  const doc = DocumentApp.openById(file.id);
  const extractedText = doc.getBody().getText();
  
  Logger.log(extractedText);
  // Output:
  // Project Summary
  // The roll-out was successful across all regions.
  
  // Trash the temporary Google Doc to maintain a clean Drive
  DriveApp.getFileById(file.id).setTrashed(true);
}

This pattern provides a reliable way to turn web markup into native document elements or extract structured text while preserving structural hierarchy.

The Heavy-Duty Approach: Multi-Step Conversions and OCR

Direct API calls work well when Google Drive natively supports the source and target MIME type pairing. However, problems arise when there is no direct conversion path – for instance, converting a Microsoft Word file (.docx) directly into a PDF, or converting an image into editable text via Optical Character Recognition (OCR).

To solve this, Bruce McPherson developed a comprehensive Apps Script file conversion library [June, 2023].

How the Library Works

  1. Path Resolution: The library evaluates the source MIME type and the target MIME type.
  2. Direct Conversion: If a direct route exists (e.g. Google Doc to PDF), it executes the transformation immediately.
  3. Indirect Pipeline: If no direct route exists (e.g. Word document to PDF), it automatically determines the intermediate steps. It first converts the Word file to an intermediate Google Doc, then exports that Google Doc as a PDF, before cleaning up temporary files.
  4. OCR Processing: For image formats (.png, .jpg), it passes the file through Drive API’s OCR engine to extract embedded text directly into a Google Doc.

This approach removes the manual work of tracking MIME compatibility matrices and chaining multiple Drive API requests manually.

Summary

Matching your conversion method to the task keeps your Google Apps Script projects lean and reliable. For rich document generation and extraction, Drive API conversions offer structured flexibility.

Securing Local Execution: From the Workspace CLI to Sandboxed Emulation with the `gas-fakes` Agent

gf_agent is an interactive automation agent for Gemini CLI that enables users to access and manupulate workspace resources conversationally.

The automation of Google Workspace is advancing rapidly. We are moving away from static scripts and rigid cloud triggers towards environments where AI agents autonomously orchestrate complex tasks. Recently, I shared a recipe exploring how we could use the Workspace CLI to call the Apps Script Execution API. I was quite pleased with it, however, a recent email exchange with Bruce Mcpherson quickly highlighted a much more efficient path.

Bruce pointed out that his new gf_agent for the Gemini CLI bypasses the need to write these intermediary scripts entirely. By using his gas-fakes emulation environment, the agent accepts plain English requests, generates the required Apps Script logic dynamically, and executes it securely on your local machine. It is a brilliant piece of work. You simply ask the agent to summarise your latest emails or resize images in a document, and it handles the heavy lifting without using the Apps Script runtime.

To illustrate this capability, Bruce shared an excerpt from a recent run demonstrating a complete web to document flow, similar to the Workspace CLI / Apps Script Execution API example. The log captures the moment the system activates the local skill, maps the available resources, and then executes the required logic directly from the terminal:

✦ I will activate the gf_agent skill to access specialized guidance for Google Workspace automation.

╭───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│ ✓  Activate Skill "gf_agent": Specialized agent for automating Google Workspace tasks locally using gas-fakes. Gener… │
│                                                                                                                       │
│ Skill gf_agent activated. Resources loaded from /Users/brucemcpherson/.gemini/skills/gf_agent:                        │
│                                                                                                                       │
│ Showing up to 200 items (files + folders).                                                                            │
│                                                                                                                       │
│ /Users/brucemcpherson/.gemini/skills/gf_agent/                                                                        │
│ ├───documentation.md                                                                                                  │
│ ├───index.md                                                                                                          │
│ ├───README.md                                                                                                         │
│ ├───SKILL.md                                                                                                          │
│ ├───scripts/                                                                                                          │
│ │   └───builder.js                                                                                                    │
│ └───skills/                                                                                                           │
│     ├───base.md                                                                                                       │
│     ├───cache.md                                                                                                      │
│     ├───calendar.md                                                                                                   │
│     ├───charts.md                                                                                                     │
│     ├───document.md                                                                                                   │
│     ├───drive.md                                                                                                      │
│     ├───forms.md                                                                                                      │
│     ├───gmail.md                                                                                                      │
│     ├───jdbc.md                                                                                                       │
│     ├───lock.md                                                                                                       │
│     ├───properties.md                                                                                                 │
│     ├───script.md                                                                                                     │
│     ├───slides.md                                                                                                     │
│     ├───spreadsheet.md                                                                                                │
│     ├───urlfetch.md                                                                                                   │
│     ├───utilities.md                                                                                                  │
│     └───xml.md                                                                                                        │
╰───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯

✦ I will use the workspace_agent to fetch the content from the URL, create a Google Document from the HTML, copy it, and then
  resize the images in the copy using the recommended Docs API workaround, as setWidth/setHeight are not supported in the
  local environment.

╭───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│ ✓  workspace_agent (gas-fakes-mcp MCP Server) {"script":"\nconst url = 'https://ramblings.mcpher.com/resurrecting-sc… │
│                                                                                                                       │
│ 2026-04-24T11:49:08.017Z ...using env file in                                                                         │
│ /Users/brucemcpherson/Documents/repos/empty/recipe-web-to-doc-gf/scripts/.env                                         │
│ 2026-04-24T11:49:08.763Z ...gas-fakes version 2.3.9                                                                   │
│ 2026-04-24T11:49:08.763Z Fetching content from:                                                                       │
│ https://ramblings.mcpher.com/resurrecting-scriptdb-nosql-database-for-apps-script/                                    │
│ 2026-04-24T11:49:09.451Z [Worker] ...authorized backends: google via DWD ([email protected])                           │
│ 2026-04-24T11:49:09.451Z [Worker] ...using scriptId: ab9c5881-...-2bc29a0c8834 (source: env)                          │
│ 2026-04-24T11:49:14.788Z Created original document with ID: 1sQ7oGqKm9XOQzsYQF10fM6uiAoD2_OSJ6uAJgunPnbE              │
│ 2026-04-24T11:49:17.980Z Created copy document with ID: 1Labz...ZSSo                                                  │
│ 2026-04-24T11:49:19.052Z Found 12 images in the document.                                                             │
│ 2026-04-24T11:49:19.053Z Applying 24 updates to resize images...                                                      │
│ 2026-04-24T11:49:21.557Z Image resizing complete.                                                                     │
│ 2026-04-24T11:49:21.557Z Original Doc URL:                                                                            │
│ https://docs.google.com/document/d/1sQ7...PnbE/edit                                                                   │
│ 2026-04-24T11:49:21.558Z Resized Doc URL:                                                                             │
│ https://docs.google.com/document/d/1Labz...ZSSo/edit                                                                  │
│ 2026-04-24T11:49:21.563Z ...terminating worker thread                                                                 │
│                                                                                                                       │
╰───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯

✦ I have successfully fetched the content from the specified URL and created the requested documents.

Weighing the Approaches: Broad CLI vs Sandboxed Emulation

Let us consider the practical realities of these two approaches. The Workspace CLI generally operates under the broad OAuth scopes granted during its initial setup. If you authorise full Google Drive access, any AI agent driving that CLI inherently possesses the same unrestricted permissions. Handing an autonomous reasoning engine the keys to your entire file system is risky. A simple mis-prompt could lead to data loss or unintended modifications.

Conversely, Bruce’s gas-fakes approach offers a much tighter, sandboxed environment. Rather than relying on global credentials, gas-fakes can be explicitly configured to operate only on specific Drive files or within isolated boundaries. By functioning as a Model Context Protocol (MCP) server, it allows the LLM to write native Apps Script syntax and immediately test it against Workspace resources, but it forces the execution to happen within a securely fenced area. The primary benefit here is safe, dynamic adaptability. You do not need to pre-write a specific skill to resize an image; the agent simply authors the script on the fly and the emulator runs it safely.

It is worth mentioning that gas-fakes is still in development so not all Apps Script methods are implemented yet, but the approach provides a robust sandbox for interacting with Workspace APIs. Click through to Bruce’s post to read more.

Source: gas-fakes agent: local natural language requests against workspace resources – Desktop liberation

Breaking boundaries: Running native Apps Script on Google Cloud Run

Containerize apps script code and run it on cloud platforms such as Cloud Run outside the context limitations of the Apps Script IDE.

Bruce Mcpherson continues to expand the capabilities of his gas-fakes library, a tool that has already proven valuable for running Google Apps Script locally on Node.js. In his latest update, Bruce demonstrates how to take this a step further by containerising Apps Script code to run on Google Cloud Run.

For developers familiar with the constraints of the Apps Script IDE, particularly the execution time limits, moving logic to a serverless container environment offers a powerful alternative. With the release of version 2.0.2, gas-fakes now includes a managed configuration for Workspace Domain-Wide Delegation (DWD) enabling secure keyless authentication.

Essentially, this allows developers to package their Apps Script logic into containers, enabling execution on scalable platforms like Cloud Run, free from the constraints of the standard IDE.

Authentication and Service Accounts

One of the friction points in moving from a bound script to a cloud environment is authentication. Bruce highlights that while Application Default Credentials (ADC) work well for local development, a more secure method is required for Cloud Run. The updated gas-fakes CLI simplifies this by handling the service account configuration automatically.

The library supports two primary authentication types:

  • Domain-Wide Delegation (DWD): Recommended for production environments and cross-platform scenarios, such as Cloud Run or Kubernetes.
  • Application Default Credentials (ADC): A fallback method primarily for local development.

Containerisation Workflow

For those looking to deploy their own scripts, Bruce’s guide walks through the essentials required to containerise a project.

It is important to note that while the core logic can be written in JavaScript, you will need to manually set up the infrastructure configuration. The guide provides the specific code required for:

  1. The Dockerfile: To mimic the Apps Script runtime environment.
  2. Cloud Build Configuration: A cloudbuild.yaml file to manage the build steps.

To tie it all together, the article includes a deployment script (referred to as deploy-cloudrun.sh in the text) which automates the pipeline. It handles everything from creating the Artifact Registry repository and submitting the build, to monitoring the deployment.

Code Example

To help developers get started, Bruce has provided a dedicated repository containing a working example.

Note on usage: The repository contains the core Node.js logic (example.js) and a deployment helper script (named exgcp.sh in the repo). However, to deploy this successfully, you will need to combine these files with the Dockerfile and cloudbuild.yaml configurations detailed in the main article. Bruce notes there is more to come.

The example.js file illustrates how standard Apps Script services are imported and used within the Node.js environment. By requiring gas-fakes, you can access services like DriveApp or SpreadsheetApp using the exact same syntax you use in the Apps Script editor, bridging the gap between local Node development and the Google Cloud runtime.

Summary

This development opens up interesting possibilities for hybrid workflows where lightweight tasks remain in Apps Script, while heavier processing is offloaded to Cloud Run without needing to rewrite the core logic in a different language. If you are interested in trying this out, Bruce has provided example deployment scripts and a troubleshooting guide to help you get started.

Source: Yes – you can now run native Apps Script on Cloud Run! – Desktop liberation

Gassypedia January 2025 Update: Apps Script Ecosystem Growth

Quarterly update on the shared bigquery dataset all about the Apps Script developer ecosystem on Github, with reports available on looker.

Bruce Mcpherson’s latest Gassypedia update offers a look at the Apps Script ecosystem, using publicly shared code on GitHub. The report analyses data from over 3100 developers and nearly 100 million files across 200,000 repositories. You can read the full report from the source link at the bottom but here are some key points:

  • Growth: The Apps Script community is still expanding, but at a slightly slower pace than before.
    • The number of developers increased by 4%.
    • Shared repositories grew by 3%.
    • Manifests increased by 2%.
  • Add-ons: There’s a 13% increase in Add-ons shared on GitHub.
    • Chat Add-ons are now most popular, surpassing Sheets.
    • Chat Add-ons increased by 18%, and Sheets Add-ons by 10%.
    • Calendar Add-ons saw a slight decrease.
  • Code Sharing: While the number of Apps Script developers and related content has increased, the total number of all types of repositories and files associated with them has decreased by almost 5%. However, the percentage of those repositories that are Apps Script related has increased.
  • Clasp: 25.2% of manifests showed Clasp usage, a 1% increase.
  • OAuth: 851 repos and 1008 manifests use the auth/script_external_request scope, a 6% increase.
  • Advanced Services: Drive is the most popular advanced service, used in 499 manifests.
  • Web Apps: 53% of web apps are public, and 81% are executed as the user deploying. 6% of web apps are created in Japan.
  • Libraries: oauth2 is the most popular library, with 236 users.

Key Takeaways

  • Apps Script is still a growing platform, with many developers sharing their work.
  • The rise of Chat Add-ons indicates the maturing of the platform for Google Workspace users.
  • More developers are sharing Apps Script projects on Github.

Explore the Data

Bruce’s full report is on Looker, with the data available on BigQuery. You can use this data for your own research and share any findings with Bruce.

Source: Gassypedia – January 2025 update – Desktop liberation

Harnessing the power of Puppeteer, Cloud Run, and GraphQL with Google Apps Script

A Google Cloud run hosted puppeteer with a graphQL interface … In this article I’ll show you how to use this (I’ve called it gql-puppet ) with Apps Script

One of Apps Scripts superpowers is the ability to make HTTP requests to external services. These can be requests to other product APIs, or as in the following example, your own services. In this post from Bruce Mcpherson you can learn how you can use Google Apps Script to interact with a service he has created on Cloud Run which has a deployment of the headless browser, Puppeteer.

To interact with Puppeteer, Bruce has added GraphQL as an application interface. GraphQL is a query language that allows developers to request specific data from an API, making it more efficient and flexible than REST, which often requires multiple requests to retrieve the same data.

As Puppeteer is just a browser there are lots of things you can do like take a screenshot, print a PDF or get the page content. With GraphQL there is an interface layer to do this as well as returning specific data from a webpage.

The article has various code examples for different use cases, such as taking screenshots, extracting table data, and creating PDFs from web pages using Google Apps Script and saving the data in Google Drive. Bruce is providing access to his combined Puppeteer/Cloud Run/GraphQL solution, gql-puppet but you can also find out how you can deploy it as your own service.

Source: Puppeteer, Cloud Run and GraphQL together – Desktop liberation

Sharing cache data between Google Apps Script projects with bmCacheSharer

Shared cached data between multiple scripts with this enhanced Apps Script Cacheservice library

Bruce Mcpherson has shared a new Apps Script library, bmCacheSharer, which enables sharing of cache data between multiple Google Workspace projects. The library was originally created to solve the problem of sharing configuration data stored in a Google Sheet with multiple script projects.

The library includes a number of nice features to overcome some of the limitations of the Apps Script CacheService, such as the 100k maximum item size and the 6-hour expiration limit by incorporating features like compression, key digestion, and automatic refresh.

It also provides options for sharing cached values by using community keys. The library is designed to be flexible, allowing users to either use its built-in cache service or provide their own. Additionally, it offers a memory cache for faster access within the same script instance. The document includes code examples and explanations to illustrate the library’s usage and benefits.

Follow the source link to find out more..

Source: Google Apps Script CacheSharer library

Google Apps Script gets a public knowledge base of Github projects with Gassypedia

All the Google Apps Script related github activity is now on Google Bigquery and Google Looker. Here’s how it was done.

Bruce Mcpherson has recently revisited his work on the visual Google Apps Script explorer tool, scrviz. Bruce has been working diligently to address limitations with the Github API and overcome quota restrictions. This new iteration still allows users to explore Google Apps Script projects and creators, but this time through a shared Looker Studio dashboard. The underlying dataset has also been made available on BigQuery if you would like to do your own analysis.

Follow the source link to find out more and explore the data!

Source: Gassypedia – public Google Apps Script on Github – Desktop Liberation

New Google Apps Script library to convert files with the Drive API (including OCRing image file formats)

Apps Script library to convert between file types, including OCR for image to documents, with a huge repertoire of conversion combinations.

The Drive API offers a whole range of conversions between mimeTypes, but it’s a little fiddly to figure out exactly how. This library takes a file and an a desired output format and converts it for you. Sometimes, there’s not a direct route – for example if you need to convert a word file to a pdf, it first needs to get converted to a Google Doc, then to a Pdf. This library automatically works out and actions any intermediate conversions required.

For those who are unfamiliar MIME types (mimeTypes) is a standard way of identifying a file’s content type, such as text, image, or audio. The MIME type for a file is usually used by applications to determine how to open and display the file. Google Drive is able to convert various files, such as a MS Word document to Google Docs.

Sometimes there isn’t a direct route and this clever library from Bruce Mcpherson can help alleviate the pain. The library works by first checking if there is a direct route between the input and output file formats. If there is, it simply converts the file. If there is no direct route, the library will use the Drive API to first convert the file to a format that can be converted to the output format. For example, if you need to convert a Word file to a PDF, the library will first convert the Word file to a Google Doc, and then convert the Google Doc to a PDF.

Knowing what mimeType to use can be a bit of a challenge but you can also use the library to give a list of known types, or if you prefer a more readable list of Google Drive export MIME types.

Source: Convert any file with Apps Script – Desktop Liberation

Generating XML and HTML from JSON objects using Google Apps Script

A useful library to create prettified HTML, XML GraphML and other markups directly from Apps Script or JavaScript.

A long, long, long time ago Apps Script had a Xml class which was deprecated in favour of the current XML Service. One of the nice features of the old Xml class was the Xml.parseJS() method, which “given a JavaScript array … returns an XmlDocument representation”.

The current XML Service doesn’t have a JavaScript to XML parser, but Bruce Mcpherson has recently shared a library that can be used to easily convert JSON objects into XML and it’s many recognised formats like HTML. Bruce’s post shows how to can create various HTML page elements including head sections and tables. It’s also worth checking out Bruce’s other post on “Create GraphML markups from Apps Script” which is included in the source link.

Source: Markup HTML from JSON with Apps Script or JavaScript

Find and clone Apps Script projects from GitHub directly into the IDE with scrviz – Desktop Liberation

I thought it might be useful if you are learning Apps Script to be able to pull in examples to play around with. This latest release adds the ability to configure and clone projects from github directly into the Apps Script IDE.

We’ve previously highlighted Bruce Mcpherson’s visual Google Apps Script explorer tool, ‘scrviz’. If you are not familiar with this it is Bruce has figured a way to search and identify Google Apps Script projects publicly shared on GitHub. In this latest update to the tool you can now clone public Google Apps Script projects from scrviz straight into the Apps Script IDE.

The source link explains more about how you can do this:

Source: Find and clone Apps Script projects from github directly into the IDE with scrviz – Desktop Liberation