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 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.

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 image to format its size. Use the following code to insert the image into Word by using C#.

Namespaces used:

  1. using Spire.Doc;  
  2. using Spire.Doc.Documents;  
  3. using Spire.Doc.Fields;  
  4. using System.Drawing;  
Code to create and insert an image into a Word document:
  1. private static void InsertImage()  
  2. {  
  3.     //Create Document  
  4.     Document document = new Document();  
  5.     Section s = document.AddSection();  
  6.     Paragraph p = s.AddParagraph();  
  7.   
  8.     //Insert Image and Set Its Size  
  9.     DocPicture Pic = p.AppendPicture(Image.FromFile(@"D:\C# Corner.png"));  
  10.     Pic.Width = 500;  
  11.     Pic.Height = 500;  
  12.   
  13.     //Save and Launch  
  14.     document.SaveToFile("Image.docx", FileFormat.Docx);  
  15.     System.Diagnostics.Process.Start("Image.docx");  
  16. }  
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.

Code to extract images from Word document:
  1. private static void ExtractImages()  
  2. {  
  3.     //Load document  
  4.     Document document = new Document(@"D:\ExtractImages.docx");  
  5.     int index = 0;  
  6.   
  7.     //Get Each Section of Document  
  8.     foreach (Section section in document.Sections)  
  9.     {  
  10.         //Get Each Paragraph of Section  
  11.         foreach (Paragraph paragraph in section.Paragraphs)  
  12.         {  
  13.             //Get Each Document Object of Paragraph Items  
  14.             foreach (DocumentObject docObject in paragraph.ChildObjects)  
  15.             {  
  16.                 //If Type of Document Object is Picture, Extract.  
  17.                 if (docObject.DocumentObjectType == DocumentObjectType.Picture)  
  18.                 {  
  19.                     DocPicture pic = docObject as DocPicture;  
  20.                     String imgName = String.Format(@"D:\Extracted_Image-{0}.png", index);  
  21.   
  22.                     //Save Image  
  23.                     pic.Image.Save(imgName, System.Drawing.Imaging.ImageFormat.Png);  
  24.                     index++;  
  25.                 }  
  26.             }  
  27.         }  
  28.     }  
  29. }  
Output

Extract Images

Replace images with texts in Word Document

Let us see how Spire.Doc can help developers to 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.

Code for replace images with texts in Word document:
  1. private static void ReplaceImageWithText()  
  2. {  
  3.     Document doc = new Document(@"D:\ExtractImages.docx");  
  4.     int j = 1;  
  5.     foreach (Section sec in doc.Sections)  
  6.     {  
  7.         foreach (Paragraph para in sec.Paragraphs)  
  8.         {  
  9.             List<DocumentObject> images = new List<DocumentObject>();  
  10.             foreach (DocumentObject docObj in para.ChildObjects)  
  11.   
  12.             {  
  13.                 if (docObj.DocumentObjectType == DocumentObjectType.Picture)  
  14.                 {  
  15.                     images.Add(docObj);  
  16.                 }  
  17.             }  
  18.             foreach (DocumentObject pic in images)  
  19.             {  
  20.                 int index = para.ChildObjects.IndexOf(pic);  
  21.                 TextRange range = new TextRange(doc);  
  22.                 range.Text = string.Format("C# Corner Demo Example {0}", j);  
  23.                 para.ChildObjects.Insert(index, range);  
  24.                 para.ChildObjects.Remove(pic);  
  25.                 j++;  
  26.             }  
  27.         }  
  28.     }  
  29.     doc.SaveToFile(@"D:\result.docx", FileFormat.Docx);  
  30.     System.Diagnostics.Process.Start(@"D:\result.docx");  
  31. }  
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.

Contents used from Spire.Doc for more information click here.