Adding Images to Documents in Word 2007 by Using the Open XML SDK 2.0 for Microsoft Office

Summary: Learn how to use the Open XML Software Development Kit 2.0 for Microsoft Office to programmatically create Word 2007 documents that contain inline and floating images. (19 printed pages)

Office Visual How To

Applies to: 2007 Microsoft Office System, Microsoft Office Word 2007, Open XML SDK 2.0 for Microsoft Office, Microsoft Office Excel 2007, Microsoft Office PowerPoint 2007

Joel Krist, iSoftStone

August 2009

Overview

The Open XMLSoftware Development Kit 2.0 for Microsoft Office makes it possible to create and manipulate Microsoft Office Word 2007, Microsoft Office Excel 2007, and Microsoft Office PowerPoint 2007 documents programmatically via the Open XML formats. The typesafe classes included with the SDK provide a layer of abstraction between the developer and the Open XML formats, simplifying the process of working with Office 2007 documents and enabling the creation of solutions that are not dependent on the presence of the Office client applications to handle document creation.

The sample code in this visual how-to article shows how to use the classes provided with the Open XML SDK 2.0 for Microsoft Office to programmatically create a Word 2007 document that contains inline and floating images. The code uses the Drawing, Anchor, Inline, and ImagePart Open XML SDK 2.0 classes to create the required document parts.

See It Video startup screen

Watch the Video

Length: 08:34 | Size: 13.60 MB | Type: WMV file

Code It | Read It | Explore It

Code It

Download the sample code

This visual how-to article presents a solution that creates a Word 2007 document that contains two images. The first image is formatted as an inline image by setting its Text Wrapping format to In Line with Text.

Figure 1. Inline image in a Word document

Inline image in a Word document

 

The second image is formatted as a floating image by setting its Text Wrapping format to Tight.

Figure 2. Floating image in a Word document

Floating image in a Word document

 

To illustrate how to create a Word 2007 document that contains inline and floating images programmatically, this section walks through the following steps:

  1. Creating a Windows console application solution in Visual Studio 2008.

  2. Adding references to the DocumentFormat.OpenXml, WindowsBase, and System.Drawing assemblies.

  3. Adding the sample code to the solution.

Creating a Windows Console Application in Visual Studio 2008

This visual how-to article uses a Windows console application to provide the framework for the sample code. However, you could use the same approach that is illustrated here with other application types as well.

To create a Windows Console Application in Visual Studio 2008

  1. Start Microsoft Visual Studio 2008.

  2. On the File menu, point to New, and then click Project.

  3. In the New Project dialog box select the Visual C# Windows type in the Project types pane.

  4. Select Console Application in the Templates pane, and then name the project AddImage.

    Figure 3. Create new solution in the New Project dialog box

    Create new solution in the New Project dialog box

     

  5. Click OK to create the solution.

Adding References to the DocumentFormat.OpenXml, WindowsBase, and System.Drawing Assemblies

The sample code uses the classes and enumerations that are in the DocumentFormat.OpenXml.dll assembly that is installed with the Open XML SDK 2.0 for Microsoft Office. To add the reference to the assembly in the following steps or to build the sample code that accompanies this visual how-to, you must first download and install the Open XML SDK 2.0 for Microsoft Office so that the assembly is available.

To add References to the DocumentFormat.OpenXml, WindowsBase, and System.Drawing Assemblies

  1. Add a reference to the DocumentFormat.OpenXml assembly by doing the following:

    1. On the Project menu in Visual Studio, click Add Reference to open the Add Reference dialog box.

    2. Select the .NET tab, scroll down to DocumenFormat.OpenXml, select it, and then click OK.

      Figure 4. Add Reference to DocumentFormat.OpenXML

      Add Reference to DocumentFormat.OpenXML

       

  2. The classes in the DocumentFormat.OpenXml assembly use the System.IO.Packaging.Package class that is defined in the WindowsBase assembly. Add a reference to the WindowsBase assembly by doing the following:

    1. On the Project menu in Visual Studio, click Add Reference to open the Add Reference dialog box.

    2. Select the .NET tab, scroll down to WindowsBase, select it, and then click OK.

      Figure 5. Add Reference to WindowsBase

      Add Reference to WindowsBase

       

  3. The sample code uses the Bitmap class that is defined in the System.Drawing assembly. Add a reference to the System.Drawing assembly by doing the following:

    1. On the Project menu in Visual Studio, click Add Reference to open the Add Reference dialog box.

    2. Select the .NET tab, scroll down to System.Drawing, select it, and then click OK.

      Figure 6. Add Reference to System.Drawing

      Add Reference to System.Drawing

       

