OpenXML replacing image placeholder with actual image replaces all placeholders

Viewed 146

I have some weird problem trying to replace image placeholders in a Word document. If I try to replace the placeholder with the code below it replaces all of them. Not only the one who matches the name in docproperties.

With some further inspection I've discovered that viewing the word document with OpenXML SDK Productivity Tool that my placeholder pictures share the same embed id.. Why is that? That seems to be why all my placeholders get replaced by the new image.

Part of Document using OpenXML Productivity Tool:

 <pic:blipFill>
                <a:blip r:embed="rId6">
                  <a:extLst>
                    <a:ext uri="{28A0092B-C50C-407E-A947-70E740481C1C}">
                      <a14:useLocalDpi xmlns:a14="http://schemas.microsoft.com/office/drawing/2010/main" val="0" />
                    </a:ext>
                  </a:extLst>
                </a:blip>
                <a:stretch>
                  <a:fillRect />
                </a:stretch>
              </pic:blipFill>

My code in C#

public static void ReplacePlaceHolderWithPicture(this WordprocessingDocument doc, string nameOfImage, string imgFilePath)
{
    var drawings = doc.MainDocumentPart.Document.Descendants<Drawing>().ToList();
    var newImageBytes = File.ReadAllBytes(imgFilePath);

    foreach (var drawing in drawings)
    {
        var dpr = drawing.Descendants<DocProperties>().FirstOrDefault();
        if (dpr != null && dpr.Name == nameOfImage)
        {
            foreach (var b in drawing.Descendants<A.Blip>())
            {
                OpenXmlPart imagePart = doc.MainDocumentPart.GetPartById(b.Embed);

                using (var writer = new BinaryWriter(imagePart.GetStream()))
                {
                    writer.Write(newImageBytes);
                }
            }
        }
    }
}
0 Answers
Related