Search code examples
pythonsvgdocx.emf

Unable to insert EMF into Word using Python


I have a requirement for inserting SVG file into Word. Since, we cannot do this directly I am planning to convert SVG to EMF and insert it. Conversion from SVG to EMF works fine using the inkscape. However, I am unable to come up with right code for inserting it into Word. I followed the steps explained the the person Alvaro in this post. Have shown the steps followed in the attached file - enter image description here

This is my code -

enter image description here

However, when I run the code shown in the attachment - It still throws docx.image.exceptions.UnrecognizedImageError. The Contributor of the library on github claims that this library addresses this issue. If so then please let me know if I am missing anything.

I am able to insert the EMF file successfully manually. Attaching the doc by inserting the EMF. This EMF was downloaded from the internet for testing.


Solution

  • Here is another solution based on win32com module and MS Word API:

    from pathlib import Path
    import win32com.client
    
    cur_dir  = Path.cwd()                                   # get current folder
    pictures = list((cur_dir / "pictures").glob("*.emf"))   # get a list of pictures
    word_app = win32com.client.Dispatch("Word.Application") # run Word
    doc      = word_app.Documents.Add()                     # create a new docx file
    
    for pict in pictures:                                   # insert all pictures
        doc.InlineShapes.AddPicture(pict)
    
    doc.SaveAs(str(cur_dir / "pictures.docx"))              # save the docx file
    doc.Close()                                             # close docx
    word_app.Quit()                                         # close Word
    

    Put your EMF images in subfolder pictures and run this script. After that you get in current folder the file pictures.docx that contains all these EMF images inside.