Skip to content

Instantly share code, notes, and snippets.

@noamtamim
Forked from jesperronn/docx2md.md
Last active February 19, 2018 20:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save noamtamim/7cf3dc250d7f6c87d98d48ebf4a76f7a to your computer and use it in GitHub Desktop.
Save noamtamim/7cf3dc250d7f6c87d98d48ebf4a76f7a to your computer and use it in GitHub Desktop.
Convert a Word Document into MD

Converting a Word Document to Markdown in One Move

The Problem

A lot of important government documents are created and saved in Microsoft Word (*.docx). But Microsoft Word is a proprietary format, and it's not really useful for presenting documents on the web. So, I wanted to find a way to convert a .docx file into markdown.

Installing Pandoc

On a mac you can use homebrew by running the command brew install pandoc.

The Solution

As it turns out, there are several open-source tools that allow for conversion between file types. Pandoc is one of them, and it's powerful. In fact, pandoc's website says "If you need to convert files from one markup format into another, pandoc is your swiss-army knife." Pandoc can convert from markdown into .docx, and it also works in the other direction.

Example

Say you have the Council Rules in a Word Document named "test.docx." (For a real-life example, visit http://github.com/vzvenyach/Council_Rules/). Now, you run the following at the command line:

pandoc -f docx -t markdown -o test.md test.docx

Out is a beautiful markdown file. Admittedly, there's a bit of junk at the top with the Table of Contents. I deleted this when I rendered it nicely with strapdown.js. In the end, here's my nicely rendered version of the Rules.

#!/bin/bash
#
# generate a Markdown version of a word document. Goes in separate folder, since
# images are extracted and converted as well (separate folder avoids naming clashes).
#
# REQUIREMENTS: pandoc
#
#
# with pandoc
# --extract-media=[media folder]
#
# USAGE:
#
# docx2md.sh filename
#
# This will generate a converted file in a subfolder, for example if you have a file
# `contract.docx`:
#
# generates:
# ```
# contract
# ├── README.md
# └── media
# ├── image1.png
# ├── image2.png
# └── image3.png
# ```
#
which pandoc > /dev/null
rc=$?
if [[ $rc != 0 ]]; then
echo "FATAL missing pandoc. You can install with 'brew install pandoc' or similar"
exit 9
fi
if [ -z "$1" ]; then
echo "Usage:"
echo ""
echo " ./docx2md.sh [filename]"
exit 13
fi
if [ ! -f "$1" ]; then
echo "FATAL missing file '$1'"
exit 11
fi
name=$(basename $1 .docx)
mkdir -p "$name"
cd "$name"
pandoc -f docx -t gfm --extract-media="." -o "README.md" "../$1"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment