public static void replacePicture(string filePath) { using (WordprocessingDocument doc = WordprocessingDocument.Open(filePath, 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) { 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("test.png", FileMode.Open)) ip.FeedData(fileStream); } } } }
public static WordprocessingDocument InsertImages(this WordprocessingDocument doc, ClientContext clientContext, string contentControlTag, string attachementServerRelativeUrl, TraceWriter log, List <string> messages) { try { SdtElement cc = doc.MainDocumentPart.Document.Body.Descendants <SdtElement>().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 == contentControlTag) { return(true); } } return(false); }); string embed = null; if (cc != null) { Drawing dr = cc.Descendants <Drawing>().FirstOrDefault(); if (dr != null) { DocumentFormat.OpenXml.Drawing.Blip blip = dr.Descendants <DocumentFormat.OpenXml.Drawing.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; var attachmentFile = clientContext.Site.RootWeb.GetFileByServerRelativeUrl(attachementServerRelativeUrl); clientContext.Load(attachmentFile); clientContext.ExecuteQueryRetry(); if (attachmentFile != null) { // Returns required result ClientResult <Stream> attachmentStream = attachmentFile.OpenBinaryStream(); clientContext.ExecuteQueryRetry(); ip.FeedData(attachmentStream.Value); } } } return(doc); } catch (Exception ex) { string message = $"An error occurred replacing Image Content Control Tag \"{contentControlTag}\". Please ensure its an Image Content Control, and the value is the server relative url of an image file that you have access to"; log.Info(message); messages.Add(message); return(doc); } }