[Python] 纯文本查看 复制代码from PIL import Image
from io import BytesIO
from docx import Document
from docx.shared import Cm, Inches, RGBColor, Pt
from docx.oxml.ns import qn
import requests
import os
from lxml import etree
import time
import random
import threading
def add_img_to_word(image_url, doc, max_width_cm=14):
"""
下载图片并将其插入到Word文档中。
如果图片的实际宽度小于max_width_cm,则保持原样;否则,将宽度限制为max_width_cm。
:param doc: word文档
:param image_url: 图片URL
:param max_width_cm: 图片的最大宽度(单位:厘米)
"""
response = requests.get(image_url, timeout=15).content
# 使用BytesIO加载图片数据
img_stream = BytesIO(response)
img = Image.open(img_stream)
# 修复DPI缺失问题
if img.info.get("dpi") == (0, 0) or "dpi" not in img.info:
img.info["dpi"] = (72, 72)
#计算图片宽度
width_px = img.width
width_cm = width_px / img.info.get("dpi")[0] * 2.54
# 决定插入图片的宽度
if width_cm
结果展示: