Home > Software design >  Word Document can't be opened when adding an image using OpenXML
Word Document can't be opened when adding an image using OpenXML

Time:10-31

After adding a Bitmap to a Docx file, I'm finding I get the following error when I then try to open the document in Microsoft Word.

Word experienced an error trying to open the file.

My code is as follows:

using (WordprocessingDocument doc = WordprocessingDocument.Open(saveAsPath, true))
            {
                Bitmap bm = GeneratCadImage();
                
                string fileName = @"C:\test.bmp";
                var codeBitmap = new Bitmap(fileName);
                Image image = (Image)codeBitmap;    
                Drawing drawing = ConvertBitmapToDrawing(doc, codeBitmap);
                Run newRun = new Run(drawing);

                //I've tried placing it in several places
                OpenXmlElement contentControl = doc.MainDocumentPart.Document.Body.Descendants().Where(x => x != null).Last() ;

                contentControl.InsertAfterSelf(newRun);    
            }

Regarding which ContentControl to place the image in, I have tried first, last etc to see if it's position has anything to do with it.

A clue is the file size only gets 10kb bigger despite the image being in the order of 7Mb.

The following is a pretty lengthy method but most of it is a copy paste from here: MSDN

    static Drawing ConvertBitmapToDrawing(WordprocessingDocument wordDoc, System.Drawing.Bitmap image)
    {
        MainDocumentPart mainDocumentPart = wordDoc.MainDocumentPart;
        ImagePart imagePart = mainDocumentPart.AddImagePart(ImagePartType.Bmp);
        using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
        {
            image.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
            stream.Position = 0;
            imagePart.FeedData(stream);
        }

        string imagePartId = mainDocumentPart.GetIdOfPart(imagePart);

        var element =
                 new 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 = imagePartId,
                                             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"
                     });

        return element;
    }

Edit:

@pfx: I couldn't run your code as is I was getting an error of:

Cannot insert the OpenXmlElement "newChild" because it is part of a tree

I was able to run it like this however:

Drawing drawing = ConvertBitmapToDrawing(doc, codeBitmap);
Run newRun = new Run(drawing);
Paragraph para = new();
para.Append(newRun);
doc.MainDocumentPart.Document.Body.AppendChild(para);

But this yielded the same result where I couldn't open the word document.

CodePudding user response:

That Run containing the Drawing needs to be within a Paragraph, which can be added as a child of the Body.

using (WordprocessingDocument doc = WordprocessingDocument.Open(saveAsPath, true))
{
    Bitmap bitmap = Bitmap.FromFile(@"C:\test.bmp") as Bitmap;
    DocumentFormat.OpenXml.Wordprocessing.Drawing drawing = ConvertBitmapToDrawing(doc, bitmap);
    doc.MainDocumentPart.Document.Body.AppendChild(
        new DocumentFormat.OpenXml.Wordprocessing.Paragraph(
            new DocumentFormat.OpenXml.Wordprocessing.Run(drawing)
            ));
}
  • Related