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:

  1. 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.
  2. Write the doctype, head information, etc. as well as the header and footer (see Prince's documentation 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 to view PDFs with Safari (and consequently TextMate).

2 comments | no trackbacks

Comments

  1. Luke Hartman said 17 days later:

    I was all excited about this until I saw the pricing for Prince. Boo.

    Thanks for showing another example for using Textmate though

  2. Ben Jackson said 17 days later:

    Yeah, it ain't an impulse buy, that's for sure ;)

Trackbacks

Use the following link to trackback from your own site:
http://www.unfitforprint.com/trackbacks?article_id=markdown2pdf-with-prince-xml-and-textmate&day=23&month=12&year=2005

Comments are disabled