Adding the Sample Code to the Solution

Replace the entire contents of the Program.cs source file with the following code.

using System;
using System.IO;
using System.Drawing;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using wp = DocumentFormat.OpenXml.Drawing.Wordprocessing;
using DocumentFormat.OpenXml;
using a = DocumentFormat.OpenXml.Drawing;
using pic = DocumentFormat.OpenXml.Drawing.Pictures;

class Program
{
  static void Main(string[] args)
  {
    string imageDocumentPath = @"C:\Temp\ImageDocument.docx";
    string imageFileFolder = @"C:\Temp\";
    string imageFileName = "Image.jpg";

    using (WordprocessingDocument package =
      WordprocessingDocument.Create(imageDocumentPath,
      WordprocessingDocumentType.Document))
    {
      AddParts(package, imageFileFolder, imageFileName);
    }
  }

  private static void AddParts(WordprocessingDocument parent,
      string imageFileFolder, string imageFileName)
  {
    long imageWidthEMU = 0;
    long imageHeightEMU = 0;

    var mainDocumentPart = parent.AddMainDocumentPart();

    var imagePart =
      mainDocumentPart.AddNewPart<ImagePart>("image/jpeg", "rId1");

    GenerateImagePart(imagePart, imageFileFolder + imageFileName,
      ref imageWidthEMU, ref imageHeightEMU);

    GenerateMainDocumentPart(imageFileName, imageWidthEMU,
      imageHeightEMU).Save(mainDocumentPart);
  }

