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

Gists

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

Description

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

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.

This report introduces the following 2 sample scripts to explore this potential.

Sample scripts

The sample script uses Drive API. So, please enable Drive API at Advanced Google services. Ref

1. Convert Google Document to markdown

Please set the document ID of the Google Document.

function sample1() {
  // Please set your Document ID.
  const documentId = "###";

  const url = `https://docs.google.com/feeds/download/documents/export/Export?exportFormat=markdown&id=${documentId}`;
  const res = UrlFetchApp.fetch(url, {
    headers: { authorization: "Bearer " + ScriptApp.getOAuthToken() },
  });
  const blob = res.getBlob();
  DriveApp.createFile(blob);
}

Testing

When the following sample Google Document is used,

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

the following result is obtained.

sample text 1

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

sample text 2

* sample option1
* sample option2
* sample option3

sample text 3

2. Convert markdown to Google Document

In this case, the sample script is very simple. Please set the file ID of the markdown file.

function sample2() {
  // Please set the file ID of the markdown file on your Google Drive.
  const fileId = "###";

  Drive.Files.copy({ mimeType: MimeType.GOOGLE_DOCS }, fileId, {
    supportsAllDrives: true,
  });
}

Testing

When the following sample markdown is used,

sample text 1

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

sample text 2

* sample option1
* sample option2
* sample option3

sample text 3

the following result is obtained.

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

Note

Reference

 Share!