C#/VB.NET: Replace Images in Word Documents
Sometimes you may encounter a situation where you need to replace images in a Word document. For example, if you are creating a resume from a template, you may need to replace the profile picture in the template with your own photo. In this article, we will show you how to replace images in a Word document in C# and VB.NET using Spire.Doc for .NET.
Install Spire.Doc for .NET
To begin with, you need to add the DLL files included in the Spire.Doc for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.Doc
Replace Image with New Image in Word in C# and VB.NET
To replace an image in a Word document with another image, you need to loop through the elements of the document, find the images and add them to a list, then get the image that you want to replace from the list and call the DocPicture.LoadImage() method to replace it with another image.
The following are the detailed steps:
- Initialize an instance of the Document class.
- Load a Word document using Document.LoadFromFile() method.
- Initialize an instance of the List class.
- Iterate through all sections in the document.
- Iterate through all paragraphs in each section.
- Iterate through all child objects in each paragraph.
- Find the images and add them to the list.
- Get a specific image from the list and replace it with another image using DocPicture.LoadImage() method.
- Save the result document using Document.SaveToFile() method.
- C#
- VB.NET
using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using System.Collections.Generic; using System.Drawing; namespace ReplaceImageWithImage { internal class Program { static void Main(string[] args) { //Initialize an instance of the Document class Document doc = new Document(); //Load a Word document doc.LoadFromFile("Sample.docx"); //Initialize an instance of the List class List pictures = new List(); //Iterate through all sections in the document foreach (Section sec in doc.Sections) { //Iterate through all paragraphs in each section foreach (Paragraph para in sec.Paragraphs) { //Iterate through all child objects in each paragraph foreach (DocumentObject docObj in para.ChildObjects) { //Find the images and add them to the list if (docObj.DocumentObjectType == DocumentObjectType.Picture) { pictures.Add(docObj); } } } } //Replace the first picture in the list with another image DocPicture picture = pictures[0] as DocPicture; picture.LoadImage(Image.FromFile(@"doc.png")); //Save the result document doc.SaveToFile("ReplaceWithNewImage.docx", FileFormat.Docx2013); } } }
Replace Image with Text in Word in C# and VB.NET
Spire.Doc doesn’t provide a direct method to replace image with text, but you can achieve this task by inserting the text at the image location and then removing the image from the document.
The following steps demonstrate how to replace all images in a Word document with text:
- Initialize an instance of the Document class.
- Load a Word document using Document.LoadFromFile() method.
- Iterate through all sections in the document.
- Iterate through all paragraphs in each section.
- Initialize an instance of the List class.
- Iterate through all child objects in each paragraph.
- Find the images and add them to the list.
- Iterate through the images in the list.
- Get the index of the image in the paragraph using Paragraph.ChildObjects.Indexof() method.
- Initialize an instance of TextRange class and set text for the text range through TextRange.Text property.
- Insert the text range at the image location using Paragraph.ChildObjects.Insert() method.
- Remove the image from the paragraph using Paragraph.ChildObjects.Remove() method.
- Save the result document using Document.SaveToFile() method.
- C#
- VB.NET
using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using System.Collections.Generic; namespace ReplaceImageWithText { internal class Program { static void Main(string[] args) { //Initialize an instance of the Document class Document doc = new Document(); //Load a Word document doc.LoadFromFile("Sample.docx"); int j = 1; //Iterate through all sections in the document foreach (Section sec in doc.Sections) { //Iterate through all paragraphs in each section foreach (Paragraph para in sec.Paragraphs) { //Initialize an instance of the List class List pictures = new List(); //Find the images and add them to the list foreach (DocumentObject docObj in para.ChildObjects) { if (docObj.DocumentObjectType == DocumentObjectType.Picture) { pictures.Add(docObj); } } //Iterate through all images in the list and replace them with text "Here is image {image index}" foreach (DocumentObject pic in pictures) { int index = para.ChildObjects.IndexOf(pic); TextRange range = new TextRange(doc); range.Text = string.Format("Here is image-{0}", j); para.ChildObjects.Insert(index, range); para.ChildObjects.Remove(pic); j++; } } } //Save the result document doc.SaveToFile("ReplaceWithText.docx", FileFormat.Docx); } } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Insert Image at Specified Location in C#, VB.NET
Image can add interest and take effect to your Word documents. Suppose you've written an article introducing a city about its beautiful scenery. Just using words describe, you cannot present perfect scenery to your readers, because that page of text looks indistinct and dull. You need image to embellish your scenery.
Spire.Doc for .NET, a professional .NET word component to fast generate, open, modify and save Word documents without using MS Office Automation, enables users to insert image into Word document and set its size according to page by using C#.NET. This guide introduces an easy method how to insert image via Spire.Doc for .NET.
At first, create new Word document and add section, paragraph for this document. Then, insert image in the new created paragraph. You can set this image's size, position, rotate it and choice the wrapping-style about the text. Download and Install Spire.Doc for .NET. Use the following code to insert image in Word by using C#.
The sample demo shows how to insert an image into a document.
using System; using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using System.Drawing; namespace Insert_image_to_Word_Document { class Program { static void Main(string[] args) { //Open a blank word document as template Document document = new Document(@"Blank.doc"); Section section = document.Sections[0]; Paragraph paragraph = section.Paragraphs.Count > 0 ? section.Paragraphs[0] : section.AddParagraph(); paragraph.AppendText("The sample demonstrates how to insert an image into a document."); paragraph.ApplyStyle(BuiltinStyle.Heading2); paragraph = section.AddParagraph(); //get original image Bitmap p = new Bitmap(Image.FromFile(@"Word.jpg")); //rotate image and insert image to word document p.RotateFlip(RotateFlipType.Rotate90FlipX); DocPicture picture = document.Sections[0].Paragraphs[0].AppendPicture(p); //set image's position picture.HorizontalPosition = 50.0F; picture.VerticalPosition = 60.0F; //set image's size picture.Width = 200; picture.Height = 200; //set textWrappingStyle with image; picture.TextWrappingStyle = TextWrappingStyle.Through; //Save doc file. document.SaveToFile("Sample.doc", FileFormat.Doc); //Launching the MS Word file. System.Diagnostics.Process.Start("Sample.doc"); } } }
If you have finished the tutorial Spire.Doc Quick Start, the steps above will be simpler.
With Spire.Doc, you can insert an image into your Word documents and do more same thing in your ASP.NET, WPF and Silverlight applications without Word automation and any other third party add-ins.
Extract Images from Word in C#, VB.NET
Solution in this guide demonstrates how to extract images from an existing Word document and save them to a specified path in C# and VB.NET via Spire.Doc for .NET.
Image is one kind of document objects which belongs to paragraph items. Spire.Doc for .NET provides a DocumentObject class to store images in Document. And also provides a DocPicture class to get and set images of document. Download and Install Spire.Doc for .NET. Follow steps to extract images from Word.
- Get each Paragraph of each Section in Document.
- Get each DocumentObject of ChildObjects in Paragraph.
- If the gotten DocumentObjectType is Picture, initialize a DocPicture class instance and assign the DocumentObject as value for this instance.
- Initialize a String class instance to name extracted image instead of its original name by invoking String.Format(String format, object arg0)
- Invoke DocPictrue.Image.Save(String, ImageFormat) method to save images.
using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using System; namespace ExtractImage { class Program { static void Main(string[] args) { //Load document Document document = new Document(@"E:\Work\Documents\WordDocuments\Spire.Doc for .NET.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 picture = docObject as DocPicture; //Name Image String imageName = String.Format(@"images\Image-{0}.png", index); //Save Image picture.Image.Save(imageName, System.Drawing.Imaging.ImageFormat.Png); index++; } } } } } } }
Imports Spire.Doc Imports Spire.Doc.Documents Imports Spire.Doc.Fields Namespace ExtractImage Class Program Private Shared Sub Main(args As String()) 'Load document Dim document As New Document("E:\Work\Documents\WordDocuments\Spire.Doc for .NET.docx") Dim index As Integer = 0 'Get Each Section of Document For Each section As Section In document.Sections 'Get Each Paragraph of Section For Each paragraph As Paragraph In section.Paragraphs 'Get Each Document Object of Paragraph Items For Each docObject As DocumentObject In paragraph.ChildObjects 'If Type of Document Object is Picture, Extract. If docObject.DocumentObjectType = DocumentObjectType.Picture Then Dim picture As DocPicture = TryCast(docObject, DocPicture) 'Name Image Dim imageName As [String] = [String].Format("images\Image-{0}.png", index) 'Save Image picture.Image.Save(imageName, System.Drawing.Imaging.ImageFormat.Png) index += 1 End If Next Next Next End Sub End Class End Namespace
After debugging, all the extracted images are saved in a specified path. Open the directory, the images will be found.
Spire.Doc, an easy-to-use component to operate Word document, allows developers to fast generate, write, edit and save Word (Word 97-2003, Word 2007, Word 2010) in C# and VB.NET for .NET, Silverlight and WPF.
C#/VB.NET: Insert Images in Word
Images in Word documents are often closely related to the textual content. Compared with documents full of text, documents with images are more illustrative and attractive. In this article, you will learn how to programmatically insert images in a Word document using Spire.Doc for .NET. With this professional Word library, you can also set the image size, position as well as wrapping styles.
- Insert Images and Set their Wrapping Styles in a Word Document
- Insert an Image at a Specified Location in a Word document
Install Spire.Doc for .NET
To begin with, you need to add the DLL files included in the Spire.Doc for .NET package as references in your .NET project. The DLLs files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.Doc
Insert Images and Set their Wrapping Styles in a Word Document
Spire.Doc for .NET supports common wrapping styles such as In Line with Text, Square, Tight, Through, Top and Bottom, Behind the Text as well as In Front of Text. Below are the detailed steps to insert images and then set their wrapping styles.
- Create a Document instance.
- Load a sample Word document using Document.LoadFromFile() method.
- Get the first section of the Word Document using Document.Sections[] property.
- Get a specified paragraph of the section using Section.Paragraphs[] property.
- Load an image and insert the image in the specified paragraph using Paragraph.AppendPicture() method.
- Set the wrapping style of the image using DocPicture.TextWrappingType property.
- Save the document to another file using Document.SaveToFile() method.
- C#
- VB.NET
using System.Drawing; using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; namespace WordImage { class ImageinWord { static void Main(string[] args) { //Create a Document instance Document document = new Document(); //Load a sample Word document document.LoadFromFile("input.docx"); //Get the first section Section section = document.Sections[0]; //Get two specified paragraphs Paragraph para1 = section.Paragraphs[5]; Paragraph para2 = section.Paragraphs[9]; //Insert images in the specified paragraphs DocPicture Pic1 = para1.AppendPicture(Image.FromFile(@"C:\Users\Administrator\Desktop\pic1.jpg")); DocPicture Pic2 = para2.AppendPicture(Image.FromFile(@"C:\Users\Administrator\Desktop\pic2.png")); //Set wrapping styles to Square and Inline respectively Pic1.TextWrappingStyle = TextWrappingStyle.Square; Pic2.TextWrappingStyle = TextWrappingStyle.Inline; //Save the document to file document.SaveToFile("InsertImage.docx", FileFormat.Docx); } } }
Insert an Image at a Specified Location in a Word document
The DocPicture.HorizontalPosition and DocPicture.VerticalPosition properties offered by Spire.Doc for .NET allows you to insert an image at a specified location. The detailed steps are as follows.
- Create a Document instance.
- Load a sample Word document using Document.LoadFromFile() method.
- Get the first section of the Word Document using Document.Sections[] property.
- Get a specified paragraph of the section using Section.Paragraphs[] property.
- Load an image and insert the image to the document using Paragraph.AppendPicture() method.
- Set the horizontal and vertical position of the image using DocPicture.HorizontalPosition and DocPicture.VerticalPosition properties.
- Set the height and width of the image using DocPicture.Width and DocPicture.Height properties.
- Set the wrapping style of the image using DocPicture.TextWrappingType property.
- Save the document to another file using Document.SaveToFile() method.
- C#
- VB.NET
using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using System.Drawing; namespace InsertImage { class Program { static void Main(string[] args) { //Create a Document instance Document document = new Document(); //Load a sample Word document document.LoadFromFile("input.docx"); //Get the first section Section section = document.Sections[0]; //Load an image and insert it to the document DocPicture picture = section.Paragraphs[0].AppendPicture(Image.FromFile(@"C:\Users\Administrator\Desktop\pic.jpg")); //Set the position of the image picture.HorizontalPosition = 90.0F; picture.VerticalPosition = 50.0F; //Set the size of the image picture.Width = 150; picture.Height = 150; //Set the wrapping style to Behind picture.TextWrappingStyle = TextWrappingStyle.Behind; // Save the document to file document.SaveToFile("Insert.docx", FileFormat.Docx); } } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.