Rich Text Format (RTF) documents from your web2py application

We needed to generate Microsoft Word .doc files from a web application based on web2py.  Creating a .doc file from scratch from python is no small task, but luckily for us rtf (Rich Text Format) files can be opened natively by Word and cover everything we needed.

Web2py includes the pyrtf library. Pyrtf is a set of python classes that make it possible to produce RTF documents from python programs. The library has no external dependencies and has proven reliable and fast.

The code snippet below is in a web2py function, it imports the library, initializes it and then creates a simple rtf doc.

After adding the line ‘Certified Staff Evaluation’ the function returns the newly created doc file. It is possible to create tables and include images – documentation for the library and example rtf generation files can be found at PyRTF. (note that web2py uses a slightly older version of pyrtf – you can see docs for it here.

from gluon.contrib.pyrtf import *

doc     = Document()
ss      = doc.StyleSheet
section = Section()
doc.Sections.append( section )

p = Paragraph( ss.ParagraphStyles.Heading1 )
p.append( 'Certified Staff Evaluation' )
section.append( p )
return doc

PDFS from GAE using web2py & pdfcrowd

Recently we used pdfcrowd to print pdfs from several of our applications running on the Google App Engine.

Integration is very straight forward – we use the web2py python framework to run on top of GAE – so these steps reflect that. Also in our example we want our python function to return the content as a pdf file.

  1. Register at pdfcrowd
  2. Download their python client library
  3. Copy the source of the client library to the module directory of your web2py application directory
  4. Use the code snippet example below to initialize and call the pdfcrowd library
def print_observation_formpdfcrowd():

   out = StringIO.StringIO()

   pdfcrowd = local_import('pdfcrowd')

   client = pdfcrowd.Client("username", "apikey")

   # our html to convert
   html='<head></head><body>My HTML Layout</body>'

   client.convertHtml(html, out)

   # prepare PDF to download:

   pdf_file_name = 'evaluation.pdf'


   return out.getvalue()