it编程 > 前端脚本 > Python

Python在Word中进行图片添加、替换和删除操作

7人参与 2025-03-08 Python

通过python编程实现word文档中图片的动态管理,可精准实现图片的插入定位、条件化替换及冗余元素删除,尤其适用于需要定期生成标准化word文档。这种自动化方案不仅显著降低人工操作导致的格式错位、版本混乱等风险,还能通过api接口与数据库、图像处理系统无缝集成,为构建端到端的智能文档生成体系奠定基础。本文将介绍如何使用python在word文档中添加、替换和删除图片。

本文所使用的方法需要用到免费的free spire.doc for python,pypi:pip install spire.doc

用python插入图片到word文档

我们可以通过库中提供的paragraph.appendpicture(string: filename)方法从指定路径插入图片到word文档中的指定段落,并可使用docpicture类下的属性对图像的大小、位置和文字环绕方式等进行设置。以下是操作步骤:

1.导入所需模块。

2.创建document对象,从而新建word文档。

3.使用document.addsection()方法在文档中添加节,并设置格式。

4.使用section.addparagraph()方法在节中添加段落,使用paragraph.appendtext()方法在段落中添加文本,并设置格式。

5.使用paragraph.appendpicture()方法在段落中添加图片。

6.使用docpicture类下的属性设置图片属性:

7.使用document.savetofile()方法保存文档。

8.释放资源。

代码示例:

from spire.doc import document, textwrappingstyle, fileformat

# 创建document对象,从而新建word文档
doc = document()

# 在文档中添加一个节,并设置页边距
section = doc.addsection()
section.pagesetup.margins.all = 72

# 在节中添加段落,在段落中添加文本
para = section.addparagraph()
textrange = para.appendtext("document introduction")
textrange.characterformat.fontname = "arial"
textrange.characterformat.fontsize = 16
textrange.characterformat.bold = true

# 添加段落,并添加图片到段落中
para1 = section.addparagraph()
pic = para1.appendpicture("word.png")

# 设置图片尺寸
pic.width = 64
pic.height = 64

# 设置图片位置(可选)
pic.horizontalposition = 360
pic.verticalposition = 10

# 设置图片文本环绕方式
pic.textwrappingstyle = textwrappingstyle.square

# 添加文本并设置格式
textrange2 = para1.appendtext("this document serves as a structured repository of critical information, designed to facilitate clear communication, collaborative workflows, and long-term knowledge retention. its architecture prioritizes accessibility, with a navigable hierarchy of headings, cross-referenced sections, and embedded metadata to streamline information retrieval.")
textrange2.characterformat.fontname = "arial"
textrange2.characterformat.fontsize = 12

# 保存文档
doc.savetofile("output/addpictoword.docx", fileformat.docx2019)
doc.dispose()

结果文档

用python替换word文档中的图片为新的图片

我们可以通过判断段落的各个子对象的documentobjecttype属性是否为documentobjecttype.picture来找出文档中的所有图片。然后,我们可以将图片子对象转换为docpicture,再使用docpicture.loadimage()方法使用指定的图片替换原图片。替换后的图片将保留原图片的位置和文本环绕方式属性,图片大小可设置为原图片的大小。以下是操作步骤:

1.导入所需模块。

2.创建document对象,使用document.loadfromfile()方法载入word文档。

3.依次遍历文档中的节、节中的段落以及段落中的子对象,判断每个子对象的documentobjecttype属性是否为documentobjecttype.picture,将判断成功的对象添加到列表中。

4.将图片子对象转换为docpicture,再使用docpicture.loadimage()方法使用指定的图片替换原图片。

5.使用document.savetofile()方法保存文档。

6.释放资源。

代码示例:

from spire.doc import document, documentobjecttype, docpicture

# 创建document对象
doc = document()

# 加载word文档
doc.loadfromfile("output/addpictoword.docx")

# 创建一个列表来存储图片
pictures = []

# 遍历文档中的所有节
for i in range(doc.sections.count):
    sec = doc.sections.get_item(i)

    # 遍历每一节中的所有段落
    for j in range(sec.paragraphs.count):
        para = sec.paragraphs.get_item(j)

        # 遍历每个段落中的所有子对象
        for k in range(para.childobjects.count):
            docobj = para.childobjects.get_item(k)

            # 查找图片并将其添加到列表中
            if docobj.documentobjecttype == documentobjecttype.picture:
                pictures.append(docobj)

# 用新图片替换列表中的第一张图片
picture = docpicture(pictures[0])
width = picture.width
height = picture.height
picture.loadimage("newword.png")

# 修改图片的尺寸
picture.width = width
picture.height = height

# 保存结果文档
doc.savetofile("output/replacewordimage.docx")
doc.close()

