You may have a picture content control where you want to replace the picture with a different picture. This post shows the Open XML SDK V2 code that is necessary to find a picture content control with an alias of “MyPicture”. It then finds the ImagePart, and then replaces the contents of the image part with a different image.
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; using DocumentFormat.OpenXml.Drawing; class Program { static void Main(string[] args) { using (WordprocessingDocument doc = WordprocessingDocument.Open("Test1.docx", true)) { SdtBlock cc = doc.MainDocumentPart.Document.Body.Descendants<SdtBlock>() .FirstOrDefault(c => { SdtProperties p = c.Elements<SdtProperties>().FirstOrDefault(); if (p != null) { // Is it a picture content control? SdtContentPicture pict = p.Elements<SdtContentPicture>().FirstOrDefault(); // Get the alias. SdtAlias a = p.Elements<SdtAlias>().FirstOrDefault(); if (pict != null && a.Val == "MyPicture") return true; } return false; }); string embed = null; if (cc != null) { Drawing dr = cc.Descendants<Drawing>().FirstOrDefault(); if (dr != null) { Blip blip = dr.Descendants<Blip>().FirstOrDefault(); if (blip != null) embed = blip.Embed; } } if (embed != null) { IdPartPair idpp = doc.MainDocumentPart.Parts .Where(pa => pa.RelationshipId == embed).FirstOrDefault(); if (idpp != null) { ImagePart ip = (ImagePart)idpp.OpenXmlPart; using (FileStream fileStream = File.Open("After.jpg", FileMode.Open)) ip.FeedData(fileStream); Console.WriteLine("done"); } } } } }
Hi Eric, I have noticed that if I have two picture content control with diferent names, the images are set to the last one replaced, so both controls have the same image at the end, do you know how to fix this issue?
thank you
blip.Embed return always the same rId for all picture content controls
All picture content controls will indeed have the same rId initially, because they all point to the same 'blank' image, so this method won't work with multiple images.
Made a blog post with a working solution: www.eelcomulder.nl/.../open-xml-setting-multiple-picture.html