Recently I’m working on a project in which I need to implement the Find And Replace Image In Word Document Using C#. Our project requirement is that our software can have 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.
Add a windows project with a button
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
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.
As 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
* 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.
The post Replace image in word document using C# appeared first on Software Development | Programming Tutorials.
Read More Articles
- Write a value which contain comma to a CSV file in c#?
- Reading CSV File with cells containing commas c#
- Split CSV with columns may contain ‘,’ Comma C#
- [Simple Way]-Cascading DropDownList in Asp.Net Mvc Using Jquery Ajax
- [Simple Way]-How to get data from database using JQuery Ajax in asp net MVC
- [Simple Way]-ASP.NET Core Upload Multiple File Web API model
- [Simple Way]- Image Upload in .NET Core Web API
- [Easy Way]-Receive File and other form data together in ASP.NET Core Web API
- Replace image in word document using C#
- How to add new rows to an existing word document table in C#
- How can I add an external image to a word document using OpenXml?
- Insert an image into word document using open xml and C#
- Adding image to word document using OpenXML
- How can I form a Word document using stream of bytes
- How to write an image from byte[] into MS WORD using C# Windows application
- How can I programmatically delete a line from a Word document using c#?
- How do you access the numbering of an outline in a Word Document using C# and OpenXml?
- Using C# to create a Word document from an existing template
- Is it possible to insert pieces of RTF text into a Word document (.docx) using OpenXml?
- Loading an online image in a word document
- Iterating over Word Document Fields using ComAutomationFactory in Silverlight 4
- Adding an Embedded Chart to word document using open xml
- How can I get all unloaded images in word document using Aspose.Word
- How can I remove the readonly attribute of a word document using c#?
- How to set border of Shapes inside Word Document to None using c#?
- How to replace text at bookmark in a Word document
- How to copy content of Rich Text Content Control from Word document and remove the control itself using Open XML SDK
- How to iterate and count Revisions in a Word document using C#?
- How to split a Word document by section using C# and the Open XML SDK?
- Faster way to create Word document in C# using Interop
- How to insert a picture/text label at specific coordinates in a word 2007 document using C#?
- Replace MergeFields in a Word 2003 document and keep style
- Extracting field values from a Word Document using openxml SDK
- OpenXML replace specific customxml part of word document
- Reading and modifying Microsoft Word document using C#
- C# Windows Service keeps file locked using FlatDocument an example from MSDN "Find and Replace text in a Word document"
- Create word document with headings using c#
- how to change font size of word document using .net
- How to update but not replace a document using updateOne() of the MongoDB-driver for .NET
- need a document to extract text from image using onenote Interop?
- Read JSON property name from JsonContract
- How to restart an embedded, NETMF C# program on error?
- FileSystemWatcher Exception - The network BIOS command limit has been reached
- PDF printing in .NET Core using System.Drawing.Printing
- Remove 'None' from textbox without using codebehind
- How do you pass an OutputStream as an InputStream in C#?
- Passing Command-line arguments from C# to a external exe
- SetWindowLong Enable/Disable Click through form
- Ignore mouse click and send keyboard Input to external application
- Counting items in specific dimension of multidimensional array (C#)
- How to set and get tag in xaml dynamically?
- Building, and Publishing, and User-Data (oh my!)
- Unity download a video from server and save it
- Reflection.Emit unsafe code
- C# Raw Sockets Port Forwarding
- Nested Foreach loop runs too many times - C#
- Exception handling in WinForm
- What this C# code mean?
- Failing to read String value from an excel column
- Remove events without knowing their names