Search code examples
pythonms-wordpython-docxparagraph

How can I add a new paragraph at the end of a word document?


I would like to add a last paragraph after everything in the word doc that I have. I tried using this code, but the text is appended before my last table.

How can I make sure the text is always appended at the very end?

from docx import Document
document = Document('Summary_output.docx')
paragraphs = document.paragraphs

#Store content of second paragraph
text = paragraphs[1].text

#Clear content
paragraphs[1]._p.clear()

#Recreate second paragraph
paragraphs[1].add_run('Appended part ' + text)
document.save("Summary_output.docx")

Solution

  • Short answer: use document.add_paragraph().

    new_last_paragraph = document.add_paragraph("Appended part %s" % text)
    

    It's important to understand the distinction in Word between paragraphs and runs. A paragraph is a "block" item (as is a table). A block item fits between the margins, is vertically entirely below the prior block item and entirely above the following block item. Intuitively, it is a full-width block in the stack of full-width blocks appearing in the "column" bounded on each side by the margins.

    A run is an inline item, a sequence of characters that all share the same character formatting. A run always appears within a paragraph and in general a paragraph contains multiple runs. Using runs is how you make, for example, a single word bold or a phrase within a paragraph italic or red. Runs are flowed within the paragraph by line-wrapping.

    So in your code, you were just extending an existing paragraph (by adding a run) rather than creating a new one, which explains why its position did not change.