OpenXML added Image is in the Document media folder but not displayed in Office

Viewed 431

I have trouble creating a Word Document (openXML) and adding an image to it. I already tried a lot with code snippets i found only as well as the offical MS Documentation (https://docs.microsoft.com/de-de/office/open-xml/how-to-insert-a-picture-into-a-word-processing-document).

To get this working I basically copied the complete Code from the Link above and wrapped 2 WPF FileDialogs around to create a Document first, and then choose the Image to add. I also add some text before the image to check if accessing the document works in general.

Everything compiles and runs without errors. However the created Document only has my text and no sign of the image. I often read about people having errors like "a red X" or some sign of the ressource of an added image being missing, but for me the document simply contains nothing but the added text. HOWEVER when i open the Document as an archive (using winrar for example) I can see the image i have chosen is placed inside the "media" folder in my Document.

Why is nothing displayed when I open the document in an office application?

Below is my Code but its basically from the offical SDK:

using A = DocumentFormat.OpenXml.Drawing;
using DW = DocumentFormat.OpenXml.Drawing.Wordprocessing;
using PIC = DocumentFormat.OpenXml.Drawing.Pictures;    

public static void ExportToDoc()
    {
        
        SaveFileDialog exportFile = new SaveFileDialog
        {
            Filter = "Word Document (*.docx)|*.docx",
            AddExtension = true,
            FileName = "Proposed-Filename.docx"
        };
        switch (exportFile.ShowDialog())
        {
            case true:
                WordprocessingDocument doc = WordprocessingDocument.Create(exportFile.FileName, WordprocessingDocumentType.Document);
                // Make some changes to the document.  
                MainDocumentPart mainDocumentPart = doc.AddMainDocumentPart();
                mainDocumentPart.Document = new Document();
                Document document = mainDocumentPart.Document;
                Body body = document.AppendChild(new Body());
                Paragraph para = body.AppendChild(new Paragraph());
                Run run = para.AppendChild(new Run());
                run.AppendChild(new Text("Created text in body."));

                //Prepare Image
                OpenFileDialog openImage = new OpenFileDialog
                {
                    Filter = "Bild (*.jpg)| *.jpg"
                };
                
                //Document is created
                doc.Close();

                switch (openImage.ShowDialog())
                {
                    case true:
                        InsertAPicture(exportFile.FileName, openImage.FileName);
                        break;
                    default:
                        break;
                }

                Console.WriteLine("Bild angehängt");
                break;
            default:
                break;
        }
        
    }
    //from MSDN after this point:
    public static void InsertAPicture(string document, string fileName)
    {
        using (WordprocessingDocument wordprocessingDocument =
            WordprocessingDocument.Open(document, true))
        {
            MainDocumentPart mainPart = wordprocessingDocument.MainDocumentPart;

            ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg);

            using (FileStream stream = new FileStream(fileName, FileMode.Open))
            {
                imagePart.FeedData(stream);
            }

            AddImageToBody(wordprocessingDocument, mainPart.GetIdOfPart(imagePart));
        }
    }

    private static void AddImageToBody(WordprocessingDocument wordDoc, string relationshipId)
    {
        // Define the reference of the image.
        var element =
             new DocumentFormat.OpenXml.Office.Drawing.Drawing(
                 new DW.Inline(
                     new DW.Extent() { Cx = 990000L, Cy = 792000L },
                     new DW.EffectExtent()
                     {
                         LeftEdge = 0L,
                         TopEdge = 0L,
                         RightEdge = 0L,
                         BottomEdge = 0L
                     },
                     new DW.DocProperties()
                     {
                         Id = (UInt32Value)1U,
                         Name = "Picture 1"
                     },
                     new DW.NonVisualGraphicFrameDrawingProperties(
                         new A.GraphicFrameLocks() { NoChangeAspect = true }),
                     new A.Graphic(
                         new A.GraphicData(
                             new PIC.Picture(
                                 new PIC.NonVisualPictureProperties(
                                     new PIC.NonVisualDrawingProperties()
                                     {
                                         Id = (UInt32Value)0U,
                                         Name = "New Bitmap Image.jpg"
                                     },
                                     new PIC.NonVisualPictureDrawingProperties()),
                                 new PIC.BlipFill(
                                     new A.Blip(
                                         new A.BlipExtensionList(
                                             new A.BlipExtension()
                                             {
                                                 Uri =
                                                    "{28A0092B-C50C-407E-A947-70E740481C1C}"
                                             })
                                     )
                                     {
                                         Embed = relationshipId,
                                         CompressionState =
                                         A.BlipCompressionValues.Print
                                     },
                                     new A.Stretch(
                                         new A.FillRectangle())),
                                 new PIC.ShapeProperties(
                                     new A.Transform2D(
                                         new A.Offset() { X = 0L, Y = 0L },
                                         new A.Extents() { Cx = 990000L, Cy = 792000L }),
                                     new A.PresetGeometry(
                                         new A.AdjustValueList()
                                     )
                                     { Preset = A.ShapeTypeValues.Rectangle }))
                         )
                         { Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" })
                 )
                 {
                     DistanceFromTop = (UInt32Value)0U,
                     DistanceFromBottom = (UInt32Value)0U,
                     DistanceFromLeft = (UInt32Value)0U,
                     DistanceFromRight = (UInt32Value)0U,
                     EditId = "50D07946"
                 });

        // Append the reference to body, the element should be in a Run.
        wordDoc.MainDocumentPart.Document.Body.AppendChild(new Paragraph(new Run(element)));
    }

}
1 Answers

Ok I figured it out myself:

I was using the wrong Namespace for Drawing. Thats it.

Funny how this didnt produce any errors at all but did not work.

So if you have this Problem here is what I changed:

 private static void AddImageToBody(WordprocessingDocument wordDoc, string relationshipId)
        {
            // Define the reference of the image.
            var element =
                 new DocumentFormat.OpenXml.Office.Drawing.Drawing(
                   

Changed to:

private static void AddImageToBody(WordprocessingDocument wordDoc, string relationshipId)
            {
                // Define the reference of the image.
                var element =
                     new DocumentFormat.OpenXml.Wordprocessing.Drawing(
Related