Add line in Writer (odt) document using odfpy

1k views Asked by At

I am trying to insert an horizontal line in a LibreOffice Writer (odt) document using odfpy. (In Writer: Menu->Insert->Horizontal line)

This is my attempt (adapting this example):

from odf import opendocument, chart, text, draw

drawdoc = opendocument.OpenDocumentDrawing() # Create the subdocument
maindoc = opendocument.OpenDocumentText() # Create the main document
dl = draw.Line(x1="1pt", x2="1pt", y1="100pt", y2="100pt",  anchortype="paragraph")
maindoc.text.addElement(dl)
objectloc = maindoc.addObject(drawdoc)
do = draw.Object(href=objectloc)
dl.addElement(do)
maindoc.save("horizontalline.odt")

But I get the next error:

Traceback (most recent call last):
  File "pagebreak.py", line 9, in <module>
    dl.addElement(do)
  File "/usr/local/lib/python3.6/dist-packages/odf/element.py", line 427, in addElement
    raise IllegalChild( "<%s> is not allowed in <%s>" % ( element.tagName, self.tagName))
odf.element.IllegalChild: <draw:object> is not allowed in <draw:line>

I'm learning odfpy but there are few documentation. Also I have try to create the document in Writer, and after that read the style.xml and content.xml but I'm unable to see the related parts.

2

There are 2 answers

0
exodehm On

Finally I solved. Reading the style.xml file of a *.odt file generated by LO Writer with only a horizontal line, I have been able to do it. Probably there'll be a better way to figure out, but I can't fount it.

textFile = OpenDocumentText()
horizontal_line = Style(name="Horizontal_20_Line", displayname="Horizontal Line", family="paragraph", parentstylename="Standard", nextstylename="Text_20_body")
horizontal_line.addElement(ParagraphProperties(margintop="0cm", marginbottom="0.499cm", contextualspacing="false", borderlinewidthbottom="0cm 0.010cm 0.08cm", padding="0cm", borderleft="none", borderright="none", bordertop="none", borderbottom="0.06pt double #574644", numberlines="false", linenumber="0", joinborder="false"))
horizontal_line.addElement(TextProperties(fontfamily="arial", fontsize="12pt", fontsizeasian="6pt", fontsizecomplex="6pt"))
textFile.styles.addElement(horizontal_line)
parrafo = P(text="THIS IS AN HORIZONTAL LINE", stylename=horizontal_line)
textFile.text.addElement(parrafo)
0
Umbral Reaper On

You can draw a horizontal line by simply adding a Line to textdoc.text.

from odf.opendocument import OpenDocumentText
from odf.draw import Line

textdoc = OpenDocumentText()
line = Line(x1="1pt", x2="100pt", y1="100pt", y2="100pt")
textdoc.text.addElement(line)