如何解决使用python-docx将QTextDocument保存到docx
是否已经有一个库通过QTextDocument中的QTextBlocks进行了解析,并将其转换为对python-docx的add_paragaph和add_run调用。我想将在QTextDocuemnt中创建的用户的代码片段保存到我的docx输出中,似乎这已经有人完成了。也许是我找不到的python-docx的功能?
解决方法
这是我写的一个穷人解析器。它虽然不漂亮,但我认为如果您要编写一个更完整和更强大的版本,它会显示出原理
@staticmethod
def convertDocument(docx:Document,qtd: QTextDocument) -> Document:
retVal = Document()
block = qtd.begin()
while block is not None:
Convert.convertBlock(docx,block)
if block == qtd.end():
block = None
else:
block = block.next()
return retVal
@staticmethod
def convertBlock(docx:Document,block: QTextBlock):
textlist = block.textList()
style = None
indent = False
if textlist is not None:
listformat = textlist.format()
bulletTypes = [QTextListFormat.ListDisc,QTextListFormat.ListCircle,QTextListFormat.ListSquare]
if listformat.style() in bulletTypes:
style = 'List Bullet'
else:
style = 'List Number'
indent = True
p = docx.add_paragraph("",style)
text = block.text()
for frange in block.textFormats():
r = p.add_run(text[frange.start:(frange.start+frange.length)])
if frange.format.hasProperty(QTextFormat.FontPointSize):
r.font.size = Pt(frange.format.doubleProperty(QTextFormat.FontPointSize))
if frange.format.hasProperty(QTextFormat.FontWeight):
weight = frange.format.intProperty(QTextFormat.FontWeight)
if weight > 50:
r.font.bold = True
if indent:
p.paragraph_format.left_indent = Inches(0.70)
return p
```
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。