DEV Community

lukaszkuczynski
lukaszkuczynski

Posted on • Originally published at lukaszkuczynski.github.io on

OpenOffice docs and Python

Writing ODT by Python

When creating my little Python utility I realized, that writing data to txt via print (console) will not be enough. To make my pinmix little more useful I wanted to create the way of clear presentation of a textual data. The first thought was to create a HTML with contents, using classes and divs. But, I usually use Word-like tools to edit and modify my documents. They have this nice option of posting comments and so on. And overall this is more straightforward way of managing text documents, right? So how to create OpenOffice doc with Python? It is so easy using odfpy module.

Solution

So this is basically how I did that using Python. You are just to import some libraries and voila, happy editing. Having separate styles defined you can then do the batch-updates of all of the similar text parts. It sounds like fast document adaptation, fitting all your needs.

from odf.opendocument import OpenDocumentText
from odf.style import Style, TextProperties
from odf.text import H, P, Span

class DocFactory:

    def __init__(self, filename):
        self.filename = filename
        self.quotStyle = Style(name="Quotations")
        self.marginaliaStyle = Style(name="Marginalia")
        self.doc = OpenDocumentText()

    def add_p1_text(self, txt):
        self.doc.text.addElement(P(text=txt))

    def add_p2_text(self, txt):
        self.doc.text.addElement(P(text=txt, stylename=self.quotStyle))

    def add_p3_text(self, txt):
        self.doc.text.addElement(P(text=txt, stylename=self.marginaliaStyle))

    def save(self):
        self.doc.save(self.filename)
Enter fullscreen mode Exit fullscreen mode

Conclusion

Once again I understood, having Python in your toolset you are always just few lines away from advanced solutions.

Top comments (0)