pythondocx不添加pictu

2024-06-26 14:32:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用pythondocx将图片插入Word文档,但遇到了错误。在

代码很简单:

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

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

^{pr2}$

这实际上是在我的文档.xml文件。(解压缩docx文件时)。然而,查看OOXML格式,我可以看到图像也应该保存在媒体文件夹下,并且关系应该映射到word/\u rels中/文档.xml:

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

然而,这一切都不会发生,当我打开Word文档时,会遇到一个“图片无法显示”占位符。在

有谁能帮我弄清楚发生了什么事吗?在

图像似乎没有按应有的方式嵌入,我需要将其插入媒体文件夹并添加映射,但是作为一项有良好文档记录的功能,此应该按预期工作。在

更新:

用一个空的docx文件进行测试,该文件确实如预期的那样添加了图像,这使我相信它可能与pythondocx模板库有关。(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')

Tags: 文件文档test图像add方式图片files
2条回答

我会继续这样做,以防有人和我一样犯同样的错误:)我最终成功地调试了它。在

问题在于我如何使用pythondocx模板库。我打开了一个DocxTemplate,如下所示:

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

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

^{pr2}$

最后,在我构建了子文档之后,我渲染了第一个模板,它似乎可以很好地处理段落之类的内容,但我猜图像是添加到“第二个”打开的模板中的,而不是添加到我实际渲染的第一个模板中。在将模板传递给函数后,它开始按预期工作!在

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

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)

相关问题 更多 >