Skip to content

Instantly share code, notes, and snippets.

@lanfon72
Created June 8, 2017 03:39
Show Gist options
  • Save lanfon72/fd97a2fdaf8c1b71eb998a82222f434f to your computer and use it in GitHub Desktop.
Save lanfon72/fd97a2fdaf8c1b71eb998a82222f434f to your computer and use it in GitHub Desktop.
export word images via python win32com
from pathlib import Path
from win32com.client import Dispatch
xls = Dispatch("Excel.Application")
doc = Dispatch("Word.Application")
def export_images(fp, prefix="img_", suffix="png"):
""" export all of images(inlineShapes) in the word file.
:param fp: path of word file.
:param prefix: prefix of exported images.
:param suffix: suffix of exported images.
"""
fp = Path(fp)
word = doc.Documents.Open(str(fp.resolve()))
sh = xls.Workbooks.Add()
for idx, s in enumerate(word.inlineShapes, 1):
s.Range.CopyAsPicture()
d = sh.ActiveSheet.ChartObjects().add(0, 0, s.width, s.height)
d.Chart.Paste()
d.Chart.Export(fp.parent / ("%s_%s.%s" % (prefix, idx, suffix))
sh.Close(False)
word.Close(False)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment