Skip to content

Instantly share code, notes, and snippets.

@batok
Created February 25, 2011 16:54
Show Gist options
  • Save batok/844077 to your computer and use it in GitHub Desktop.
Save batok/844077 to your computer and use it in GitHub Desktop.
En example of using mako and pisa to generate pdf. Python 2.6 o 2.7 needed $ virtualenv --no-site-packages yourenv $ cd yourenv $ source bin/activate $pip install mako pypdf html5lib reportlab pisa $python mako_pisa_example.py
import os, sys, subprocess
from mako.template import Template
from mako.runtime import Context
from cStringIO import StringIO #needed as buffer for mako
try:
from mako.util import FastEncodingBuffer #new kind of buffer that is faster ( version 0.4) than StringIO
except:
pass
from ho import pisa as pisa
def preview(pdf_file_name= "output.pdf"):
if sys.platform == "win32":
try:
os.startfile( pdf_file_name)
except:
return
return
if sys.platform == "darwin":
command = "open {0}".format(pdf_file_name)
else:
command = "xdg-open {0}".format( pdf_file_name )
try:
p = subprocess.Popen(command, shell = True)
pid , sts = os.waitpid(p.pid, 0)
except subprocess.CalledProcessError, e:
print "Error", e.returncode
print e.output
return
def generate( data = "hello world", template_file = "foo.html", output_file_name = "template_output.html", pdf_file_name="output.pdf"):
t = Template(filename = template_file, input_encoding = "utf-8")
try:
buf = FastEncodingBuffer()
except:
buf = StringIO()
ctx = Context(buf, data = data)
t.render_context( ctx )
open(output_file_name,"w").write(buf.getvalue())
html = buf.getvalue().encode("utf-8")
pdf = pisa.CreatePDF(StringIO(html), file( pdf_file_name, "wb"))
if pdf.err:
print "I couldn't generate {0}".format( pdf_file_name )
return
try:
pdf.dest.close()
except:
print "Problems when closing pdf file"
return
if __name__ == "__main__":
generate()
preview()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment