Replace Image In Word Document Using C#


Recently, I have been working on a project that requires implementing the functionality to find and replace images in a Word document using C#. Our project requires our software to support multiple standard templates in Word format.

With the help of MS word, we can do many types of tasks, we can create a resume, write a letter, design wedding cards, write any notice, and in addition, we can do a lot of work. In MS Word, we can design a written word so that it looks more attractive, with the help of this we can increase the size of the words, change the font, make any words bold, etc.
Using MS word we can convert the given letters into different types of colors. With the help of MS Word, we can create any type of document and after editing it, we can do its formatting, open it and view it and we can also share that document.

I created a word template as you can see in the below image. In which we have some content and image. Now our task is to Replace Image with new Image in Word using C#. So lets’ do that.

replcaeimage

Add a windows project with a button

Winform

Step 1: Install open XML Nuget package for editing the WordDocument

Install-Package DocumentFormat.OpenXml -Version 2.15.0

Write the below code on button Click

 private void button2_Click(object sender, EventArgs e)
        {
// original template path
var inputFile = @"E:\WordFile\Template.docx";
//modify template path where we save modify word template
var outputFile = @"E:\WordFile\outputword.docx";
string imagePath = @"E:\WordFile\replacenewimg.JPG";
//check if file exist or not
if (System.IO.File.Exists(inputFile))
            {
                WordDocumentService wordDocumentService = new WordDocumentService();
if (System.IO.File.Exists(inputFile))
                {
using (WordprocessingDocument doc = WordprocessingDocument.Open(inputFile, true)) //open source word file
                    {
                        Document document = doc.MainDocumentPart.Document;
                        OpenXmlPackage res = doc.SaveAs(outputFile); // copy it to outfile path for editing
                        res.Close();
                    }
using (WordprocessingDocument wordprocessingDocument =
               WordprocessingDocument.Open(outputFile, true))
                    {
//get all image inside the document
                        IEnumerable<Drawing> drawings = wordprocessingDocument.MainDocumentPart.Document.Descendants<Drawing>().ToList();
foreach (Drawing drawing in drawings)
                        {
                            DocProperties dpr = drawing.Descendants<DocProperties>().FirstOrDefault();
//this very importent here we are replacing the image by checking the name
if (dpr != null && dpr.Name == "Picture 2")
                            {
foreach (DocumentFormat.OpenXml.Drawing.Blip b in drawing.Descendants<DocumentFormat.OpenXml.Drawing.Blip>().ToList())
                                {
                                    OpenXmlPart imagePart = wordprocessingDocument.MainDocumentPart.GetPartById(b.Embed);
using (var writer = new BinaryWriter(imagePart.GetStream()))
                                    {
                                        writer.Write(File.ReadAllBytes(imagePath));
                                    }
                                }
                            }
                        }
                    }

                }

            }
        }

*Important Note

  • Original Template Path: the path to the original Word document template file (Template.docx) stored on the local file system.
  • Modified Template Path: This line specifies the path where the modified Word document template file (outputword.docx) will be saved after making changes
  • Image Path: This variable imagePath specifies the path to the new image file (replacenewimg.JPG) that will replace the existing image in the Word document.
  • Check if File Exists: This if statement checks if the original template file exists at the specified path before proceeding with any operations.
  • WordDocumentService Initialization: An instance of the WordDocumentService class is created to utilize its methods for modifying the Word document.
  • Open Original Word Document: The original Word document (Template.docx) is opened for editing using the WordprocessingDocument.Open method. It's opened in write mode (true).
  • Save Copy of Original Document: The original document is saved as a copy to the specified output file path (outputword.docx). This is done using the SaveAs method of WordprocessingDocument, and the resulting package is stored in the res variable.
  • Close Original Document: The original document (Template.docx) is closed using the Close method on the res package.
  • Open Modified Word Document: The copied Word document (outputword.docx) is opened for further modification using the WordprocessingDocument.Open method.
  • Get All Images in the Document: The code retrieves all images contained within the Word document by querying the document's Drawing elements.
  • Replace Image: For each image found in the document, the code checks if its name matches a predefined value (Picture 2). If a match is found, it replaces the image with the new image specified by imagePath. This is achieved by obtaining the corresponding image part from the document and writing the binary data of the new image file to it.

Put debugger on the below line and get the name property of image in the word document and the put condition in the code which image you want to replace.

Below code demonstrates how to find and replace images in a Word document using C# and the Open XML SDK.

ExtractimageAs you can see in the code, first we are getting all images in a word document and then iterating through each image. and then we put condition which image we want to replace in case we have multiple images in the document.

using (WordprocessingDocument wordprocessingDocument =
               WordprocessingDocument.Open(outputFile, true))
                    {
//get all image inside the document
                        IEnumerable<Drawing> drawings = wordprocessingDocument.MainDocumentPart.Document.Descendants<Drawing>().ToList();
foreach (Drawing drawing in drawings)
                        {
                            DocProperties dpr = drawing.Descendants<DocProperties>().FirstOrDefault();
//this very importent here we are replacing the image by checking the name
if (dpr != null && dpr.Name == "Picture 2")
                            {
foreach (DocumentFormat.OpenXml.Drawing.Blip b in drawing.Descendants<DocumentFormat.OpenXml.Drawing.Blip>().ToList())
                                {
                                    OpenXmlPart imagePart = wordprocessingDocument.MainDocumentPart.GetPartById(b.Embed);
using (var writer = new BinaryWriter(imagePart.GetStream()))
                                    {
                                        writer.Write(File.ReadAllBytes(imagePath));
                                    }
                                }
                            }
                        }
                    }

Output

OutputReplaceimage

* if you have a question please comment

In MS Word, we can share a single document with many people at once, in which we can save the document and also delete it and copy paste it.In today’s time MS word is being used all over the world.MS Word is mostly used in offices, apart from this MS World is also used in schools and colleges.

With the help of MS Word, we can create and format the documents and design it and give them a new look. If you have to do the following types of tasks on a computer such as typing, data entry, accounting, mailing, etc., then you should have the knowledge of MS Word because MS Word is a basic computer knowledge that can be used to work in the computer. It is done in almost all types of fields.