  private static Document GenerateMainDocumentPart(
    string imageFileName, long imageWidthEMU, long imageHeightEMU)
  {
    string fillText = "0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 ";
    string GraphicDataUri =
      "http://schemas.openxmlformats.org/drawingml/2006/picture";
    
    // Image wrapping polygons in Microsoft Word use a fixed
    // coordinate space that is 21600 units x 21600 units.
    // Coordinate (0,0) is the upper left corner of the image and
    // coordinate (21600,21600) is the lower right corner of the
    // image. This is the case regardless of the original size of
    // the image. The 21600 value is a legacy artifact from the
    // drawing layer of early versions of the Microsoft Office.
    // 
    // In order to specify a triangular wrapping polygon with
    // specific margins for a floating image the code shown below
    // needs to know how many wrapping polygon units there are per
    // inch in both the horizontal and vertical directions since
    // they will not be the same for non-square images.

    double imageWidthInInches = imageWidthEMU / 914400.0;
    double imageHeightInInches = imageHeightEMU / 914400.0;

    long horizontalWrapPolygonUnitsPerInch =
      (long)(21600L / imageWidthInInches);

    long verticalWrapPolygonUnitsPerInch =
      (long)(21600L / imageHeightInInches); 

    var element =
      new Document(
        new Body(
          new Paragraph(

            new ParagraphProperties(
              new Justification() { Val = JustificationValues.Both }),

            new Run(
              new Text(fillText + fillText + fillText +
                       fillText + fillText + fillText +
                       fillText + fillText + fillText +
                       fillText + fillText + fillText +
                       fillText + fillText + fillText +
                       fillText + fillText + fillText)),

            new Run(
              new Drawing(
                new wp.Inline(

                  new wp.Extent()
                  {
                    Cx = imageWidthEMU,
                    Cy = imageHeightEMU
                  },

                  new wp.EffectExtent()
                  {
                    LeftEdge = 19050L,
                    TopEdge = 0L,
                    RightEdge = 9525L,
                    BottomEdge = 0L
                  },

                  new wp.DocProperties()
                  {
                    Id = (UInt32Value)1U,
                    Name = "Inline Text Wrapping Picture",
                    Description = imageFileName
                  },

                  new wp.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 = imageFileName
                          },
                          new pic.NonVisualPictureDrawingProperties()),

                        new pic.BlipFill(
                          new a.Blip() { Embed = "rId1" },
                          new a.Stretch(
                            new a.FillRectangle())),

                        new pic.ShapeProperties(
                          new a.Transform2D(
                            new a.Offset() { X = 0L, Y = 0L },
                            new a.Extents()
                            {
                                Cx = imageWidthEMU,
                                Cy = imageHeightEMU
                            }),

                          new a.PresetGeometry(
                            new a.AdjustValueList()
                          ) { Preset = a.ShapeTypeValues.Rectangle }))
                    )
                    { Uri = GraphicDataUri })
                )
                {
                    DistanceFromTop = (UInt32Value)0U,
                    DistanceFromBottom = (UInt32Value)0U,
                    DistanceFromLeft = (UInt32Value)0U,
                    DistanceFromRight = (UInt32Value)0U
                })),

              new Run(
                  new Text(fillText + fillText + fillText +
                           fillText + fillText + fillText +
                           fillText + fillText + fillText +
                           fillText + fillText + fillText +
                           fillText + fillText + fillText +
                           fillText + fillText + fillText))
          ),

          new Paragraph(

            new ParagraphProperties(
              new Justification() { Val = JustificationValues.Both },

            new Run(

              new Drawing(

                new wp.Anchor(

                  new wp.SimplePosition() { X = 0L, Y = 0L },

                  // Center the image horizontally on the page.
                  new wp.HorizontalPosition(
                    new wp.HorizontalAlignement("center")
                  )
                  { RelativeFrom =
                    wp.HorizontalRelativePositionValues.Margin },

                  // Position the image 1.5" from the top of the
                  // paragraph.
                  new wp.VerticalPosition(
                    new wp.PositionOffset("1371600")
                  )
                  { RelativeFrom =
                    wp.VerticalRelativePositionValues.Paragraph },

                  new wp.Extent()
                  { Cx = imageWidthEMU,
                    Cy = imageHeightEMU },

                  new wp.EffectExtent()
                  { LeftEdge = 0L,
                    TopEdge = 0L,
                    RightEdge = 0L,
                    BottomEdge = 0L },

                  new wp.WrapTight(
                    new wp.WrapPolygon(
                      // Create a wrapping polygon that is a triangle.
                      // Start point is 1" to the left and .5" above
                      // the upper left corner of the image.
                      new wp.StartPoint()
                      { X = -horizontalWrapPolygonUnitsPerInch,
                        Y = -verticalWrapPolygonUnitsPerInch / 2
                      },
                      // Next point is centered horizontally and 1"
                      // below the bottom of the image.
                      new wp.LineTo()
                      { X = 10800,
                        Y = 21600L + verticalWrapPolygonUnitsPerInch
                      },
                      // Next point is 1" to the right and .5" above
                      // the upper right corner of the image.
                      new wp.LineTo() 
                      { X = 21600L + horizontalWrapPolygonUnitsPerInch,
                        Y = -verticalWrapPolygonUnitsPerInch / 2 }
                    ) { Edited = false }
                  ){ WrapText = wp.WrapTextValues.BothSides },
                  
                  new wp.DocProperties()
                  { Id = (UInt32Value)2U,
                    Name = "Tight Text Wrapping Picture",
                    Description = "imageFileName" },

                  new wp.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 = "imageFileName" },
                          new pic.NonVisualPictureDrawingProperties()),

                        new pic.BlipFill(
                          new a.Blip() { Embed = "rId1" },
                          new a.Stretch(
                            new a.FillRectangle())),

                        new pic.ShapeProperties(

                          new a.Transform2D(
                            new a.Offset() { X = 0L, Y = 0L },

                            new a.Extents()
                            { Cx = imageWidthEMU,
                              Cy = imageHeightEMU }),
                          
                          new a.PresetGeometry(
                            new a.AdjustValueList()
                          )
                          { Preset = a.ShapeTypeValues.Rectangle }
                        )
                      )
                )
                { Uri = GraphicDataUri })
              )
              { DistanceFromTop = (UInt32Value)0U,
                DistanceFromBottom = (UInt32Value)0U,
                DistanceFromLeft = (UInt32Value)114300U,
                DistanceFromRight = (UInt32Value)114300U,
                SimplePos = false,
                RelativeHeight = (UInt32Value)251658240U,
                BehindDoc = true,
                Locked = false,
                LayoutInCell = true,
                AllowOverlap = true })),

                new Run(
                  new Text(fillText + fillText + fillText +
                           fillText + fillText + fillText +
                           fillText + fillText + fillText +
                           fillText + fillText + fillText +
                           fillText + fillText + fillText +
                           fillText + fillText + fillText +
                           fillText + fillText + fillText +
                           fillText + fillText + fillText +
                           fillText + fillText + fillText +
                           fillText + fillText + fillText +
                           fillText + fillText + fillText +
                           fillText + fillText + fillText +
                           fillText + fillText + fillText +
                           fillText + fillText + fillText +
                           fillText + fillText + fillText))
          )
        )
      )
    );

    return element;
  }

  public static void GenerateImagePart(OpenXmlPart part,
    string imageFilePath, ref long imageWidthEMU,
    ref long imageHeightEMU)
  {
    byte[] imageFileBytes;
    Bitmap imageFile;

    // Open a stream on the image file and read it's contents.
    using (FileStream fsImageFile = File.OpenRead(imageFilePath))
    {
      imageFileBytes = new byte[fsImageFile.Length];
      fsImageFile.Read(imageFileBytes, 0, imageFileBytes.Length);

      imageFile = new Bitmap(fsImageFile);
    }

    // Get the dimensions of the image in English Metric Units (EMU)
    // for use when adding the markup for the image to the document.
    imageWidthEMU =
      (long)(
      (imageFile.Width / imageFile.HorizontalResolution) * 914400L);
    imageHeightEMU =
      (long)(
      (imageFile.Height / imageFile.VerticalResolution) * 914400L);

    // Write the contents of the image to the ImagePart.
    using (BinaryWriter writer = new BinaryWriter(part.GetStream()))
    {
      writer.Write(imageFileBytes);
      writer.Flush();
    }
  }
}

