使用odfpy在Writer(odt)文档中添加行

问题描述 投票:0回答:1

我正在尝试使用odfpy在LibreOffice Writer(odt)文档中插入一条水平线。(在编写器中:菜单->插入->水平线)

这是我的尝试(适应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")

但是出现下一个错误:

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>

我正在学习odfpy,但是文档很少。另外,我尝试在Writer中创建文档,然后读取style.xmlcontent.xml,但看不到相关部分。

python libreoffice odf opendocument
1个回答
0
投票

最后我解决了。仅用一条水平线读取LO Writer生成的* .odt文件的style.xml文件,就可以做到这一点。也许会有更好的方法来弄清楚,但我找不到它。

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)
© www.soinside.com 2019 - 2024. All rights reserved.