Avatar
Linux, plaintext & minimalism
April 9, 2018

Converting Markdown to HTML

To convert Markdown-documents to HMTL-documents I use Markdown2, which is a complete implementation of Markdown in Python.

It’s available via pip:

$ pip install markdown2 --user

To convert a document you simply use the command:

$ markdown2 input_file.md > output_file.html

But if you use tables in your document it will not render them correctly unless you add the flag -x tables:

$ markdown2 input.md > output.html -x tables

The default styling of tables is bad as you can see in this before and after picture:

The styling I added was this:

<style>
	table { border-collapse: collapse; width:100%; }
	td, th { border: 1px solid #ddd; padding: 8px; }
	tr:nth-child(even){background-color: #f2f2f2;}
	tr:hover {background-color: #ddd;}
	th { padding-top: 12px; padding-bottom: 12px; background-color: #ddd; }
</style>

But manually adding that to every document with tables isn’t going to be very fun, so I wrote a simple script called md2html.sh to do it for me:

#!/bin/sh
markdown2 $1 > $2 -x tables
sed -i '1 i\<style>table { border-collapse: collapse; width:100%; }	td, th { border: 1px solid #ddd; padding: 8px; } tr:nth-child(even){background-color: #f2f2f2;}	tr:hover {background-color: #ddd;} th { padding-top: 12px; padding-bottom: 12px; background-color: #ddd; }</style>' $2

And to use it:

$ md2html.py input.md output.html

If I want to convert it to a PDF-document I just print it to a PDF-document via my web browser, which saves me from installing additional packages for something that I rarely ever use anyway.

Tags: Markdown | HTML

Feedback

I don't have a commenting system simply because I haven't found a solution that I like. If you want to leave any feedback and/or have any questions, feel free to contact me either via e-mail, fediverse, XMPP or IRC (I'm Hund at freenode.net).