News Category

Replace Image with new Image in Word using C#

2017-05-23 08:50:54 Written by  support iceblue
Rate this item
(0 votes)

Replacing image with text or image in a Word document is possible in Spire.Doc. We've already illustrated how to replace image with text, in this tutorial, we will show you how to replace a specified image with another image using Spire.Doc and C#.

Below is the original Word document before replacing image:

Replace Image with new Image in Word using C#

Code Snippet:

Step 1: Load the Word document.

Document document = new Document("Input.docx");

Step 2: Replace the image which title is "Figure 1" with new image.

//Loop through the paragraphs of the section
foreach (Paragraph paragraph in document.Sections[0].Paragraphs)
{
    //Loop through the child elements of paragraph
    foreach (DocumentObject docObj in paragraph.ChildObjects)
    {
        if (docObj.DocumentObjectType == DocumentObjectType.Picture)
        {
            DocPicture picture = docObj as DocPicture;
            if (picture.Title == "Figure 1")
            {
                //Replace the image
                picture.LoadImage(Image.FromFile("PinkRoses.jpg"));
            }
        }
    }
}

Step 3: Save and close the document.

document.SaveToFile("ReplaceImage.docx");
document.Close();

The resultant document looks as follows:

Replace Image with new Image in Word using C#

Full code:

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

namespace Replace_Image
{
    class Program
    {        
        static void Main(string[] args)
        {
            //Load the Word document
            Document document = new Document("Input.docx");

            //Loop through the paragraphs of the section
            foreach (Paragraph paragraph in document.Sections[0].Paragraphs)
            {
                //Loop through the child elements of paragraph
                foreach (DocumentObject docObj in paragraph.ChildObjects)
                {
                    if (docObj.DocumentObjectType == DocumentObjectType.Picture)
                    {
                        DocPicture picture = docObj as DocPicture;
                        if (picture.Title == "Figure 1")
                        {
                            //Replace the image
                            picture.LoadImage(Image.FromFile("PinkRoses.jpg"));
                        }
                    }
                }
            }

            //Save and close the document
            document.SaveToFile("ReplaceImage.docx");
            document.Close();            
        }
    }
}

Additional Info

  • tutorial_title:
Last modified on Friday, 03 September 2021 03:47