在文档 (.docx) 的特定位置添加图像? [英] Add an image in a specific position in the document (.docx)?

查看:52
本文介绍了在文档 (.docx) 的特定位置添加图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Python-docx 生成 Microsoft Word 文档.用户在为例如:大家早上好,这是我的 %(profile_img)s 你喜欢它吗?"的时候想要这样.在 HTML 字段中,我创建了一个 Word 文档,并从数据库中恢复了用户的图片,并将关键字 %(profile_img)s 替换为用户的图片不在文档末尾强>.使用 Python-docx,我们使用此指令添加图片:

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 HTML field, i create a word document and i recuper the picture of the user from the database and i replace the key word %(profile_img)s by the picture of the user NOT at the END OF THE DOCUMENT. With Python-docx we use this instruction to add a picture:

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

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

The picture is added to the document but the problem that it is added at the end of the document. Is it impossible to add a picture in a specific position in a microsoft word document with python? I've not found any answers to this in the net but have seen people asking the same elsewhere with no solution.

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

Thanks (note: I'm not a hugely experiance programmer and other than this awkward part the rest of my code will very basic)

推荐答案

引用 python-docx 文档:

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

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.

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

When we "dig a little deeper", we discover the 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')

这篇关于在文档 (.docx) 的特定位置添加图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