问题描述
是否已经有一个库通过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
```