Search code examples
pythonpython-docx

How to insert a title after a paragraph using python-docx


I am trying to insert a title after a paragraph using python-docx. To do so, I have this first function that allows me to insert any element after a paragraph :

def insert_element_after_paragraph(element, paragraph):
    p = paragraph._p
    p.addnext(element)

And then using this function I am trying to insert a title :

paraIndex = 20   #Position of my paragraph
personPara = document.add_heading(f"Title {i+1} :", 2)
personHeadungPara = insert_element_after_paragraph(personPara._p, document.paragraphs[paraIndex])

But by doing this, it will not add a title but a paragraph.

So how can I correct this to have a title inserted and not a paragraph ?


Solution

  • so what happens when you call: personPara = document.add_heading(f"Title {i+1} :", 2) is that a new heading will be added to the bottom of the document storing the reference to it. in your case, you don't want to add the new heading to the bottom of the document, but rather to insert it at the given position.

    import docx
    
    doc = docx.Document()
    
    h1 = doc.add_heading('Test heading 1')
    p1 = doc.add_paragraph('text of para 1')
    p2 = doc.add_paragraph('text of para 2')
    
    p2.insert_paragraph_before(text='Test heading 2', style='Heading 1')
    
    doc.save('test.docx')
    

    So how can I correct this to have a title inserted and not a paragraph?

    note that title is actually a paragraph with a Heading style applied to it.

    word preview after inserted heading title