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

前端 未结 4 1173
一生所求
一生所求 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?']
    
    0 讨论(0)
  • 2020-12-03 08:46

    well, I don't know if this will apply to you but here is what I've done to set an image in a specific spot to a docx document: I created a base docx document (template document). In this file, I've inserted some tables without borders, to be used as placeholders for images. When creating the document, first I open the template, and update the file creating the images inside the tables. So the code itself is not much different from your original code, the only difference is that I'm creating the paragraph and image inside a specific table.

    from docx import Document
    from docx.shared import Inches
    
    doc = Document('addImage.docx')
    tables = doc.tables
    p = tables[0].rows[0].cells[0].add_paragraph()
    r = p.add_run()
    r.add_picture('resized.png',width=Inches(4.0), height=Inches(.7))
    p = tables[1].rows[0].cells[0].add_paragraph()
    r = p.add_run()
    r.add_picture('teste.png',width=Inches(4.0), height=Inches(.7))
    doc.save('addImage.docx')
    
    0 讨论(0)
  • 2020-12-03 08:49

    Quoting the python-docx documentation:

    The Document.add_picture() method adds a specified picture to the end of the document in a paragraph of its own. However, by digging a little deeper into the API you can place text on either side of the picture in its paragraph, or both.

    When we "dig a little deeper", we discover the Run.add_picture() API.

    Here is an example of its use:

    from docx import Document
    from docx.shared import Inches
    
    document = Document()
    
    p = document.add_paragraph()
    r = p.add_run()
    r.add_text('Good Morning every body,This is my ')
    r.add_picture('/tmp/foo.jpg')
    r.add_text(' do you like it?')
    
    document.save('demo.docx')
    
    0 讨论(0)
  • 2020-12-03 08:53

    Here's my solution. It has the advantage on the first proposition that it surrounds the picture with a title (with style Header 1) and a section for additional comments. Note that you have to do the insertions in the reverse order they appear in the Word document.

    This snippet is particularly useful if you want to programmatically insert pictures in an existing document.

    from docx import Document
    from docx.shared import Inches
    
    # ------- initial code -------
    
    document = Document()
    
    p = document.add_paragraph()
    r = p.add_run()
    r.add_text('Good Morning every body,This is my ')
    picPath = 'D:/Development/Python/aa.png'
    r.add_picture(picPath)
    r.add_text(' do you like it?')
    
    document.save('demo.docx')
    
    # ------- improved code -------
    
    document = Document()
    
    p = document.add_paragraph('Picture bullet section', 'List Bullet')
    p = p.insert_paragraph_before('')
    r = p.add_run()
    r.add_picture(picPath)
    p = p.insert_paragraph_before('My picture title', 'Heading 1')
    
    document.save('demo_better.docx')
    
    0 讨论(0)
提交回复
热议问题