Following on from my last question here
OpenXML looks like it probably does exactly what I want, but the documentation is terrible. An hour of googling hasn’t got me any closer to figuring out what I need to do.
I have a word document. I want to add an image to that word document (using word) in such a way that I can then open the document in OpenXML and replace that image. Should be simple enough, yes?
I’m assuming I should be able to give my image ‘placeholder’ an id of some sort and then use GetPartById to locate the image and replace it. Would this be the correct method? What is this Id? How do you add it using Word?
Every example I can find which does anything remotely similar starts by building the whole word document from scratch in ML, which really isn’t a lot of use.
EDIT: it occured to me that it would be easier to just replace the image in the media folder with the new image, but again can’t find any indication of how to do this.
Although the documentation for OpenXML isn’t great, there is an excellent tool that you can use to see how existing Word documents are built. If you install the OpenXml SDK it comes with the DocumentReflector.exe tool under the Open XML Format SDK\V2.0\tools directory.
Images in Word documents consist of the image data and an ID that is assigned to it that is referenced in the body of the document. It seems like your problem can be broken down into two parts: finding the ID of the image in the document, and then re-writing the image data for it.
To find the ID of the image, you’ll need to parse the MainDocumentPart. Images are stored in Runs as a Drawing element
In the above example, you need to find the ID of the image stored in the blip element. How you go about finding that is dependent on your problem, but if you know the filename of the original image you can look at the docPr element:
Then when you have the image ID, you can use that to rewrite the image data. I think this is how you would do it: