import zipfile import StringIO from django import http from django.template import Context, Template def print_odf( request, odf_path, context ): """ odf_path - path to the template document context - dictionary to create context from """ c = Context() for key, value in context.items(): if callable( value ): c[key] = value() else: c[key] = value # default mimetype mimetype = 'application/vnd.oasis.opendocument.text' # ODF is just a zipfile input = zipfile.ZipFile( template_name, "r" ) # we cannot write directly to HttpResponse, so use StringIO text = StringIO.StringIO() # output document output = zipfile.ZipFile( text, "a" ) # go through the files in source for zi in input.filelist: out = input.read( zi.filename ) # waut for the only interesting file if zi.filename == 'content.xml': # un-escape the quotes (in filters etc.) t = Template( out.replace( '"', '"' ) ) # render the document out = t.render( c ) elif zi.filename == 'mimetype': # mimetype is stored within the ODF mimetype = out output.writestr( zi.filename, out ) # close and finish output.close() return http.HttpResponse( content=text.getvalue(), mimetype=mimetype )