使用 Python 在文档 (.docx) 中的特定位置添加图像?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32932230/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add an image in a specific position in the document (.docx) with Python?
提问by Kais Dkhili
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:
我使用 Python-docx 生成 Microsoft Word 文档。用户在他写的时候想要这样:“大家早上好,这是我的 %(profile_img)s,你喜欢吗?” 在一个HTML字段,我创建一个Word文档,我recuper用户的图片从数据库和i。由所述用户的图片替换键字%(profile_img)■不能在文件的结尾。在 Python-docx 中,我们使用此指令添加图片:
document.add_picture('profile_img.png', width=Inches(1.25))
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.
图片添加到文档中,但问题是添加在文档末尾。用python在microsoft word文档中的特定位置添加图片是不可能的吗?我没有在网上找到任何答案,但看到人们在其他地方问同样的问题而没有解决方案。
Thanks (note: I'm not a hugely experiance programmer and other than this awkward part the rest of my code will very basic)
谢谢(注意:我不是一个非常有经验的程序员,除了这个尴尬的部分,我的其余代码将非常基本)
采纳答案by Rob?
Quoting the python-docx documentation:
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.
Document.add_picture() 方法将指定图片添加到文档末尾的一个段落中。但是,通过更深入地研究 API,您可以将文本放置在段落中图片的任一侧,或两者兼而有之。
When we "dig a little deeper", we discover the Run.add_picture()
API.
当我们“深入挖掘”时,我们会发现Run.add_picture()
API。
Here is an example of its use:
以下是它的使用示例:
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')
回答by Wand
well, I don't know if this will apply to you but here is what I've done to set an image in a specific spot to a docx document: I created a base docx document (template document). In this file, I've inserted some tables without borders, to be used as placeholders for images. When creating the document, first I open the template, and update the file creating the images inside the tables. So the code itself is not much different from your original code, the only difference is that I'm creating the paragraph and image inside a specific table.
好吧,我不知道这是否适用于您,但这是我在特定位置将图像设置为 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')
回答by Jean-Pierre Schnyder
Here's my solution. It has the advantage on the first proposition that it surrounds the picture with a title (with style Header 1) and a section for additional comments. Note that you have to do the insertions in the reverse order they appear in the Word document.
这是我的解决方案。它在第一个命题上的优势在于它用标题(带有样式 Header 1)和一个用于附加注释的部分围绕图片。请注意,您必须按照它们在 Word 文档中出现的相反顺序进行插入。
This snippet is particularly useful if you want to programmatically insert pictures in an existing document.
如果您想以编程方式在现有文档中插入图片,此代码段特别有用。
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')
回答by Siddhartha Mukherjee
You Can use this:
你可以使用这个:
document.add_picture(settings.MEDIA_ROOT+'/image/cta-header3-min.png', width=Inches(5.8))
settings.MEDIA_ROOTFile location path
settings.MEDIA_ROOT文件位置路径
回答by Azhar
This is adopting the answer written by Rob?while considering more flexible input from user.
My assumption is that the HTML field mentioned by Kais Dkhili(orignal enquirer) is already loaded in docx.Document()
. So...
这是采用Rob写的答案?同时考虑更灵活的用户输入。我的假设是Kais Dkhili(原始询问者)提到的 HTML 字段已经加载到docx.Document()
. 所以...
Identify where is the related HTML text in the 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
Replace desired image into placeholder identified as img_tag = '%(profile_img)s'
将所需图像替换为标识为的占位符 img_tag = '%(profile_img)s'
The following code is after considering the text contains only a single run
May be changed accordingly if condition otherwise
以下代码是在考虑文本仅包含单个之后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])
and done. document.save()
it if finalised.
并做了。document.save()
如果最终确定。
In case you are wondering what to expect from the temp_text
...
如果您想知道从temp_text
...
[In]
[In]
img_tag.split(img_paragraph.text)
[Out]
[Out]
['This is my ', ' do you like it?']