Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python-docx: Insert a paragraph after

In python-docx, the paragraph object has a method insert_paragraph_before that allows inserting text before itself:

p.insert_paragraph_before("This is a text")

There is no insert_paragraph_after method, but I suppose that a paragraph object knows sufficiently about itself to determine which paragraph is next in the list. Unfortunately, the inner workings of the python-docx AST are a little intricate (and not really documented).

I wonder how to program a function with the following spec?

def insert_paragraph_after(para, text):
like image 306
fralau Avatar asked Jul 20 '26 17:07

fralau


2 Answers

Trying to make sense of the inner workings of docx made me dizzy, but fortunately, it's easy enough to accomplish what you want, since the internal object already has the necessairy method addnext, which is all we need:

from docx import Document

from docx.text.paragraph import Paragraph
from docx.oxml.xmlchemy import OxmlElement

def insert_paragraph_after(paragraph, text=None, style=None):
    """Insert a new paragraph after the given paragraph."""
    new_p = OxmlElement("w:p")
    paragraph._p.addnext(new_p)
    new_para = Paragraph(new_p, paragraph._parent)
    if text:
        new_para.add_run(text)
    if style is not None:
        new_para.style = style
    return new_para

def main():
    # Create a minimal document
    document = Document()
    p1 = document.add_paragraph("First Paragraph.")
    p2 = document.add_paragraph("Second Paragraph.")

    # Insert a paragraph wedged between p1 and p2
    insert_paragraph_after(p1, "Paragraph One And A Half.")

    # Test if the function succeeded
    document.save(r"D:\somepath\docx_para_after.docx")

if __name__ == "__main__":
    main()
like image 119
Jan Avatar answered Jul 23 '26 05:07

Jan


Please refer below details:

para1 = document.add_paragraph("Hello World")
para2 = document.add_paragraph("Testing!!")

p1 = para1._p
p1.addnext(para2._p)

Reference

like image 20
ANK Avatar answered Jul 23 '26 07:07

ANK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!