none
Insert an image into Word using Open XML SDK 2.0

All replies

  • Hi ChileKitty,

    Thanks for your question.

    Firstly since it is required to use the Open XML SDK 2.0 under .NET Framework version 3.5 SP1, so you need to upgrade your .NET Framework. Maybe the compile error was caused by the wrong .NET Framework version.

    As to your problem of not being able to display the image, I guess it is probably because the code doesn't add an image reference in the document body. Using the answer code in this thread only add an image part to package level and there is no reference of it in the document body to display it. I think the sample code in this article will work to solve your problem. And since there is no VB.NET code in the mentioned article, you might try to search some tools to convert C# to VB.NET (which could not guarantee 100% accuracy, you might have to check it after convertion, there is a site about the differences between VB.NET and C# which might be helpful: http://www.harding.edu/fmccown/vbnet_csharp_comparison.html).

    Hope this helps. If you have any question, please let me know.

    Thanks,

    Lu

    Friday, April 02, 2010 2:28 AM
  • Hi Lu,

    First, I'd like to thank you very much for responding so quickly...

    OK, so I upgraded my project to 3.5 SP1 and switched over to c#.  On Friday I tried to follow the sample code (http://msdn.microsoft.com/en-us/library/bb497430(office.14).aspx) and could not get it to work so I decided to start a brand new project so I could try to understand, in code, exactly what I need to do in order to insert an image.  So I copied the code exactly as it is and only changed the image name to Pic.jpg (see below).  It does not even open; error reads >>>  Location: Par:/word/document.xml, Line:1, Column: 1390

    class Program
    {
    
        static void Main(string[] args)
        {
            string template = @"Tester.docx";
            string document = @"Tester1.docx";
            //string imageFileFolder = 
            string fileName = @"Pic.jpg";
            if (File.Exists(document))
            {
                File.Delete(document);
            }
            File.Copy(template, document,true);
            InsertAPicture(document, fileName);
        }
    
        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.
            //Define the reference of the image.
            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 = "Pic.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)));
    
        }
    }

    What I also tried on Friday was to reflect a docx with an image using the SDK tool.  After running the code, I tried to open the docx and it told me it was corrupt.  It  allowed me to open it up anyway but the image was not able to display (the little box with a red x ). 

    I see that both the sample code and the reflected code are similar.  Obviously I'm missing something in all this; I just can't see it or am not understanding something. Both my template and image are located under the bin/debug for this project.

    I appreicate your patience and all your help :)

     

     

     

     

     

    Monday, April 05, 2010 6:06 PM
  • Hi ChileKitty,

    Thanks for your reply.

    Firstly, it doesn't matter if you change the image name instead of "New Bitmap Image.jpg". I run the sample code on an empty Word document and it works well. From your shared code and error information, I guess there may be some problems with the template document or there occurs some conflicts after inserting a picture. So would you please show your content of the document.xml file of the template document before inserting the picture? This may help better figure out the problem and improve the sample code if needed.

    Thanks,

    Lu

    Tuesday, April 06, 2010 7:45 AM
  • Hi ChileKitty,

    Thanks for your reply.

    Firstly, it doesn't matter if you change the image name instead of "New Bitmap Image.jpg". I run the sample code on an empty Word document and it works well. From your shared code and error information, I guess there may be some problems with the template document or there occurs some conflicts after inserting a picture. So would you please show your content of the document.xml file of the template document before inserting the picture? This may help better figure out the problem and improve the sample code if needed.

    Thanks,

    Lu

    Tuesday, April 06, 2010 7:45 AM
  • Hi Lu,

    Thank you for responding!!!

    So, late yesterday I tried again to see what the problem could be but got a little smarter and used the SDK Productivity Tool.  I found that my document.xml contained 2 errors when validated:

    Body: (The element has unexpected child element 'http://schemas.openxmlformats.org/wordprocessingml/2006/main:p')                                    

    Inline (The 'http://schemas.microsoft.com/office.word/2010/wordprocessingDrawing:editId' attribute is not declared.)

    So I took out the editId in the Inline code ("EditId = "50D07946") and a picture came up J.  Don’t know if taking out the editId was correct or not...what do you think? 

    Then I went ahead and did what you did; started with a blank word document but I still received the same Body validation error.  I’m attaching the latest pre-drawing and post-drawing document.xml for you.

     

     <?xml version="1.0" encoding="UTF-8" standalone="yes" ?> 
    - <w:document xmlns:ve="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:w10="urn:schemas-microsoft-com:office:word" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:wne="http://schemas.microsoft.com/office/word/2006/wordml">
    - <w:body>
      <w:p w:rsidR="003661C5" w:rsidRDefault="003661C5" /> 
    - <w:sectPr w:rsidR="003661C5" w:rsidSect="003661C5">
      <w:pgSz w:w="12240" w:h="15840" /> 
      <w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="720" w:footer="720" w:gutter="0" /> 
      <w:cols w:space="720" /> 
      <w:docGrid w:linePitch="360" /> 
      </w:sectPr>
      </w:body>
      </w:document>
     <?xml version="1.0" encoding="utf-8" standalone="yes" ?> 
    - <w:document xmlns:ve="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:w10="urn:schemas-microsoft-com:office:word" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:wne="http://schemas.microsoft.com/office/word/2006/wordml">
    - <w:body>
      <w:p w:rsidRPr="008B4C5D" w:rsidR="009404EB" w:rsidP="008B4C5D" w:rsidRDefault="009404EB" /> 
    - <w:sectPr w:rsidRPr="008B4C5D" w:rsidR="009404EB" w:rsidSect="005B274A">
      <w:footerReference w:type="even" r:id="rId9" /> 
      <w:footerReference w:type="default" r:id="rId10" /> 
      <w:footerReference w:type="first" r:id="rId11" /> 
      <w:type w:val="continuous" /> 
      <w:pgSz w:w="12240" w:h="15840" w:code="1" /> 
      <w:pgMar w:top="1440" w:right="864" w:bottom="1440" w:left="1440" w:header="720" w:footer="432" w:gutter="0" /> 
      <w:cols w:space="1080" /> 
      <w:docGrid w:linePitch="360" /> 
      </w:sectPr>
    - <w:p>
    - <w:r>
    - <w:drawing>
    - <wp:inline distT="0" distB="0" distL="0" distR="0">
      <wp:extent cx="990000" cy="792000" /> 
      <wp:effectExtent l="0" t="0" r="0" b="0" /> 
      <wp:docPr id="1" name="Picture 1" /> 
    - <wp:cNvGraphicFramePr>
      <a:graphicFrameLocks noChangeAspect="1" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" /> 
      </wp:cNvGraphicFramePr>
    - <a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main">
    - <a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture">
    - <pic:pic xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture">
    - <pic:nvPicPr>
      <pic:cNvPr id="0" name="Pic.jpg" /> 
      <pic:cNvPicPr /> 
      </pic:nvPicPr>
    - <pic:blipFill>
    - <a:blip r:embed="Rf1ce3874f22a4c73" cstate="print">
    - <a:extLst>
      <a:ext uri="{28A0092B-C50C-407E-A947-70E740481C1C}" /> 
      </a:extLst>
      </a:blip>
    - <a:stretch>
      <a:fillRect /> 
      </a:stretch>
      </pic:blipFill>
    - <pic:spPr>
    - <a:xfrm>
      <a:off x="0" y="0" /> 
      <a:ext cx="990000" cy="792000" /> 
      </a:xfrm>
    - <a:prstGeom prst="rect">
      <a:avLst /> 
      </a:prstGeom>
      </pic:spPr>
      </pic:pic>
      </a:graphicData>
      </a:graphic>
      </wp:inline>
      </w:drawing>
      </w:r>
      </w:p>
      </w:body>
      </w:document>

    Please let me know if you need more information.

    I apprecitate your patience and help....:)  Thank  you!!

     

     

    • Edited by ChileKitty Tuesday, April 06, 2010 2:52 PM code was running into each other
    Tuesday, April 06, 2010 2:51 PM
  • Hi ChileKitty,

    Thanks for your detailed description.

    Regarding the EditId, you could find its description from the Open XML SDK Documentation of the Tool, it is a property of class Inline:

    editId, this property is only available in Office2010.

    So may be this is the problem (I'm using Office2010, which I guess you are not using). You could delete this property if you are not using Office2010 or delete the code:EditId = "50D07946" from the sample code.

    Regarding the validation error, I checked your documen.xml file content and found that this is probably due to that the SectionProperties element is not the last child of Body. It is caused by the code:

    wordDoc.MainDocumentPart.Document.Body.AppendChild(new Paragraph(new Run(element)));

    and we suggest you change it to:

    wordDoc.MainDocumentPart.Document.Body.LastChild.PrependChild(new Paragraph(new Run(element)));

    This method will insert the picture at the beginning of the document, if you don't want to do so, you could try methods like InsertAfter<T>() or InsertBefore<T>() of OpenXmlElement. The detailed API information could also be found in the Open XML SDK Documentation of the Tool.

    Hope this helps. Thank you very much for helping us find the issues of the sample code, which we will try to improve. If you have any question, please let me know.

    Thanks,

    Lu

    Wednesday, April 07, 2010 5:59 AM
  • Hi Lu,

    Thank you for your response J

     

    I did insert the change above and again, the document opens without an issue (great!!) but I still receive a validation error in my document.xml (see below):

     

    Error Node Type:  SectionProperites

    Related Node Type:  OpenXMLUnknowElement

    Description:  The element has an invalid child element  'http://schemas.openxmlformats.org/wordprocessingml/2006/main:p'.  List of possible elements expected: <http://schemas.openxmlformats.org/wordprocessingml/2006/main: headerReference>, <http://schemas.openxmlformats.org/wordprocessingml/2006/main:footerReference>

     

    My question now is….how bad are either (this and my previous) validation errors?  Will they come back to haunt me later if I leave the code as is?

    I will need to research this and see what I find.  In the meantime, thank you your help and patience.   J

    Wednesday, April 07, 2010 8:26 PM
  • Hi ChileKitty,

    Thanks for your feedback.

    From the error information I guess there is Paragraph element under SectionProperties element, which is against the schema. For elements which can be the child element of a SectionProperties, you could refer to the "Child Element Tree" section of the Tool. So could you show your content of the tag <w:sectPr>? Since I have validated your document.xml in the previous post, and there was not such validation as you mentioned. Another information I want to get from you is that which method do you choose to insert the paragragh which contains the image reference? PrependChild(), InsertAfter() or InsertBefore()? This might help figure out the problem.

    Hope this helps. If you have any question, please let me know.

    Thanks,

    Lu

    Thursday, April 08, 2010 1:50 AM
  • Hi Lu,

    Sorry for not responding earlier; I was pulled off the insert image to research 'search and replace' (which I will need to post a question here later on this subject).  Here is the <s:sectPr>:

    <w:sectPr w:rsidR="003661C5" w:rsidSect="003661C5">
        <w:pgSz w:w="12240" w:h="15840" />
        <w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="720" w:footer="720" w:gutter="0" />
        <w:cols w:space="720" />
        <w:docGrid w:linePitch="360" />
      </w:sectPr>
    

    And I'm using the method of Append now but have used the AppendChild with the same results. 

    Thank you for all your help and information :)

     

     

    Wednesday, April 14, 2010 2:59 PM
  • Hi ChileKitty,

    Thanks for your reply.

    From your description and shared XML content, I find there is nothing wrong with the SectionProperties element. But you said you are using Append method to add the reference of image to body, right? If so, it will result in the fact that SectionProperties is not the last child of body, for Append or AppendChild method will both add the elements/element to the end of the body. So I suggest you using PrependChild or InsertBefore/InsertAfter methods instead of Append/AppendChild. You could refer to the "Open XML Documentation" section of the Tool for more detailed information about those APIs.

    Hope this helps. If you have any question, please let me know.

    Thanks,

    Lu

    Thursday, April 15, 2010 6:22 AM
  •  

    Do you Know if this works in vb .net? i have tried to translate to vb .net but i am not having any luck....all the translators dont seem to work with the above AddImageToBody piece

    any help would be greatly appreciated.

     

     

    Monday, May 24, 2010 11:46 PM
  • Hi Chuck Farah,

    Thanks for your question.

    I'm afraid currently you may need to translate the code from C# to VB.NET manually for the sample code in VB.NET is not available on MSDN now. Besides, this link might be helpful to you when doing the translation.

    Thanks,

    Lu

    Monday, May 31, 2010 6:09 AM
  • So I suggest you using PrependChild or InsertBefore/InsertAfter methods instead of Append/AppendChild. You could refer to the "Open XML Documentation" section of the Tool for more detailed information about those APIs.



    Do you have any examples of this? I'm trying to insert one image on the bottom of a page in a word document (docx) that has several pages.

    Monday, January 17, 2011 10:09 PM
  • Thanks a lot ChileKitty. I struggled with this problem for two precious days :( and I never thought of EditId.
    Wednesday, November 21, 2012 9:09 PM