Created
May 7, 2013 03:42
-
-
Save jingoro/5530113 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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