Python-docx: Is it possible to add a new run to paragraph in a specific place (not at the end)

懵懂的女人 提交于 2019-12-06 16:14:19

There's no API support for this, but it can be readily accomplished at the oxml/lxml level:

from docx.text.run import Run
from docx.oxml.text.run import CT_R
# ...
for run in p.runs:
    if 'text' in run.text:
        new_run_element = p._element._new_r()
        run._element.addnext(new_run_element)
        new_run = Run(new_run_element, run._parent)
        # ---do things with new_run, e.g.---
        new_run.text = 'Foobar'
        new_run.bold = True

If you want to insert the new run prior to the existing run, use run._element.addprevious(new_run_element). These two are methods on the lxml.etree._Element class which all python-docx elements subclass.
https://lxml.de/api/lxml.etree._Element-class.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!