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.

Leave a Reply

Your email address will not be published. Required fields are marked *