使用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
    ```

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...