【问题标题】:Add an image in a specific position in the document (.docx)?在文档 (.docx) 的特定位置添加图像?
【发布时间】:2016-01-01 03:26:21
【问题描述】:

我使用 Python-docx 生成 Microsoft Word 文档。用户希望在他写例如:“大家早上好,这是我的 %(profile_img)s 你喜欢吗?” 在 HTML 字段中,我创建了一个 word 文档,并从数据库中恢复了用户的图片,并将关键字 %(profile_img)s 替换为用户的图片不在文档末尾强>。使用 Python-docx 我们使用这条指令来添加图片:

document.add_picture('profile_img.png', width=Inches(1.25))

图片添加到文档中,但是添加到文档末尾的问题。 用python不能在microsoft word文档的特定位置添加图片吗?我在网上没有找到任何答案,但看到有人在其他地方提出同样的问题,但没有解决方案。

谢谢(注意:我不是一个经验丰富的程序员,除了这个尴尬的部分之外,我的其余代码将非常基本)

【问题讨论】:

  • 如果先将剩下的部分文本添加到关键短语中,然后添加图像,然后添加其余文本呢?你试过这个吗?
  • 您好 Lenz,是的,我已经尝试过了,但结果是第一行中的文字“大家早上好,这是我的”,第二行中的文字是“你喜欢吗”和图片在文档末尾

标签: python image python-2.7 python-docx


【解决方案1】:

引用the python-docx documentation:

Document.add_picture() 方法将指定图片添加到文档末尾的段落中。但是,通过更深入地研究 API,您可以将文本放置在段落中图片的任一侧,或两者兼而有之。

当我们“深入挖掘”时,我们会发现 Run.add_picture() API。

以下是它的使用示例:

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')

【讨论】:

【解决方案2】:

好吧,我不知道这是否适用于您,但这是我为将特定位置的图像设置为 docx 文档所做的工作: 我创建了一个基础 docx 文档(模板文档)。在这个文件中,我插入了一些没有边框的表格,用作图像的占位符。创建文档时,首先我打开模板,然后更新在表格中创建图像的文件。因此代码本身与您的原始代码并没有太大区别,唯一的区别是我在特定表格中创建段落和图像。

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')

【讨论】:

  • 对于以厘米为单位的工作,只需将上面的 Inches 类替换为 Cm 类!
【解决方案3】:

这是我的解决方案。它在第一个命题上的优势在于,它用标题(样式 Header 1)和用于附加 cmets 的部分围绕图片。请注意,您必须按照它们在 Word 文档中出现的相反顺序进行插入。

如果您想以编程方式在现有文档中插入图片,此 sn-p 特别有用。

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')

【讨论】:

    【解决方案4】:

    这是采用 Robᵩ 写的答案,同时考虑到用户更灵活的输入。 我的假设是 Kais Dkhili(原始查询者)提到的 HTML 字段已经加载到 docx.Document() 中。所以...

    确定文档中相关 HTML 文本的位置。

    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
    

    将所需图像替换为标识为img_tag = '%(profile_img)s' 的占位符

    下面的代码是在考虑文本只包含一个run之后 如果条件不同,可能会相应更改

    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])
    

    然后完成。 document.save() 如果最终确定。

    如果您想知道temp_text 会发生什么...

    [In]

    img_tag.split(img_paragraph.text)
    

    [Out]

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

    【讨论】:

      【解决方案5】:

      我花了几个小时在里面。如果您需要使用 python 将图像添加到模板 doc 文件中,最好的解决方案是使用 python-docx-template 库。 文档可用here here中提供的示例

      【讨论】:

        【解决方案6】:

        这是一个主题的变体。让 I 成为特定文档中的段落号:

        p = doc.paragraphs[I].insert_paragraph_before('\n')
        p.add_run().add_picture('Fig01.png', width=Cm(15))
        

        【讨论】:

          【解决方案7】:

          在文档的特定位置添加图片

          from docx import Document
          from docx.shared import Inches
          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')
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2022-11-10
            • 1970-01-01
            • 2018-06-09
            • 1970-01-01
            • 2012-09-22
            • 1970-01-01
            相关资源
            最近更新 更多