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