网站的架设,做网站要租服务器吗,广东企业网站模板推荐,广西建设网注册中心文章目录 前置操作解析body中的图形解析页眉中的图形 前置操作
基于pywin32打开、关闭word应用程序#xff1b; import pythoncom
from win32com.client import Dispatch, GetActiveObjectdef get_word_instance(): 获取word进程 实例py… 文章目录 前置操作解析body中的图形解析页眉中的图形 前置操作
基于pywin32打开、关闭word应用程序 import pythoncom
from win32com.client import Dispatch, GetActiveObjectdef get_word_instance(): 获取word进程 实例pythoncom.CoInitialize()try:# 获取运行的Word实例word_app GetActiveObject(Word.Application)except pythoncom.com_error:# 打开word程序word_app Dispatch(Word.Application)word_app.Visible False # 不显示 Word 界面word_app.DisplayAlerts Falsefinally:return word_appdef close_word_instance():try:word GetActiveObject(Word.Application)if word:word.Quit()except pythoncom.com_error:# 杀掉word进程pass解析body中的图形
graphics {}
import os
from PIL import ImageGrab, Imagedef get_graphic_with_pywin32(doc_path): 基于pywin32 解析文档主体中的图形 global graphicsword get_word_instance()doc word.Documents.Open(doc_path)for shape in doc.Shapes: # 文档主体中的图形print(shape:, shape.Name, shape.Type) # Type为1是图形Name唯一page_id shape.Anchor.Information(1)# shape.Anchor.CopyAsPicture() 个人版不支持# image ImageGrab.grabclipboard()# 方案1 图形转图片inline_shape shape.ConvertToInlineShape()bdata inline_shape.Range.EnhMetaFileBits.tobytes()from io import BytesIOimg Image.open(BytesIO(bdata))img.save(shape.Name .png)# 方案2若以上方案获取的图片 纵横比失真则采用该方案# inline_shape shape.ConvertToInlineShape()# inline_shape.Range.CopyAsPicture()# image ImageGrab.grabclipboard()# 方案3 图形直接保存 (个人版 报错AttributeError: unknown.SaveAsPicture)# pic_path os.path.abspath(./{}_3.png.format(shape.Name))# shape.SaveAsPicture(pic_path) # 绝对路径解析页眉中的图形
def get_graphic_with_pywin32(doc_path): 基于pywin32 解析文档主体中的图形 global graphicsword get_word_instance()doc word.Documents.Open(doc_path)for section in doc.Sections:for header in section.Footers:for shape in header.Shapes:inline_shape shape.ConvertToInlineShape()bdata inline_shape.Range.EnhMetaFileBits.tobytes() # 直接保存无法查看img PillowImage.open(BytesIO(bdata))img.save(./{}.png.format(shape.Name))with open(./{}.png.format(shape.Name), rb) as f:bdata f.read() # 读取的字节 与 image.tobytes() 不一样graphics[shape.Name] bdata # Name唯一