docx库不仅可以提取word文档中的图片,也可以给文档添加图片。本篇介绍如何添加一张图片到word文档中。
看一下效果图:
其中,最后的图片是通过代码加进去的。
代码:# -*- coding: utf-8 -*-
import os
import sys
import re
import time
import docx
from docx.shared import RGBColor
from docx.shared import Pt
def fetch_image(doc_path, desc_path):
"""
抓取word文件中的图片
:param doc_path: 文件名称
:param desc: 目标路径
:return:
"""
doc = docx.Document(doc_path)
dict_rel = doc.part._rels #rels其实是个目录
for rel in dict_rel:
rel = dict_rel[rel]
print("rel",rel.target_ref)
if "image" in rel.target_ref:
# create_dir(desc_path)
img_name = re.findall("/(.*)", rel.target_ref)[0] #windos:/
print("img_name",img_name)
word_name = os.path.splitext(doc_path)[0]
print("word_name",word_name)
if os.sep in word_name:
new_name = word_name.split('\')[-1]
else:
new_name = word_name.split('/')[-1]
#图片文件
img_name = f'{new_name}_{img_name}'
with open(f'{desc_path}/{img_name}', "wb") as f:
f.write(rel.target_part.blob)
def get_image():
"""
获取word文档中的图片
:param:
:return:
"""
doc_name = "念奴娇_赤壁怀古.docx"
desc_path = sys.argv[1]
pwd = os.path.dirname(os.path.abspath(desc_path))
print("[get_image]desc_path",desc_path)
desc_path = os.path.join(pwd, desc_path) #目标路径
fetch_image(doc_name,desc_path)
def add_image():
"""
在weord文档中添加一个图片
:param:
:return:
"""
doc_name = "念奴娇_赤壁怀古_1654065536.139004.docx"
doc = docx.Document(doc_name)
#添加一个图片
doc.add_picture('念奴娇_赤壁怀古_image1.jpg')
doc.save('add_image_test.docx')
#创建目录
def create_dir(desc_path):
if not os.path.exists(desc_path):
os.makedirs(desc_path)
if __name__ == '__main__':
#create_doc()
#fetch_doc()
#update_doc()
#create_doc_table()
#fetch_doc_table()
#modify_doc_table()
#get_image()
add_image()
说明:
1. add_image中,打开word文档的代码:
doc_name = "念奴娇_赤壁怀古_1654065536.139004.docx" doc = docx.Document(doc_name)2.add_image中,添加一张图片的代码:
doc.add_picture('念奴娇_赤壁怀古_image1.jpg'):添加一张图片3. 保存图片:
doc.save('add_image_test.docx')
用python操作word文档中的图片,是不是很简单呀!



