python-docx不添加图片

时间:2018-03-23 09:05:51

标签: python python-docx

我尝试使用python-docx将图片插入Word文档但遇到错误。

代码很简单:

document.add_picture("test.jpg", width = Cm(2.0))

通过查看python-docx文档,我可以看到应该生成以下XML:

<pic:pic xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture">
  <pic:nvPicPr>
    <pic:cNvPr id="1" name="python-powered.png"/>
    <pic:cNvPicPr/>
  </pic:nvPicPr>
  <pic:blipFill>
    <a:blip r:embed="rId7"/>
    <a:stretch>
      <a:fillRect/>
    </a:stretch>
  </pic:blipFill>
  <pic:spPr>
    <a:xfrm>
      <a:off x="0" y="0"/>
      <a:ext cx="859536" cy="343814"/>
    </a:xfrm>
    <a:prstGeom prst="rect"/>
  </pic:spPr>
</pic:pic>

这实际上是在我的document.xml文件中生成的。 (解压缩docx文件时)。然而,在查看OOXML格式时,我可以看到图像也应该保存在 media 文件夹下,并且关系应该映射到 word / _rels / document.xml: < / p>

<Relationship Id="rId20"
Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image"
Target="media/image20.png"/>

然而,这一切都没有发生,当我打开Word文档时,我遇到了一个&#34;图片无法显示&#34;占位符。

任何人都可以帮我理解发生了什么吗?

看起来图像没有以它应该的方式嵌入,我需要将其插入媒体文件夹并为其添加映射,但是作为一个记录良好的功能,此应该正在工作如预期的那样。

更新:

使用空的docx文件测试它,图像确实按预期添加,这让我相信它可能与python-docx-template库有关。 (https://github.com/elapouya/python-docx-template

它使用python-docx和jinja来提供模板功能,但运行和工作方式与python-docx 相同。我将图像添加到一个子文件中,然后将其插入到给定位置的完整文档中。

下面的示例代码(来自https://github.com/elapouya/python-docx-template/blob/master/tests/subdoc.py):

from docxtpl import DocxTemplate
from docx.shared import Inches

tpl=DocxTemplate('test_files/subdoc_tpl.docx')

sd = tpl.new_subdoc()
sd.add_paragraph('A picture :')
sd.add_picture('test_files/python_logo.png', width=Inches(1.25))

context = {
    'mysubdoc' : sd,
}

tpl.render(context)
tpl.save('test_files/subdoc.docx')

3 个答案:

答案 0 :(得分:1)

I'll keep this up in case anyone else manages to make the same mistake as I did :) I managed to debug it in the end.

The problem was in how I used the python-docx-template library. I opened up a DocxTemplate like so:

    report_output = DocxTemplate(template_path)
    DoThings(value,template_path)
    report_output.render(dictionary)
    report_output.save(output_path)

But I accidentally opened it up twice. Instead of passing the template to a function, when working with it, I passed a path to it and opened it again when creating subdocs and building them.

def DoThings(data,template_path):
    doc = DocxTemplate(template_path)
    temp_finding = doc.new_subdoc()
    #DO THINGS

Finally after I had the subdocs built, I rendered the first template which seemed to work fine for paragraphs and such but I'm guessing the images were added to the "second" opened template and not to the first one that I was actually rendering. After passing the template to the function it started working as expected!

答案 1 :(得分:1)

我遇到了这个问题,并在方法add_picture中删除了参数width =(1.0)后解决了该问题。

enter image description here

添加参数width =(1.0)时,在test.docx中看不到图片

因此,可能是由于图片尺寸设置不正确造成的,

答案 2 :(得分:0)

在现有文档中添加图片,标题,段落:

doc = Document(full_path) # open an existing document with existing styles
for row in tableData:   # list from the json api ... 
    print ('row {}'.format(row))
    level = row['level']
    levelStyle = 'Heading ' + str(level)
    title = row['title']
    heading = doc.add_heading( title , level)
    heading.style = doc.styles[levelStyle]
    p = doc.add_paragraph(row['description'])
    if row['img_http_path']:
        ip = doc.add_paragraph()
        r = ip.add_run()
        r.add_text(row['img_name'])
        r.add_text("\n")
        r.add_picture(row['img_http_path'], width = Cm(15.0))

doc.save(full_path)