python-docx不添加图片

python-docx does not add picture

我正在尝试使用 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:

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

None 但是,当我打开 Word 文档时,我遇到了一个 "The picture can't be displayed" 占位符。

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

看起来图像没有按照应有的方式嵌入,我需要将它插入媒体文件夹并为其添加映射,但是作为一个有据可查的功能,这个 应该 按预期工作。

更新:

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

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

示例代码如下(来自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')

我会坚持下去,以防其他人犯下和我一样的错误:) 最后我设法调试了它。

问题在于我如何使用 python-docx-template 库。我像这样打开了一个 DocxTemplate:

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

但是我不小心打开了两次。在使用它时,我没有将模板传递给函数,而是传递了一个路径并在创建子文档和构建它们时再次打开它。

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

最后,在我构建了子文档之后,我渲染了第一个模板,它似乎适用于段落等,但我猜这些图像是添加到 "second" 打开的模板而不是第一个我实际上正在渲染的一个。将模板传递给函数后,它开始按预期工作!

向现有文档添加图片、标题、段落:

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)

我遇到了这个问题,去掉方法add_picture中的参数width=(1.0)就解决了。

添加参数width=(1.0)后,我在test.docx

中看不到图片

所以,这可能是由于为图片设置了不合适的尺寸造成的,