Replacing a Picture in a Picture Content Control in an Open XML WordprocessingML Document

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");
               
}
           
}
       
}
   
}
}