Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)

like image 437
Ruben Kostandyan Avatar asked Mar 07 '23 10:03

Ruben Kostandyan


1 Answers

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
like image 149
Shawn Avatar answered Mar 24 '23 12:03

Shawn