python使用docxtpl库实现图片替换功能

 更新时间:2026年01月21日 08:57:26   作者:一zhi小蜗牛  
这篇文章主要介绍了如何利用Python的DocxTemplate包实现Word文档中图片的自动化替换,主要是通过读取并解码base64字符串,将其转换为图片文件,再定位到Word文档中的图片位置进行替换,感兴趣的小伙伴可以了解下

代码示例

docxtpl 一个很强大的包,其主要通过对docx文档模板加载,从而对其进行修改,我主要是用docxtpl对图片进行替换。

简单代码如下:

import base64
from docxtpl import DocxTemplate

pl = int(input('输出数字:'))
num = 'D:\\py\\testdata\\1.docx'
tpl = DocxTemplate(num)
# 定义图片名称位置
context = {
    1: '1.jpg',
    2: '2.jpg',  
}
images = "base64"
tmp_img = "%s.jpg" % (pl)
with open(tmp_img, 'wb') as image_tpl:
    data = images.split(',')
    imgs_tmp = base64.b64decode(data[1])
    image_tpl.write(imgs_tmp)
    datas = image_tpl.name
print(datas)
# 判断位置,进行图片替换
if tpl:
    tpl.replace_pic(context.get(pl), datas)
print(tpl)
tpl.save("决定1003.docx")
print(tpl)

查找图片的位置

如果图片位置不清楚可以使用docx转xml,然后进行解压在目录word\document.xml下面可以找到图片的位置。

方法补充

1.Python替换图片的指定区域

要在Python中替换图片的指定区域,可以使用Pillow库。以下是一个简单的例子,展示如何替换图片的一个区域:

from PIL import Image

def replace_image_region(src_path, dest_path, region, replacement_image):
# 加载原始图片和替换区域的图片
image = Image.open(src_path)
replacement = Image.open(replacement_image).convert(image.mode)

# 获取替换区域的大小
region_width, region_height = region[2] - region[0], region[3] - region[1]

# 调整替换图片的大小以匹配替换区域
replacement = replacement.resize((region_width, region_height))

# 通过掩码获取替换区域
mask = Image.new("L", (region_width, region_height), 255)
region_image = image.crop(region)

# 应用掩码和替换图片
region_image.paste(replacement, (0, 0), mask)

# 粘贴图片区域回原图
image.paste(region_image, region)

# 保存新图片
image.save(dest_path)

使用示例

src_img_path = ‘source.jpg' # 原始图片路径
dest_img_path = ‘destination.jpg' # 替换后保存的图片路径
replacement_img_path = ‘replacement.png' # 替换区域的图片路径
region = (100, 100, 300, 300) # 替换的区域坐标 (左, 上, 右, 下)

replace_image_region(src_img_path, dest_img_path, region, replacement_img_path)

2.python-docx替换Word中图片的方法

需要先安装python-docx:

pip install python-docx

再使用以下的代码:

import docx
from docx.shared import Cm


def replace_img(in_word_path, out_word_path, output_paragraph_idx, new_img_path, height, width):
    """
    Replace a image in a docx(Word) file.
    :param in_word_path: The path of the input docx file to be replaced
    :param out_word_path: The path of the output docx file
    :param new_img_path: The path of the image that will be the new image in the docx file(i.e. one image(The image is assigned by output_paragraph_idx) will be replaced by the image which is in img_path)
    :param output_paragraph_idx: The paragraph index of the image in the docx file(The index starts with 0)
    :param height: The height of the new image which is in centimeters.
    :param width: The width of the new image which is in centimeters..
    :return: Empty
    """
    doc = docx.Document(in_word_path)
    para = doc.paragraphs[output_paragraph_idx]
    para.clear()
    pic = para.add_run().add_picture(new_img_path)
    pic.height = Cm(height)
    pic.width = Cm(width)
    doc.save(out_word_path)

到此这篇关于python使用docxtpl库实现图片替换功能的文章就介绍到这了,更多相关python docxtpl图片替换内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • python最小生成树kruskal与prim算法详解

    python最小生成树kruskal与prim算法详解

    这篇文章主要为大家详细介绍了python最小生成树kruskal与prim算法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-01-01
  • python通过实例讲解反射机制

    python通过实例讲解反射机制

    这篇文章主要介绍了python通过实例讲解反射机制,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-10-10
  • python实现用户登陆邮件通知的方法

    python实现用户登陆邮件通知的方法

    这篇文章主要介绍了python实现用户登陆邮件通知的方法,实例分析了Python计划任务与邮件发送的使用技巧,需要的朋友可以参考下
    2015-07-07
  • Python设置pip镜像源的几种方法

    Python设置pip镜像源的几种方法

    本文介绍了在Python中使用pip设置镜像源的方法,包括临时使用、永久配置、使用命令配置、查看配置、恢复默认源和使用多个镜像源等,推荐使用清华镜像源或阿里云镜像源,并提供了注意事项,如信任主机、超时设置和SSL验证,需要的朋友可以参考下
    2025-12-12
  • python函数闭包概念

    python函数闭包概念

    函数是实现特定功能的代码段的封装,在需要时可以多次调用函数来实现该功能,这篇文章主要介绍了python函数闭包概念,需要的朋友可以参考下
    2025-04-04
  • Python浅析匿名函数lambda的用法

    Python浅析匿名函数lambda的用法

    lambda所表示的匿名函数的内容应该是很简单的,如果复杂的话,干脆就重新定义一个函数了,使用lambda就有点过于执拗了。lambda就是用来定义一个匿名函数的,如果还要给他绑定一个名字的话,就会显得有点画蛇添足,通常是直接使用lambda函数
    2022-07-07
  • 如何安装anaconda以及修改源的最新方法

    如何安装anaconda以及修改源的最新方法

    anaconda是一个常用的python开发环境,使用anaconda可以方便地管理Python及其依赖包,这篇文章主要介绍了如何安装anaconda以及修改源的最新方法,文中通过代码介绍的非常详细,需要的朋友可以参考下
    2025-09-09
  • flask实现验证码并验证功能

    flask实现验证码并验证功能

    Flask是一个用Python编写的Web应用程序框架,Flask是python的web框架,最大的特征是轻便,让开发者自由灵活的兼容要开发的feature。这篇文章主要介绍了flask实现验证码并验证,需要的朋友可以参考下
    2019-12-12
  • Python实现使用卷积提取图片轮廓功能示例

    Python实现使用卷积提取图片轮廓功能示例

    这篇文章主要介绍了Python实现使用卷积提取图片轮廓功能,涉及Python数值运算与图像处理相关操作技巧,需要的朋友可以参考下
    2018-05-05
  • 40行Python代码实现天气预报和每日鸡汤推送功能

    40行Python代码实现天气预报和每日鸡汤推送功能

    这篇文章主要介绍了通过40行Python代码实现天气预报和每日鸡汤推送功能,代码简单易懂,非常不错具有一定的参考借鉴价值 ,需要的朋友可以参考下
    2020-02-02

最新评论