Image Operations Using Word Document in C#

Introduction

In this article, you can learn various image operations using a Word document in C# programming. Images are more attractive for reading the document. Images are related to the contents. Sometimes, an image can describe some content more clearly, like using a chart to show data changes in a period.

Spire.Doc for .NET

It is a professional .NET Word component to quickly generate, open, modify, and save Word documents without using Microsoft Office Automation and enables users to insert an image into Word and set its size depending on the page using C#. This guide introduces an easy method for inserting an image via Spire.Doc for .NET.

The following are the operations we are learning.

  1. Insert an image into a Word Document.
  2. Extract images from a Word Document.
  3. Replace images with texts in a Word Document.

To do these operations, you need to create a Word document. Here I used Spire.Doc to create the document and perform the preceding operations.

Create a ConsoleApplication for the demo. Use the following procedure.

  1. Open Visual Studio
  2. "File" -> "New" -> "Project..."
  3. Select C# Language, then select ConsoleApplication and name it “ImageOperationInWord”
  4. Click OK.

How to Insert Image in Word Document?

First, create a new Word document and add a section and page for this document. Then, use the p.AppendPicture(Image) method to insert an image into the new paragraph. Set the height and width property for the image to format its size. Use the following code to insert the image into Word by using C#.

Namespaces used

using Spire.Doc;  
using Spire.Doc.Documents;  
using Spire.Doc.Fields;  
using System.Drawing; 

 Example

private static void InsertImage()  
{  
    //Create Document  
    Document document = new Document();  
    Section s = document.AddSection();  
    Paragraph p = s.AddParagraph();  
  
    //Insert Image and Set Its Size  
    DocPicture Pic = p.AppendPicture(Image.FromFile(@"D:\C# Corner.png"));  
    Pic.Width = 500;  
    Pic.Height = 500;  
  
    //Save and Launch  
    document.SaveToFile("Image.docx", FileFormat.Docx);  
    System.Diagnostics.Process.Start("Image.docx");  
}  

Output

Insert Image

Extract Images from Word Document

In this, you learn how to extract images from an existing Word document and save them to a specified path in C#. An image is one kind of document object that belongs to paragraph items. Spire.Doc for .NET provides a DocumentObject class to store images in a Document and provides a DocPicture class to get and set images of a document. Here I used ExtractImages.docx, and in it, I saved two images. In the output image, you can see the Red color box. There are two images from the Word document.

Example

private static void ExtractImages()  
{  
    //Load document  
    Document document = new Document(@"D:\ExtractImages.docx");  
    int index = 0;  
  
    //Get Each Section of Document  
    foreach (Section section in document.Sections)  
    {  
        //Get Each Paragraph of Section  
        foreach (Paragraph paragraph in section.Paragraphs)  
        {  
            //Get Each Document Object of Paragraph Items  
            foreach (DocumentObject docObject in paragraph.ChildObjects)  
            {  
                //If Type of Document Object is Picture, Extract.  
                if (docObject.DocumentObjectType == DocumentObjectType.Picture)  
                {  
                    DocPicture pic = docObject as DocPicture;  
                    String imgName = String.Format(@"D:\Extracted_Image-{0}.png", index);  
  
                    //Save Image  
                    pic.Image.Save(imgName, System.Drawing.Imaging.ImageFormat.Png);  
                    index++;  
                }  
            }  
        }  
    }  
}  

Output

Extract Images

Replace images with texts in Word Document

Let us see how Spire.Doc can help developers resolve their problems related to programming with Office technology. According to the description, the poster wants to replace each image in the Word file with “C# Corner Demo Example - {image index}” correspondingly. However, we would like to provide a solution with the following sample code.

Example

private static void ReplaceImageWithText()  
{  
    Document doc = new Document(@"D:\ExtractImages.docx");  
    int j = 1;  
    foreach (Section sec in doc.Sections)  
    {  
        foreach (Paragraph para in sec.Paragraphs)  
        {  
            List<DocumentObject> images = new List<DocumentObject>();  
            foreach (DocumentObject docObj in para.ChildObjects)  
  
            {  
                if (docObj.DocumentObjectType == DocumentObjectType.Picture)  
                {  
                    images.Add(docObj);  
                }  
            }  
            foreach (DocumentObject pic in images)  
            {  
                int index = para.ChildObjects.IndexOf(pic);  
                TextRange range = new TextRange(doc);  
                range.Text = string.Format("C# Corner Demo Example {0}", j);  
                para.ChildObjects.Insert(index, range);  
                para.ChildObjects.Remove(pic);  
                j++;  
            }  
        }  
    }  
    doc.SaveToFile(@"D:\result.docx", FileFormat.Docx);  
    System.Diagnostics.Process.Start(@"D:\result.docx");  
}  

Before replacing the images.

Extract Images from word word document

After replacing images with texts

replacing images

Note. For detailed code, please download the Zip file attached above.

Summary

I hope you now understand how to do operations on images in Word documents programmatically. If you have any suggestion regarding this article, then please contact me.


Similar Articles