使用odfpy生成ODF文件时如何正确为文本添加下划线
解决方法
你写错了属性名,odfpy的TextProperties中控制下划线的属性为textunderline,还可以搭配textunderlinecolor自定义下划线颜色。
修改后可正常运行的完整代码如下:
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") # 正确配置下划线,可额外指定颜色,比如加textunderlinecolor="#ff0000"就是红色下划线 uprop = TextProperties(textunderline="solid") 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")
属性查找方式
odfpy的样式属性命名规则对应ODF官方规范的属性,把属性名中的命名空间前缀、横杠都去掉,全部小写即可作为参数名:
- ODF规范里的
style:text-underline对应textunderline fo:font-weight对应fontweightfo:font-size对应fontsize
所有支持的属性可以直接查看odfpy安装目录下style.py里TextProperties类的定义,或者参考ODF 1.2规范的文本样式章节。
内容的提问来源于stack exchange,提问作者spacm
相关产品推荐
相关产品推荐