Build and run the solution in Visual Studio by pressing CTRL+F5. When you build and run the sample code, it creates a document named ImageDocument.docx in the C:\Temp folder. To change the name or location of the document modify the sample code and change the value of the imageDocumentPath variable defined in the Main method.

The document that the sample code creates contains inline and floating images. The sample code specifies that the image file to insert into the document is named Image.jpg and is located in the C:\Temp folder. To change the name or the location of the image file, modify the sample code and change the values of the imageFileFolder or imageFileName variables defined in the Main method.

Read It

The sample code in this visual how-to article illustrates how to create a Word 2007 document that contains inline and floating images. This section uses code snippets from the Code It section to describe the approach to the solution.

The code first creates a WordprocessingDocument package via the WordprocessingDocument.Create method. It then calls the AddParts helper method to add the document parts needed to support the images.

using (WordprocessingDocument package =
    WordprocessingDocument.Create(imageDocumentPath,
    WordprocessingDocumentType.Document))
{
    AddParts(package, imageFileFolder, imageFileName);
}

The AddParts method calls helper methods to add the main document and image parts to the package.

var mainDocumentPart = parent.AddMainDocumentPart();

var imagePart =
    mainDocumentPart.AddNewPart<ImagePart>("image/jpeg", "rId1");

GenerateImagePart(imagePart, imageFileFolder + imageFileName,
    ref imageWidthEMU, ref imageHeightEMU);

GenerateMainDocumentPart(imageFileName, imageWidthEMU,
    imageHeightEMU).Save(mainDocumentPart);

The main document part created by the GenerateMainDocumentPart method contains two paragraphs. The first paragraph contains the inline image that is preceeded and followed by text to illustrate it's inline placement. The code adds a Run to the paragraph that contains a Drawing element with a child Inline element that specifies the details of the inline image. The relationship to the image part that contains the image bytes is specified with a Blip element that has it's Embed attribute set to the relationship ID of the image part.

