我有一个docx文件,其中包含6-7个图像。我需要自动从这个文档文件中提取图像。有没有类似的win32com
ms word API?或者任何可以准确提取其中所有图像的库?
这是我尝试过的,但问题首先是它没有给我所有的图像,其次它给了我许多错误的图像,比如空白图像,非常小的图像,线条等。它也使用MS word来做同样的事情。
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)
export_images(r"C:\Users\HPO2KOR\Desktop\Work\venv\us2017010202.docx")
你可以在这里下载docx文件https://drive.google.com/open?id=1xdw2MieI1n3ulXlkr
发布于 2021-11-22 11:57:51
使用python提取docx文件中的所有图像
1.使用docxtxt
import docx2txt
#extract text
text = docx2txt.process(r"filepath_of_docx")
#extract text and write images in Temporary Image directory
text = docx2txt.process(r"filepath_of_docx",r"Temporary_Image_Directory")
2.使用aspose
import aspose.words as aw
# load the Word document
doc = aw.Document(r"filepath")
# retrieve all shapes
shapes = doc.get_child_nodes(aw.NodeType.SHAPE, True)
imageIndex = 0
# loop through shapes
for shape in shapes :
shape = shape.as_shape()
if (shape.has_image) :
# set image file's name
imageFileName = f"Image.ExportImages.{imageIndex}_{aw.FileFormatUtil.image_type_to_extension(shape.image_data.image_type)}"
# save image
shape.image_data.save(imageFileName)
imageIndex += 1
https://stackoverflow.com/questions/60201419
复制相似问题