How to insert an image into a Word DOCX document in C# .NET Framework

Today we are going to dive into a simplified method for adding images into a Microsoft Word DOCX file using C#.

Starting things off, we will install Cloudmersive’s API client for documents and data conversion. NuGet will take care of this for us if you drop this snipped into your console of Package Manager.

Install-Package Cloudmersive.APIClient.NET.DocumentAndDataConvert -Version 2.2.0

Moving right along, we can now call our function, EditDocumentDocxInsertImage.

using System;using System.Diagnostics;using Cloudmersive.APIClient.NET.DocumentAndDataConvert.Api;using Cloudmersive.APIClient.NET.DocumentAndDataConvert.Client;using Cloudmersive.APIClient.NET.DocumentAndDataConvert.Model;namespace Example{public class EditDocumentDocxInsertImageExample{public void main(){// Configure API key authorization: ApikeyConfiguration.Default.AddApiKey("Apikey", "YOUR_API_KEY");// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed// Configuration.Default.AddApiKeyPrefix("Apikey", "Bearer");var apiInstance = new EditDocumentApi();var reqConfig = new DocxInsertImageRequest(); // DocxInsertImageRequest | Document input requesttry{// Insert image into a Word DOCX documentDocxInsertImageResponse result = apiInstance.EditDocumentDocxInsertImage(reqConfig);Debug.WriteLine(result);}catch (Exception e){Debug.Print("Exception when calling EditDocumentApi.EditDocumentDocxInsertImage: " + e.Message );}}}}

To position our image properly, we will need to input the specifics in this format:

{
"InputDocumentFileBytes": "string",
"InputDocumentFileUrl": "string",
"InputImageFileBytes": "string",
"InputImageFileUrl": "string",
"ImageToAdd": {
"Path": "string",
"ImageName": "string",
"ImageId": 0,
"ImageDescription": "string",
"ImageWidth": 0,
"ImageHeight": 0,
"XOffset": 0,
"YOffset": 0,
"ImageDataEmbedId": "string",
"ImageDataContentType": "string",
"ImageInternalFileName": "string",
"ImageContentsURL": "string",
"InlineWithText": true
},
"InsertPlacement": "string",
"InsertPath": "string",
"WidthInEMUs": 0,
"HeightInEMUs": 0
}

Done!

Image for post
Image for post

Written by

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store