new Paragraph(

  new ParagraphProperties(
    new Justification() { Val = JustificationValues.Both }),

  new Run(
    new Text(fillText + fillText + fillText +
             fillText + fillText + fillText +
             fillText + fillText + fillText +
             fillText + fillText + fillText +
             fillText + fillText + fillText +
             fillText + fillText + fillText)),

  new Run(
    new Drawing(
      new wp.Inline(

        new wp.Extent()
        {
          Cx = imageWidthEMU,
          Cy = imageHeightEMU
        },

        new wp.EffectExtent()
        {
          LeftEdge = 19050L,
          TopEdge = 0L,
          RightEdge = 9525L,
          BottomEdge = 0L
        },

        new wp.DocProperties()
        {
          Id = (UInt32Value)1U,
          Name = "Inline Text Wrapping Picture",
          Description = imageFileName
        },

        new wp.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 = imageFileName
                },
                new pic.NonVisualPictureDrawingProperties()),

              new pic.BlipFill(
                new a.Blip() { Embed = "rId1" },
                new a.Stretch(
                  new a.FillRectangle())),

              new pic.ShapeProperties(
                new a.Transform2D(
                  new a.Offset() { X = 0L, Y = 0L },
                  new a.Extents()
                  {
                      Cx = imageWidthEMU,
                      Cy = imageHeightEMU
                  }),

                new a.PresetGeometry(
                  new a.AdjustValueList()
                ) { Preset = a.ShapeTypeValues.Rectangle }))
          )
          { Uri = GraphicDataUri })
      )
      {
          DistanceFromTop = (UInt32Value)0U,
          DistanceFromBottom = (UInt32Value)0U,
          DistanceFromLeft = (UInt32Value)0U,
          DistanceFromRight = (UInt32Value)0U
      })),

    new Run(
        new Text(fillText + fillText + fillText +
                 fillText + fillText + fillText +
                 fillText + fillText + fillText +
                 fillText + fillText + fillText +
                 fillText + fillText + fillText +
                 fillText + fillText + fillText))
)

The second paragraph contains the floating image. The code adds a Run to the paragraph that contains a Drawing element with a child Anchor element that specifies the details of the floating image. The floating image is positioned centered horizontally relative to the margins and vertically 1.5 inches from the top of the paragraph. Just as with the inline image the relationship to the image part that contains the image bytes is specified with a Blip element that has it's Embed attribute set to the relationship ID of the image part.

Floating images use a wrapping polygon to specify how text should flow around the image. Image wrapping polygons in Microsoft Word use a fixed coordinate space that is 21600 units x 21600 units. Coordinate (0,0) is the upper left corner of the image and coordinate (21600,21600) is the lower right corner of the image. Microsoft Word scales the size of the wrapping polygon units to fit the size of the image. The 21600 value is a legacy artifact from the drawing layer of early versions of Microsoft Office.

The following floating-image code snippet specifies a triangular wrapping polygon. To generically calculate the end points of the wrapping polygon for different sized images the code calculates how many wrapping polygon units there are per inch. This is done in both the horizontal and vertical directions since they will not be the same for non-square images. It then uses these values to specify the coordinates of the wrapping polygon end points. The 914400 value used in the calculations is the number of English Metric Units (EMU) in one inch.

double imageWidthInInches = imageWidthEMU / 914400.0;
double imageHeightInInches = imageHeightEMU / 914400.0;

long horizontalWrapPolygonUnitsPerInch =
  (long)(21600L / imageWidthInInches);

long verticalWrapPolygonUnitsPerInch =
  (long)(21600L / imageHeightInInches);

