Convert Markdown to PDF

Lately, I wrote a small text in markdown and felt the need to share it with someone (non-technical). I searched for solutions to convert markdown to PDF and was very surprised, that there were only so-so solutions. After some googling and coding I found an easy to use solution which comprises a markdown tool for converting markdown to html and phantomJS (a headless WebKit scriptable) for converting html to pdf. The cool things: hyperlinks and custom css work.

If you are on a mac, you can use homebrew for installing the dependencies (on linux distributions you should have a corresponding package manager):

brew install markdown phantomjs

Then create a new bash script (and chmod 751 it, so that it is executable):


echo "<html><head>" > $tmpfile
echo "<link rel=\"stylesheet\" type=\"text/css\" href=\"$cssfile\">" >> $tmpfile
echo "</head><body>" >> $tmpfile
markdown $inputfile | iconv -f utf8 -t l1 >> $tmpfile
echo "</body></html>" >> $tmpfile
phantomjs $PHANTOMJS_HOME/share/phantomjs/examples/rasterize.js $tmpfile $outputfile A4
rm $tmpfile

You may call it via command line:

$ ./ myfile.pdf markdown2.css

I used markdown2 css, which is copied (and adapted a little bit) from jasonm23.

Of course, this script is not perfect, since all references to local images (or similar stuff) are interpreted relative to /tmp. But I leave this as an exercise to the reader.

Exciting 😉


Here is a cool tool (pandoc), that allows to convert from anything to anything including markdown to html and pdf. 🙂
And this is a cool open-source markdown editor for mac (macdown). 🤓

Leave a Reply

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