How to get an image (inlineshape) from paragraph python docx

你离开我真会死。 提交于 2020-01-04 06:06:46

问题


I want to read the docx document paragraph by paragraph and if there is a picture (InlineShape), then process it with the text around it. The function Document.inline_shapes will give the list of all inline shapes in the document. But I want to get the one, that appears exactly in the current paragraph if exists...

An example of code:

from docx import Document

doc = Document("test.docx")
blip = doc.inline_shapes[0]._inline.graphic.graphicData.pic.blipFill.blip
rID = blip.embed
document_part = doc.part
image_part = document_part.related_parts[rID]

fr = open("test.png", "wb")
fr.write(image_part._blob)
fr.close()

(this is how I want to save these pictures)


回答1:


Assume your paragraph is par, you may use the following code to find the images

import xml.etree.ElementTree as ET
def hasImage(par):
    """get all of the images in a paragraph 
    :param par: a paragraph object from docx
    :return: a list of r:embed 
    """
    ids = []
    root = ET.fromstring(par._p.xml)
    namespace = {
             'a':"http://schemas.openxmlformats.org/drawingml/2006/main", \
             'r':"http://schemas.openxmlformats.org/officeDocument/2006/relationships", \
             'wp':"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"}

    inlines = root.findall('.//wp:inline',namespace)
    for inline in inlines:
        imgs = inline.findall('.//a:blip', namespace)
        for img in imgs:     
            id = img.attrib['{{{0}}}embed'.format(namespace['r'])]
        ids.append(id)

    return ids


来源:https://stackoverflow.com/questions/49800705/how-to-get-an-image-inlineshape-from-paragraph-python-docx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!