Markdown2PDF with Prince XML and TextMate
=========================================
I've been wanting a decent way to convert [Markdown][1]-formatted text to a nice, printable PDF on our company letterhead forever. I even tried rolling my own with some InDesign scripting, but quickly gave up when I realized that its XML support is below dismal.
Enter [Prince][2]. It takes html and css and turns it into a PDF. And it works. No fuss.
Download movie, text, and pdf.
Now, if only I could set up my editor to export to PDF and preview it in a new window, I'd be on easy street. Thankfully, TextMate makes that a snap with a bit of bash voodoo:
# temporary file for the output xml
tmp_xml="/tmp/${TM_FILENAME%.*}.xml"
# final pdf destination
dest=${TM_FILEPATH%.*}.pdf
# HTML header
cat > $tmp_xml <
EOD
# this is the body of the document
markdown $TM_FILEPATH >> $tmp_xml
# close up the tags
cat >> $tmp_xml <
EOD
# convert temp xml to pdf
prince -s /usr/local/prince/stylesheets/INCOMUM_letterhead_en_a4.css $tmp_xml $dest
# remove temp files
rm $tmp_xml
# show result as HTML
echo ""
Here's the rundown:
1. Designate a temporary xml file to hold the final xml document, and set the final pdf's path, using a [neat bash trick][3] to preserve the file's basename.
2. Write the doctype, head information, etc. as well as the header and footer (see [Prince's documentation][4] for more info).
3. Run markdown on the document's texts.
4. Close up the tags.
5. Run the xml through prince with our own style sheet.
6. Clean up and print out a browser redirect to open the pdf.
You'll need [Schubert's PDF Plugin][5] to view PDFs with Safari (and consequently TextMate).
[1]: http://www.daringfireball.net/projects/markdown/
[2]: http://www.princexml.com/
[3]: http://www.tldp.org/LDP/abs/html/parameter-substitution.html
[4]: http://princexml.com/doc/page-headers-footers/
[5]: http://www.schubert-it.com/pluginpdf/