| |
Dynamic OpenOffice.org Document
Submitted by: evan
Last Edited: 2005-11-17
Category: Python(External Method)
|
| Average rating is:
4.6 out of 5
|
(5 ratings) |
|
Description:
I needed to provide a printed report (a poster, actually) that used simple dynamic data, rather like a typical word processing mail merge. Unlike previous reports of this kind, which I've generated as PDFs using ReportLabs, the design of the poster needed to be easily updated by our graphic designer.
To solve the problem, I had the designer create the poster in OpenOffice.org Writer and upload it to Zope. Thanks to OOo's fantastically transparent file format, I was able to do a search and replace on the document in order to insert the data.
|
Source (Text):
import zipfile, cStringIO
def merge_ooo_doc(doc, fields, data):
docf = cStringIO.StringIO(doc)
zf = zipfile.ZipFile(docf)
txt = zf.read('content.xml')
for (field, k) in fields:
parts = txt.split(field)
newparts = [parts.pop(0)]
i = 0
while parts and i < len(data):
newparts.append(str(data[i][k]))
newparts.append(parts.pop(0))
i = i + 1
newparts.extend(parts)
txt = ''.join(newparts)
out = cStringIO.StringIO()
zf2 = zipfile.ZipFile(out, 'w')
for zi in zf.infolist():
if zi.filename == 'content.xml':
zf2.writestr(zi, txt)
else:
zf2.writestr(zi, zf.read(zi.filename))
zf2.close()
zf.close()
return out.getvalue()
|
Explanation:
The External Method takes the document template as a string, a list of (tag, key) pairs, and a list of mappings. For each (tag, key) pair, it replaces the first instance of the tag string with the value of the key in the first dictionary, the second instance with the value from the second dictionary, etc. It returns the resulting document as a string.
For example, I had the designer use placeholders such as '[[CODE]]' and '[[DESCRIPTION]]'. My 'fields' looked like '[("[[CODE]]", "CODE"), ("[[DESCRIPTION]]", "DESCRIPTION"), ...]', and my data was the .dictionaries() of the result set from a Z SQL Method.
|
Comments:
No Comments
|
|