Wednesday, November 26, 2008

Adventures in Flash and Python

The last couple of weeks I have been making a nice little Flash application, a questionnaire, for a government project. One of the features of the questionnaire was the ability to print out results based on the answers given.

In order to do pretty printing of the results, I used the awesome AlivePDF library to generate PDFs for the user to print. Neat stuff. It was a bit dodgy to get it up and running - especially because you cannot force a download from your Flash file. Instead the library uses a neat little trick of generating the PDF content in the Flash and then posting the content to another web-page that converts the post to a download-file. Pretty neat stuff.

Included with the library is a PHP script that does that little trick, and I managed to get it up and running. Especially AFTER I discovered that the reason it did not work was that my IE8 beta just didn't accept what was going on. Not even in compat mode. So I had to use Firefox. Discovering that I had to go there was a stroke of luck.

All that out of the way. Or so I thought. Because suddenly things got spicy. Clearing the solution with operations revealed the fact that they had no PHP running anywhere, so could I please make it work with Python? Yes, of course... Because I know Python (NOT). But how hard can it be? The PHP script is only 10 lines of code for crying out loud!

So I got my feet wet in Python. The language itself does not seem that hard, but getting to know the environment and how to test was not easy. But I managed to bang out a Python script that does what the doctor ordered. And only 'round 100 times slower than a real Python haX0r. :P

So if you ever need to use Python and AlivePDF, here is the script. It is missing any kind of error handling code, and may not work in all scenarios. And I will probably not be able to fix it for you. But knock yourself out.

  1: #!/usr/bin/env python
  3: import sys, cgi
  4: import cgitb; cgitb.enable()
  6: query = cgi.FieldStorage()
  7: dict = {}
  8: for param in query.qs_on_post.rsplit("&"):
  9: 	parsplit = param.rsplit("=")
 10: 	dict[parsplit[0]] = parsplit[1]
 13: print "Content-Type: application/pdf"
 14: print "Content-Length: " + query.headers["content-length"]
 15: print "Content-disposition:" + dict["method"] + "; filename='" + dict["name"] + "'"
 16: print
 17: print

No comments: