Tuesday, 29 April 2008

Outputting pdfs with google app engine

It's child easy, but not googleable yet. I used reportlab - a handy, pure-python pdf library. Here are the steps:

  1. Checkout reportlab into your app directory
    svn co http://www.reportlab.co.uk/svn/public/reportlab/trunk \
    reportlab
  2. Write some pdf-generation code, like
    import wsgiref.handlers

    from google.appengine.ext import webapp

    from reportlab.pdfgen import canvas


    class MainPage(webapp.RequestHandler):

    def get(self):
    self.response.headers['Content-Type'] = 'application/pdf'
    p = canvas.Canvas(self.response.out)
    p.drawString(100, 750, "Hey, it's easy!.")

    p.showPage()
    p.save()



    def main():
    application = webapp.WSGIApplication([('/', MainPage)], debug=True)
    wsgiref.handlers.CGIHandler().run(application)

    if __name__ == "__main__":
    main()
    The key is the canvas instantiation. The constructor takes a file-like object and writes into it. You might have noticed that the code is heavily inspired by this tutorial. The only difference is the creation of canvas.
  3. That's it. See? I said it was easy. You can run the dev_appserver or upload it to Google in order to see the results.