如何通过Python docx实现Word中图片自动适配大小?
解决python-docx插入图片自动适配表格单元格的问题
我用python-docx向Word文档的表格中插入图片时,程序默认按图片原生分辨率插入,导致尺寸过大。我不想给不同尺寸的图片设置固定宽高参数,希望实现像手动在Word中添加图片那样的自动适配效果。我尝试调整table.allow_autofit为True或False都没用,请问怎么解决?
核心思路
Word手动插入图片的自动适配,本质是按图片原始宽高比,将图片缩放到刚好适配容器(表格单元格/页面)的可用空间,避免变形或超出范围。要实现这个效果,需要先获取图片的宽高比,再结合页面/单元格的可用空间计算合适的插入尺寸,同时配置表格的自动适配规则。
具体实现
首先需要安装Pillow库来读取图片原始尺寸:
pip install pillow
修改后的代码如下:
import docx from docx.shared import Pt from docx.enum.text import WD_ALIGN_PARAGRAPH from docx.enum.style import WD_STYLE_TYPE from docx.enum.table import WD_TABLE_ALIGNMENT, WD_TABLE_AUTOFIT_BEHAVIOR import os from PIL import Image from docx.shared import Cm doc = docx.Document() section = doc.sections[0] header = section.header header_para = header.paragraphs[0] # 配置页眉样式 header_style = doc.styles.add_style('Header Style', WD_STYLE_TYPE.PARAGRAPH) font = header_style.font font.size = Pt(20) font.bold = True header_para.style = header_style header_para.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER header_para.text = "Header" # 处理目标图片 img_path = 'Capture.PNG' caption = os.path.basename(img_path) img_name, _ = os.path.splitext(caption) # 获取图片原始宽高比 with Image.open(img_path) as img: img_width, img_height = img.size aspect_ratio = img_width / img_height # 创建表格并配置自动适配 table = doc.add_table(rows=2, cols=1) table.alignment = WD_TABLE_ALIGNMENT.CENTER # 表格居中 table.allow_autofit = True table.autofit_behavior(WD_TABLE_AUTOFIT_BEHAVIOR.WD_AUTOFIT_CONTENTS) # 表格自动适配内容 table.style = 'Table Grid' # 计算页面可用宽度(减去页边距) page_width = section.page_width left_margin = section.left_margin right_margin = section.right_margin max_img_width = page_width - left_margin - right_margin # 计算适配后的图片尺寸(保持宽高比) target_width = max_img_width target_height = target_width / aspect_ratio # 插入图片到表格单元格 cell = table.cell(0, 0) run = cell.paragraphs[0].add_run() run.add_picture(img_path, width=target_width, height=target_height) # 添加图片标题 caption_para = table.cell(1, 0).paragraphs[0] caption_para.add_run(img_name) caption_para.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER doc.add_paragraph() doc.save('file.docx')
关键说明
- 宽高比计算:通过Pillow获取图片原始尺寸,计算宽高比,确保缩放后图片不会变形。
- 表格自动适配:
table.autofit_behavior(WD_TABLE_AUTOFIT_BEHAVIOR.WD_AUTOFIT_CONTENTS)让表格根据内容自动调整单元格大小,配合table.allow_autofit = True生效。 - 适配页面宽度:以页面可用宽度(总宽度减去左右页边距)作为图片的最大宽度,保证图片不会超出页面范围,同时按比例计算高度。
- 表格居中:设置
table.alignment = WD_TABLE_ALIGNMENT.CENTER让表格在页面中居中,提升排版美观度。
内容的提问来源于stack exchange,提问作者Ohtis
相关产品推荐
相关产品推荐

