AppsScriptPulse

Using Google Drive API and Google Apps Script to convert between Google Docs and Markdown

Great news for fans of both Google Docs and Markdown! Google Docs recently acquired the ability to export documents directly into the markdown format.

This functionality extends beyond the user interface, with early indications suggesting the Google Drive API might also be capable of converting between Google Docs and Markdown. I confirmed that this could also be achieved by Drive API. This opens exciting possibilities for automated workflows.

Google recently announced in July 2024 that import and export Markdown in Google Docs. This is a user facing features, which Google announced includes the ability to:

  • Convert Markdown to Docs content on paste
  • Copy Docs content as Markdown
  • Export a Doc as Markdown (from File > Download)
  • Import Markdown as a Doc (from File > Open or “Open with Google Docs” from Drive)

Kanshi Tanaike hasn’t wasted any time in unpicking Markdown conversion capabilities using the Google Drive API. This functionality enables automated workflows for converting between Google Docs and Markdown. There are various scenarios where this can be useful, in particular, given GenAI solutions like the Gemini API often generate markdown there are opportunities to automatically convert these to Google Docs.

As part of the source post there are sample scripts: one for converting Google Docs to Markdown and another for converting Markdown to Google Docs.

For the Markdown to Google Docs it is assumed that there is already a Markdown file in Google Drive. If you have a Markdown text as a string, for example from a Gemini API response, then you can create a formatted Google Doc using the following snippet designed to be used with v3 of the Google Drive Advanced Service:

function sample3() {
  // note string is tab sensitive (tabs are converted to code blocks on certain Workspace accounts)
  const sampleText = `sample text 1

| a1 | b1 | c1 |
| :---- | :---- | :---- |
| a2 | b2 | c2 |

sample text 2

* sample option1
* sample option2
* sample option3

sample text 3`;

  const blob = Utilities.newBlob(sampleText, 'text/markdown');
  const fileMetadata = {
    name: `Sample MD Conversion`,
    mimeType: MimeType.GOOGLE_DOCS,
  };

  Drive.Files.create(fileMetadata, blob, { supportsAllDrives: true });
}

Source: Convert Google Document to Markdown and vice versa using Google Apps Script

Leave a Reply

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