Add an image in a specific position in the document (.docx) with Python?

前端 未结 4 1191
一生所求
一生所求 2020-12-03 08:30

I use Python-docx to generate Microsoft Word document.The user want that when he write for eg: \"Good Morning every body,This is my %(profile_img)s do you like it?\" in a HT

4条回答
  •  暖寄归人
    2020-12-03 08:45

    This is adopting the answer written by Robᵩ while considering more flexible input from user. My assumption is that the HTML field mentioned by Kais Dkhili (orignal enquirer) is already loaded in docx.Document(). So...

    Identify where is the related HTML text in the document.

    import re 
    ## regex module
    
    img_tag = re.compile(r'%\(profile_img\)s') # declare pattern
    
    for _p in enumerate(document.paragraphs): 
        if bool(img_tag.match(_p.text)): 
            
            img_paragraph = _p 
            # if and only if; suggesting img_paragraph a list and 
            # use append method instead for full document search 
            
            break # lose the break if want full document search
    

    Replace desired image into placeholder identified as img_tag = '%(profile_img)s'

    The following code is after considering the text contains only a single run May be changed accordingly if condition otherwise

    temp_text = img_tag.split(img_paragraph.text)
    
    img_paragraph.runs[0].text = temp_text[0] 
    
    _r = img_paragraph.add_run()
    _r.add_picture('profile_img.png', width = Inches(1.25))
    
    img_paragraph.add_run(temp_text[1])
    

    and done. document.save() it if finalised.

    In case you are wondering what to expect from the temp_text...

    [In]

    img_tag.split(img_paragraph.text)
    

    [Out]

    ['This is my ', ' do you like it?']
    

提交回复
热议问题