How to Add Image in Word Document using C# Code

This tutorial will guide you step-by-step as to how to add image in word document using C#. We’ll use a command-line application in C# add image to word document.

Steps to Add Image in Word Document using C#

  1. Add reference to System.Drawing assembly in solution
  2. Next, Aspose.Words for .NET NuGet package reference needs to be added
  3. Add using directives for Aspose.Words and Aspose.Words.Drawing namespaces
  4. Call License.SetLicense method
  5. Create Document object to load Word DOC from file system or memory stream
  6. Create DocumentBuilder class object to write text, images, tables etc.
  7. Move cursor to Header or Footer or any desired position in Word DOC
  8. Use DocumentBuilder.InsertImage to add image from stream or file
  9. Use Shape class to further set Size, Position, Fill etc. of the Image
  10. Call Document.Save method to save Word DOC to disk or stream

You can use the following code example in .NET application to add image to word document using C#.

Code to Add Image in Word Document using C#

using Aspose.Words;
using Aspose.Words.Drawing;
namespace HowtoAddImageinWordDocumentUsingCsharp
{
class AddImageToWordDOC
{
static void Main(string[] args)
{
// Set license prior to adding image in Word document using C#
License setupPriorAddingImages = new License();
setupPriorAddingImages.SetLicense("path to license.lic");
// Load Word DOC document that you want to add images to
Document AddImagesToWordDOC = new Document("input.doc");
// Instantiate DocumentBuilder class object to write text, images, tables etc.
DocumentBuilder imageWriter = new DocumentBuilder(AddImagesToWordDOC);
// Move cursor to Primary Header in Word DOC
imageWriter.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
// Insert image in word document header c#
Shape headerImage = imageWriter.InsertImage("C:\\Add Image in Word Header.jpg");
// Set Image Size in Header
headerImage.Width = 1 * 72; // equals to one inch
headerImage.Height = 1 * 72;
// Now, move cursor to last Paragraph in Word Document
imageWriter.MoveTo(AddImagesToWordDOC.LastSection.Body.LastParagraph);
// Add Image to Word Document and Link to File
Shape imageAsLinkToFile = imageWriter.InsertImage("C:\\Add Image as Link to File.jpg");
imageAsLinkToFile.ImageData.SourceFullName = "C:\\Add Image as Link to File.jpg";
// Save As DOCX
AddImagesToWordDOC.Save("C:\\Word with Embeded and Linked Images.docx");
}
}
}

So, the above Visual Studio application will allow you to add image to word document C#. It loads an existing DOC file but you can even programmatically create word document in C#. The code presents two ways to add image to word DOC C# - it first insert image in word document header C# and then it adds image to word as linked image i.e. the image in this case is not embedded but inserted as link to file.

 English