new Paragraph(

  new ParagraphProperties(
    new Justification() { Val = JustificationValues.Both },

  new Run(

    new Drawing(

      new wp.Anchor(

        new wp.SimplePosition() { X = 0L, Y = 0L },

        // Center the image horizontally on the page.
        new wp.HorizontalPosition(
          new wp.HorizontalAlignement("center")
        )
        { RelativeFrom =
          wp.HorizontalRelativePositionValues.Margin },

        // Position the image 1.5" from the top of the
        // paragraph.
        new wp.VerticalPosition(
          new wp.PositionOffset("1371600")
        )
        { RelativeFrom =
          wp.VerticalRelativePositionValues.Paragraph },

        new wp.Extent()
        { Cx = imageWidthEMU,
          Cy = imageHeightEMU },

        new wp.EffectExtent()
        { LeftEdge = 0L,
          TopEdge = 0L,
          RightEdge = 0L,
          BottomEdge = 0L },

        new wp.WrapTight(
          new wp.WrapPolygon(
            // Create a wrapping polygon that is a triangle.
            // Start point is 1" to the left and .5" above
            // the upper left corner of the image.
            new wp.StartPoint()
            { X = -horizontalWrapPolygonUnitsPerInch,
              Y = -verticalWrapPolygonUnitsPerInch / 2
            },
            // Next point is centered horizontally on the image
            // and 1" below the bottom of the image.
            new wp.LineTo()
            { X = 10800,
              Y = 21600L + verticalWrapPolygonUnitsPerInch
            },
            // Next point is 1" to the right and .5" above
            // the upper right corner of the image.
            new wp.LineTo() 
            { X = 21600L + horizontalWrapPolygonUnitsPerInch,
              Y = -verticalWrapPolygonUnitsPerInch / 2 }
          ) { Edited = false }
        ){ WrapText = wp.WrapTextValues.BothSides },
        
        new wp.DocProperties()
        { Id = (UInt32Value)2U,
          Name = "Tight Text Wrapping Picture",
          Description = "imageFileName" },

        new wp.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 = "imageFileName" },
                new pic.NonVisualPictureDrawingProperties()),

              new pic.BlipFill(
                new a.Blip() { Embed = "rId1" },
                new a.Stretch(
                  new a.FillRectangle())),

              new pic.ShapeProperties(

                new a.Transform2D(
                  new a.Offset() { X = 0L, Y = 0L },

                  new a.Extents()
                  { Cx = imageWidthEMU,
                    Cy = imageHeightEMU }),
                
                new a.PresetGeometry(
                  new a.AdjustValueList()
                )
                { Preset = a.ShapeTypeValues.Rectangle }
              )
            )
      )
      { Uri = GraphicDataUri })
    )
    { DistanceFromTop = (UInt32Value)0U,
      DistanceFromBottom = (UInt32Value)0U,
      DistanceFromLeft = (UInt32Value)114300U,
      DistanceFromRight = (UInt32Value)114300U,
      SimplePos = false,
      RelativeHeight = (UInt32Value)251658240U,
      BehindDoc = true,
      Locked = false,
      LayoutInCell = true,
      AllowOverlap = true })),

      new Run(
        new Text(fillText + fillText + fillText +
                 fillText + fillText + fillText +
                 fillText + fillText + fillText +
                 fillText + fillText + fillText +
                 fillText + fillText + fillText +
                 fillText + fillText + fillText +
                 fillText + fillText + fillText +
                 fillText + fillText + fillText +
                 fillText + fillText + fillText +
                 fillText + fillText + fillText +
                 fillText + fillText + fillText +
                 fillText + fillText + fillText +
                 fillText + fillText + fillText +
                 fillText + fillText + fillText +
                 fillText + fillText + fillText))
  )
)

The Image part that contains the embedded image and is referenced by the Blip elements is generated by the GenerateImagePart method. The method opens a FileStream on the image file and reads the file contents into a byte array. It then opens the content data stream on the image part created by the AddParts method and uses a BinaryWriter to write the image file contents to the stream. The method also calculates the horizontal and vertical extents of the image in EMU. You can use those measurements to set the attributes related to those extents in the drawing elements of the inline and floating images.

public static void GenerateImagePart(OpenXmlPart part,
  string imageFilePath, ref long imageWidthEMU,
  ref long imageHeightEMU)
{
  byte[] imageFileBytes;
  Bitmap imageFile;

  // Open a stream on the image file and read it's contents. The
  // following code will generate an exception if an invalid file
  // name is passed.
  using (FileStream fsImageFile = File.OpenRead(imageFilePath))
  {
    imageFileBytes = new byte[fsImageFile.Length];
    fsImageFile.Read(imageFileBytes, 0, imageFileBytes.Length);

    imageFile = new Bitmap(fsImageFile);
  }

  // Get the dimensions of the image in English Metric Units (EMU)
  // for use when adding the markup for the image to the document.
  imageWidthEMU =
    (long)(
    (imageFile.Width / imageFile.HorizontalResolution) * 914400L);
  imageHeightEMU =
    (long)(
    (imageFile.Height / imageFile.VerticalResolution) * 914400L);

  // Write the contents of the image to the ImagePart.
  using (BinaryWriter writer = new BinaryWriter(part.GetStream()))
  {
    writer.Write(imageFileBytes);
    writer.Flush();
  }
}
NoteNote

When you use the Open XML SDK 2.0 for Microsoft Office to create a document-generation solution, it is best practice to create a template document first, and then use DocumentReflector, a tool that comes with the SDK. DocumentReflector can generate C# code that uses the SDK typesafe classes to reproduce your template document and the functionality that it contains. You can then use that code to help you add functionality or to help you understand the Open XML document parts and relationships that are required to implement a specific document feature. For more information about best practices and the Open XML SDK 2.0 for Microsoft Office, see Erika Ehrli's blog entry Getting Started Best Practices.

Explore It