Search code examples
pythondocxpython-docx

Python docx Replacer keeping style


I can’t figure out how to save the Word style settings when replacing text (font, boldness, etc.). Reviewed similar articles - did not help I am using the library: docx-python

Git(code + word docx): https://github.com/AlpacaHD/test.git

I tried this, but it didn't help much.

# style = Document.styles\['Normal'\]
# font = style.font
# font.name = 'Times New Roman'

I need to somehow "drive" the code with the fonts, but I can't figure out how.


Solution

  • You'll need to work at the Run level:

    Assigning text to [Run.text] ... Any existing run content is replaced. Run formatting is preserved.

    https://python-docx.readthedocs.io/en/latest/api/text.html#docx.text.run.Run.text

    Assigning text to [Paragraph.text] causes all existing paragraph content to be replaced with a single run containing the assigned text... Paragraph-level formatting, such as style, is preserved. All run-level formatting, such as bold or italic, is removed.

    https://python-docx.readthedocs.io/en/latest/api/text.html#docx.text.paragraph.Paragraph.text

    def find_replace(paragraph_keyword, draft_keyword, paragraph):
        if paragraph_keyword in paragraph.text:
            for run in paragraph.runs:
                if paragraph_keyword in run.text:
                    run.text = run.text.replace(paragraph_keyword, draft_keyword)