结果文档

用python替换word文档中的图片为文本

我们还可以在找出图片子对象后,使用paragraph.childobjects.insert(index, textrange)方法在其位置插入文本,并使用paragraph.childobjects.remove()方法将图片子对象删除,从而实现图片到文本的替换。以下是操作步骤:

1.导入所需模块。

2.创建document对象,使用document.loadfromfile()方法载入word文档。

3.依次遍历文档中的节、节中的段落以及段落中的子对象,判断每个子对象的documentobjecttype属性是否为documentobjecttype.picture,将判断成功的对象添加到列表中。

4.通过创建textrange对象创建文本,设置文字及其格式。

5.使用paragraph.childobjects.indexof()方法获取图片子对象在段落中的索引。

6.使用paragraph.childobjects.insert()方法将文本插入到段落中相应位置。

7.使用paragraph.childobjects.remove()方法删除图片子对象。

8.使用document.savetofile()方法保存文档。

9.释放资源。

代码示例:

from spire.doc import document, documentobjecttype, textrange, color

# 创建document对象
doc = document()

# 加载word文档
doc.loadfromfile("output/addpictoword.docx")

# 遍历文档中的所有节
for k in range(doc.sections.count):
    sec = doc.sections.get_item(k)

    # 遍历每一节中的所有段落
    for m in range(sec.paragraphs.count):
        para = sec.paragraphs.get_item(m)

        # 创建一个列表来存储图片
        pictures = []

        # 查找图片并将其添加到列表中
        for x in range(para.childobjects.count):
            docobj = para.childobjects.get_item(x)
            if docobj.documentobjecttype == documentobjecttype.picture:
                pictures.append(docobj)

        # 遍历列表中的所有图片,并用文本替换它们
        for pic in pictures:
            # 获取图片的索引位置
            index = para.childobjects.indexof(pic)
            # 创建一个textrange对象
            textrange = textrange(doc)
            textrange.text = "word document "
            textrange.characterformat.fontname = "arial"
            textrange.characterformat.fontsize = 20
            textrange.characterformat.textcolor = color.get_red()
            # 将文本插入到段落中
            para.childobjects.insert(index, textrange)
            # 删除图片
            para.childobjects.remove(pic)

# 保存结果文档
doc.savetofile("output/replacewordimagewithtext.docx")
doc.close()

结果文档

用python删除word文档中的图片

在找出文档中的图片子对象后,我们可以直接使用paragraph.childobjects.remove()方法删除图片子对象,从而删除word文档中的图片。以下是操作步骤:

1.导入所需模块。

2.创建document对象,使用document.loadfromfile()方法载入word文档。

3.依次遍历文档中的节、节中的段落以及段落中的子对象,判断每个子对象的documentobjecttype属性是否为documentobjecttype.picture,将判断成功的对象添加到列表中。

4.使用paragraph.childobjects.indexof()方法获取图片子对象在段落中的索引。

5.使用paragraph.childobjects.remove()方法删除图片子对象。

6.使用document.savetofile()方法保存文档。

7.释放资源。

代码示例:

from spire.doc import document, documentobjecttype, textrange, color

# 创建document对象
doc = document()

# 加载word文档
doc.loadfromfile("output/addpictoword.docx")

# 遍历文档中的所有节
for k in range(doc.sections.count):
    sec = doc.sections.get_item(k)

    # 遍历每一节中的所有段落
    for m in range(sec.paragraphs.count):
        para = sec.paragraphs.get_item(m)

        # 创建一个列表来存储图片
        pictures = []

        # 查找图片并将其添加到列表中
        for x in range(para.childobjects.count):
            docobj = para.childobjects.get_item(x)
            if docobj.documentobjecttype == documentobjecttype.picture:
                pictures.append(docobj)

        # 遍历列表中的所有图片,并用文本替换它们
        for pic in pictures:
            # 获取图片的索引位置
            index = para.childobjects.indexof(pic)
            # 删除图片子对象
            para.childobjects.remove(pic)

# 保存结果文档
doc.savetofile("output/removewordimage.docx")
doc.close()

结果文档

到此这篇关于python在word中进行图片添加、替换和删除操作的文章就介绍到这了,更多相关python word图片操作内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)
打赏 微信扫一扫 微信扫一扫

您想发表意见!!点此发布评论

推荐阅读

一招教你解决Pytorch GPU版本安装慢的问题

03-08

Python利用模板生成Word的三种方法小结

03-08

Python实现高精度敏感词过滤

03-08

Python实现语音启动电脑应用程序

03-08

Python+OpenCV开发一个视频播放器

03-08

Python实现查找并删除重复文件的方法小结

03-08

猜你喜欢

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论