Skip to content

after text replacement the font name, size and its other associated style like bold, italics are getting changed #410

@vikashvishnu1508

Description

@vikashvishnu1508

I am using python-docx for a automation tool. I have a issue like once after I run the code for replacement of certain words in one list with corresponding in another list it is removing all the properties (like font size, font name, part of a text in bold or italics, bookmarks in the paragraphs or table) of the text in the paragraph and table and its coming with a plain text in "Calibri" with a font size of '12'.

The code that I used is:

wrongWord = "xyz"
correctWord = "abcd"
def iter_block_items(parent):
    if isinstance(parent, _Document):
        parent_elm = parent.element.body
        # print(parent_elm.xml)
    elif isinstance(parent, _Cell):
        parent_elm = parent._tc
    else:
        raise ValueError("something's not right")
 
    for child in parent_elm.iterchildren():
        if isinstance(child, CT_P):
            yield Paragraph(child, parent)
        elif isinstance(child, CT_Tbl):
            yield Table(child, parent)
 
document = Document(r"F:\python\documentSample.docx")
for block in iter_block_items(document):
    if isinstance(block, Paragraph):
        if wrongWord in block.text:
            block.text = block.text.replace(wrongWord, correctWord)
    else:
        for row in block.rows:
            for cell in row.cells:
                if wrongWord in cell.text:
                    cell.text = cell.text.replace(wrongWord, correctWord)

document.save(r"F:\python\documentSampleAfterChanges.docx")

Could you help me to get the same font size, font name and other associated properties to be copied from the original file after the text replacement.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions