Skip to content

Enable copying of a run's font #1308

Open
@luissantosHCIT

Description

@luissantosHCIT

Hello,

I am new to this project and have been enjoying the work done.
For my own project, I replace some text fields with specific values.
Unfortunately, I noticed that the formatting gets lost when using the Paragraph::text property.
For example,
image
becomes
image

Inspection of the XML output revealed that the run's embedded font information gets lost.
image

Finally, I found this comment in the source code for the Paragraph class
image

Looking deeper, I see why the call to clear() was needed.
In my testing, I can see how Word can sometimes split text over multiple runs.

As a result, I resorted to logic like so in my program in order to recover the font information.


if len(p.runs):
            old_run = p.runs[0]
            p.text = p.text.replace(str(key), str(value))
            new_run = p.runs[0]
            new_run.italic = old_run.italic
            new_run.bold = old_run.bold
            new_run.underline = old_run.underline
            new_run.font = old_run.font
            new_run.style = old_run.style
        else:
            p.text = p.text.replace(str(key), str(value))

The one issue is that new_run.font = old_run.font was returning an error.

I went ahead and added the missing font.setter and color.setter to the respective properties in run.py and font.py.
I am going to open a pull request to associate with this issue.

Ideally, I can retain the formatting of one of the runs when changing the text via an instance of Paragraph. Since I understand this is tricky and probably not worth the time, I think enabling the ability to copy the font formatting from a run to another would be helpful for those who are assuming 1 formatting to one block of text (meaning, even if Word splits the text into multiple runs, all runs have the same formatting). I think this is a good compromise for me at this time.

Let me know what you think, how I can be of assistance, or how I can adjust my solution in #1309 to better match expectations for this project.

Thank you for your excellent work!

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