Markdown2PDF with Prince XML and TextMate
Posted by Ben Jackson Fri, 23 Dec 2005 02:29:00 GMT
I've been wanting a decent way to convert Markdown-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. 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
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<div id="header">
<img src="/usr/local/prince/images/logomark_RGB.png" />
</div>
<div id="footer">
<div>
<img src="/usr/local/prince/images/logo_horizontal_eng_RGB.png" />
</div>
<div class="address">info@incomumdesign.com<br />www.incomumdesign.com</div>
<div class="address">Rua Emilio Berla, n° 180<br />Copacabana, RJ 22061-060</div>
<div class="address">+55 (21) 9997-0593<br />+55 (21) 9997-0594</div>
</div>
EOD
# this is the body of the document
markdown $TM_FILEPATH >> $tmp_xml
# close up the tags
cat >> $tmp_xml <<EOD
</body>
</html>
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 "<meta http-equiv='refresh' content='0; tm-file://$dest'>"
Here's the rundown:
- Designate a temporary xml file to hold the final xml document, and set the final pdf's path, using a neat bash trick to preserve the file's basename.
- Write the doctype, head information, etc. as well as the header and footer (see Prince's documentation for more info).
- Run markdown on the document's texts.
- Close up the tags.
- Run the xml through prince with our own style sheet.
- Clean up and print out a browser redirect to open the pdf.
You'll need Schubert's PDF Plugin to view PDFs with Safari (and consequently TextMate).

I was all excited about this until I saw the pricing for Prince. Boo.
Thanks for showing another example for using Textmate though
Yeah, it ain't an impulse buy, that's for sure ;)