Search code examples
pythondocxpython-docx

Copy a paragraph into the same document(python 3.x, docx)


Let's say I have a certain paragraph in my docx document with certain text formatting, for example:
"Foo bar"
I want to make something like a template of this paragraph to copy it into the same document multiple times.
Copying text like in the example means loosing text formatting.

from docx import Document

document = Document('input.docx')
template = document.paragraphs[0]
for x in range(100):
    document.add_paragraph(template.text)
document.save('output.docx')

Is there any generic way to do it with python-docx library?
Other solutions for python and django in particulary are appreciated as well!
Thanks in advance.


Solution

  • In your simple example, you could do something like this:

    def clone_run_props(tmpl_run, this_run):
        this_run.bold = tmpl_run.bold
        ... maybe other possible run properties ...
    
    template_paragraph = ... however you get this ...
    new_paragraph = document.add_paragraph()
    for run in template_paragraph:
        cloned_run = new_paragraph.add_run()
        clone_run_props(run, cloned_run)
        cloned_run.text = ... however you get this ...
    

    This approach will work when the character formatting is directly applied, but not when it's indirectly applied, such as via a character style.