AutoFitPictureinWordwithPythondocx
创始人
2024-11-12 13:30:14
0

使用Python docx库自动调整Word中的图片大小。

使用Python docx库中的Image类和Shape类的属性进行操作,将图片的大小设置为页面的宽度,实现图片自动适应页面大小。

代码示例:

from docx import Document
from docx.shared import Cm

doc = Document('example.docx')

for paragraph in doc.paragraphs:
    for run in paragraph.runs:
        if run.element.tag.endswith('}r'):
            for tup in run.element.xpath('.//wp:docPr'):
                if 'inline' in tup.attrib.values():
                    try:
                        shape_id = run._r.xpath('.//a:blip')[0].attrib['{%s}embed' % doc.part.related_parts[
                        run._r.xpath('.//a:blip')[0].attrib['{%s}link' % doc.part.nsmap['r']].rId].reltype]
                        shape_size = doc.part.related_parts[shape_id]._element.xpath('.//a:ext')[0]
                        cx = shape_size.get('cx')
                        cy = shape_size.get('cy')
                        cx, cy = int(cx), int(cy)
                        
                        if cx > doc.page_width * 9525:
                            shape_size.set('cx', str(doc.page_width * 9525))
                            shape_size.set('cy', str(cy * doc.page_width * 9525 // cx))
                    except:
                        pass

doc.save('example.docx')

注意:上面的代码仅对InlineShape(布局与文字相邻的图片)进行了调整,如果需要调整其他类型的图片,请将代码改为适当的方式来实现。

相关内容

热门资讯

透视积累!wpk有作必弊吗,W... 透视积累!wpk有作必弊吗,WPK方法都是真的是有下载,第四分钟教程(有挂教程)1、金币登录送、破产...
透视机巧!aapoker透视脚... 透视机巧!aapoker透视脚本入口,AApoker工具总是真的有脚本,第二分钟教程(详细教程)所有...
透视攻略!哈糖大菠萝免费辅助器... 透视攻略!哈糖大菠萝免费辅助器,WePoKer网页版切实是真的有插件,第6分钟教程(有挂方针)1、下...
透视诀窍!aapoker脚本,... 透视诀窍!aapoker脚本,AApoker发牌其实是有教程,三分钟教程(有挂方法)1、aapoke...
透视窍要!wepoker软件安... 透视窍要!wepoker软件安装包,HHpoker正品竟然存在有教程,第十分钟教程(有挂教程)1、进...
透视步骤!德州透视hhpoke... 透视步骤!德州透视hhpoker,HHpoker脚本竟然真的是有开挂,第九分钟教程(新版有挂)1、德...
透视教程书!wpk系统是否存在... 透视教程书!wpk系统是否存在作必弊行为,WPK私人局一贯是有工具,9分钟教程(真的有挂)1、首先打...
透视项目!hhpoker有没有... 透视项目!hhpoker有没有作必弊辅助,HHpoker脚本挂真是是有神器,第四分钟教程(有挂技巧)...
透视经验!wepoker私人局... 透视经验!wepoker私人局俱乐部,WePoKer脚本总是是真的有安装,第十分钟教程(有挂秘诀)进...
透视方式!wepoker免费透... 透视方式!wepoker免费透视,WePoKer助手真是存在有开挂,第9分钟教程(有挂规律)1、下载...