Skip to content

Instantly share code, notes, and snippets.

@jingoro
Created May 7, 2013 03:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jingoro/5530113 to your computer and use it in GitHub Desktop.
Save jingoro/5530113 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# prerequisites
# sudo easy_install markdown
# install https://code.google.com/p/wkhtmltopdf/
WKHTMLTOPDF_PATH = "/usr/local/bin/wkhtmltopdf"
import sys, os, subprocess, re, urllib, tempfile
import markdown
if __name__ == '__main__':
if len(sys.argv) < 1:
print 'Usage: %s <file.(md|txt|text)>' % sys.argv[0]
sys.exit(1)
filepath = os.path.abspath(sys.argv[1])
filename = os.path.basename(filepath)
dirname = os.path.dirname(filepath)
filebase = re.sub(r'\.[a-zA-Z0-9]+$', '', filename)
baseurl = "file://" + urllib.quote(dirname)
temppath = tempfile.mkstemp('.html')[1]
outpath = os.path.join(dirname, filebase + '.pdf')
html = markdown.markdown(open(filepath).read())
html = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>%s</title>
<base href="%s/" />
</head>
<body>
%s
</body>
</html>
""" % (filebase, baseurl, html)
f = open(temppath, 'w')
f.write(html)
f.close()
subprocess.call([WKHTMLTOPDF_PATH, '--quiet', '--lowquality', temppath, outpath])
# print temppath
os.remove(temppath)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment