问题描述
我想用 odfpy 生成一个 odf 文件,但被困在下划线文本上。 这是一个受官方文档启发的最小示例,我找不到有关可以使用哪些属性以及在哪里使用的任何信息。 有什么建议吗?
from odf.opendocument import opendocumentText
from odf.style import Style,TextProperties
from odf.text import H,P,Span
textdoc = opendocumentText()
ustyle = Style(name="Underline",family="text")
#uprop = TextProperties(fontweight="bold") #uncommented,this works well
#uprop = TextProperties(attributes={"fontsize":"26pt"}) #this either
uprop = TextProperties(attributes={"underline":"solid"}) # bad guess,wont work !!
ustyle.addElement(uprop)
textdoc.automaticstyles.addElement(ustyle)
p = P(text="Hello world. ")
underlinedpart = Span(stylename=ustyle,text="This part would like to be underlined. ")
p.addElement(underlinedpart)
p.addText("This is after the style test.")
textdoc.text.addElement(p)
textdoc.save("myfirstdocument.odt")
解决方法
这是我最终得到它的方式:
我使用 libreoffice 创建了一个带下划线的示例文档,并将其解压缩。查看提取文件的styles.xml部分,我得到了在文档中加下划线的部分:
<style:style style:name="Internet_20_link" style:display-name="Internet link" style:family="text">
<style:text-properties fo:color="#000080" fo:language="zxx" fo:country="none" style:text-underline-style="solid" style:text-underline-width="auto" style:text-underline-color="font-color" style:language-asian="zxx" style:country-asian="none" style:language-complex="zxx" style:country-complex="none"/>
</style:style>
有趣的样式属性命名为:text-underline-style, 文本下划线宽度和文本下划线颜色。
要在 odfpy 中使用它们,必须删除“-”字符,并且必须将属性键用作 str(带引号),如下面的代码所示。必须在 Style 构造函数调用中指定正确的样式系列(在我们的示例中为文本)。
from odf.opendocument import OpenDocumentText
from odf.style import Style,TextProperties
from odf.text import H,P,Span
textdoc = OpenDocumentText()
#underline style
ustyle = Style(name="Underline",family="text") #here style family
uprop = TextProperties(attributes={
"textunderlinestyle":"solid","textunderlinewidth":"auto","textunderlinecolor":"font-color"
})
ustyle.addElement(uprop)
textdoc.automaticstyles.addElement(ustyle)
p = P(text="Hello world. ")
underlinedpart = Span(stylename=ustyle,text="This part would like to be underlined. ")
p.addElement(underlinedpart)
p.addText("This is after the style test.")
textdoc.text.addElement(p)
textdoc.save("myfirstdocument.odt")