odfpy:设置页面参数

时间:2018-07-08 11:20:39

标签: python odt opendocument odfpy

我正在使用odfpy使用Python生成OpenDocument文本文件。

LibreOffice之类的程序让我设置页面参数(高度,宽度,页边空白数)。我还可以创建几种样式,并将不同的页面设置为具有不同的样式(有些包含一列,另一些包含两列等等)。

我无法从odfpy中弄清楚该如何做。该文档不完整,因此,这是我在尝试并引用this blog post(约Draw个文件,而非Text)后想到的:

from odf.opendocument import OpenDocumentText
from odf.style import (
    Style,
    TextProperties,
    ParagraphProperties,
    MasterPage,
    PageLayout,
    PageLayoutProperties,
)
from odf.text import (
    H,
    P,
    Span,
    Page,
)

doc = OpenDocumentText()

# Styles
s = doc.styles
h1style = Style(name="Heading 1", family="paragraph")
h1style.addElement(TextProperties(attributes={'fontsize':"24pt", 'fontweight':"bold" }))
s.addElement(h1style)

# Page style
layout = PageLayout(name="PM1")
layout.addElement(PageLayoutProperties(
    margin="0cm",
    pageheight="100mm",
    pagewidth="260mm",
    printorientation="portrait"))
doc.automaticstyles.addElement(layout)

masterpage = MasterPage(name='Default',
    pagelayoutname=layout)
doc.masterstyles.addElement(masterpage)

# Page
page1 = Page(masterpagename=masterpage)

# Text
h = H(outlinelevel=1, stylename=h1style, text="Test Page")
doc.text.addElement(h)

p = P(text="I am a paragraph")
doc.text.addElement(p)    

if __name__ == "__main__":
    doc.save("output.odt")

这将创建文档,但没有任何自定义样式。

当我尝试将Page添加到文档中时...

doc.text.addElement(page1)

...。然后我收到此错误:

Traceback (most recent call last):
  File "layout-test.py", line 48, in <module>
    doc.text.addElement(page1)
  File "[...]/lib/python3.6/site-packages/odf/element.py", line 427, in addElement
    raise IllegalChild( "<%s> is not allowed in <%s>" % ( element.tagName, self.tagName))
odf.element.IllegalChild: <text:page> is not allowed in <office:text>

我要去哪里错了?如何添加具有不同自定义样式的页面?

0 个答案:

没有答案
相关问题