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.

Comments

I'm looking into a good way of implementing comments on my blog that works without JavaScript, respects the users privacy and is reasonably user friendly. If you have any ideas or just want to give me some feedback on this blog post or if you just want to say hello, feel free to do so either via e-mail, XMPP or Mastodon.