.NET (1316)
Children categories

Adding images to Word documents programmatically is a common requirement in document automation. Whether you're generating reports, creating invoices, or building dynamic documents, inserting and customizing images can enhance your document's visual appeal.
In this article, we'll explore how to insert images into Word documents using Spire.Doc for .NET, covering local files, byte arrays, and advanced image customization.
- .NET Library for Adding Images to Word
- Insert an Imge from Local to Word
- Insert an Image from a Byte Array to Word
- Further Customize the Image
- Conclusion
.NET Library for Adding Images to Word
Spire.Doc for .NET is a powerful library that enables developers to create, edit, and manipulate Word documents without Microsoft Office dependencies. It provides straightforward methods to insert and format images in Word files.
Key Features:
- Insert images from local storage or byte arrays.
- Adjust image size, rotation, and positioning.
- Control text wrapping around images.
- Support for various image formats (PNG, JPG, BMP, etc.).
To get started, downoad Spire.Doc from our offical website and reference the DLLs in your project. Or, you can install it via NuGet through the following command:
PM> Install-Package Spire.Doc
Insert an Imge from Local to Word
The simplest method for inserting images into a Word document is to load them directly from your file system. Using Spire.Doc's AppendPicture() method, you can easily specify the file path of the image. This method automatically detects the image format and embeds it into the document.
using Spire.Doc;
using Spire.Doc.Documents;
namespace InsertImageFromLocal
{
class Program
{
static void Main(string[] args)
{
// Create a Document object
Document document = new Document();
// Add a section
Section section = document.AddSection();
// Add a paragraph
Paragraph paragraph = section.AddParagraph();
// Append a picture from the local disk
paragraph.AppendPicture("C:\\Users\\Administrator\\Desktop\\MyPic.png");
// Save the document
document.SaveToFile("output.docx", FileFormat.Docx);
// Dispose resources
document.Dispose();
}
}
}

Insert an Image from a Byte Array to Word
In dynamic applications, integrating images from web sources or databases is often essential for enhancing user experience and content relevance.This method downloads images as byte arrays and injecte into the document using a MemoryStream .
By utilizing this technique, developers can dynamically populate documents with up-to-date content, such as logos or product images, directly from online resources or databases.
using Spire.Doc;
using Spire.Doc.Documents;
namespace InsertImageFromByteArray
{
class Program
{
static async System.Threading.Tasks.Task Main(string[] args)
{
// URL of the image
string imageUrl = "https://example.com/image.png";
// Download the image
byte[] imageBytes;
using (HttpClient client = new HttpClient())
{
imageBytes = await client.GetByteArrayAsync(imageUrl);
}
// Create a Document object
Document document = new Document();
// Add a section
Section section = document.AddSection();
// Add a paragraph
Paragraph paragraph = section.AddParagraph();
// Append a picture from the byte array
using (MemoryStream stream = new MemoryStream(imageBytes))
{
paragraph.AppendPicture(stream);
}
// Save the document
document.SaveToFile("output.docx", FileFormat.Docx);
// Dispose resources
document.Dispose();
}
}
}
Further Customize the Image
Professional documents often demand precise image formatting. Spire.Doc offers extensive controls through the DocPicture class, enabling users to manipulate images effectively.
Key features include resizing to fit layouts, rotating for optimal orientation, and text wrapping options that allow text to flow seamlessly around images. Additionally, users can specify spacing and alignment to position images accurately relative to surrounding content.
// Append an image from disk
DocPicture picture = paragraph.AppendPicture("C:\\Users\\Administrator\\Desktop\\MyPic.png");
// Resize the image to 70%
picture.SetScale(70f);
// Rotate the image 10 degrees counterclockwise
picture.Rotation = -10;
// Specify top and bottom distance to 3 units
picture.DistanceTop = picture.DistanceBottom = 3;
// Set the text wrapping style around the image
picture.TextWrappingStyle = TextWrappingStyle.TopAndBottom;
// Center align the paragraph containing the image
paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center;
Conclusion
Using Spire.Doc for .NET simplifies the process of inserting and customizing images in Word documents. Whether pulling images from local storage or online sources, the library provides flexible options to enhance document presentation.
Get a Free License
To fully experience the capabilities of Spire.Doc for .NET without any evaluation limitations, you can request a free 30-day trial license.
Editing a Word document is necessary when you want to improve readability, correct errors, refine formatting, maintain consistency, adapt content, facilitate collaboration, and optimize the document for any other purposes. Programmatically editing a Word document using C# can be a powerful approach to automate document processing and manipulation tasks.
In this article, you will learn how to edit a Word document using C# and the Spire.Doc for .NET library.
- Modify Text in a Word Document
- Change Formatting of Text in a Word Document
- Add New Elements to a Word Document
- Remove Paragraphs from 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 DLL files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.Doc
Modify Text in a Word Document in C#
Spire.Doc allows you to programmatically access specific sections and paragraphs in Word documents. To retrieve a particular section, use the Document.Sections[index] property. Then, to get a particular paragraph within that section, leverage the Section.Paragraphs[index] property. Finally, you can update the text content of the paragraph using the Paragraph.Text property.
The steps to modify text in a Word document using C# are as follows:
- Create a Document object.
- Load a Word file from the given file path.
- Get a specific section through Document.Sections[index] property.
- Get a specific paragraph through Section.Paragraphs[index] property.
- Reset the text of the paragraph through Paragraph.Text property.
- Save the updated document to a different Word file.
- C#
using Spire.Doc;
using Spire.Doc.Documents;
namespace ModifyText
{
class Program
{
static void Main(string[] args)
{
// Create a new document object
Document document = new Document();
// Load an existing Word file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx");
// Get a specific section
Section section = document.Sections[0];
// Get a specific paragraph
Paragraph paragraph = section.Paragraphs[0];
// Modify the text of the paragraph
paragraph.Text = "Updated Title";
// Save the document to a different Word file
document.SaveToFile("ModifyText.docx", FileFormat.Docx);
// Dispose resource
document.Dispose();
}
}
}

Change Formatting of Text in a Word Document in C#
To change the text formatting within a paragraph, first obtain the paragraph object, then iterate through its child objects to locate the individual text ranges. For each text range, you can reset the formatting using the CharacterFormat property of the TextRange.
The steps to change text formatting in a Word document are as follows:
- Create a Document object.
- Load a Word file from the given file path.
- Get a specific section through Document.Sections[index] property.
- Get a specific paragraph through Section.Paragraphs[index] property.
- Iterate through the child objects in the paragraph.
- Determine if a child object is a text range.
- Get a specific text range.
- Reset the text formatting through TextRange.CharacterFormat property.
- Save the updated document to a different Word file.
- C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing;
namespace ChangeTextFont
{
class Program
{
static void Main(string[] args)
{
// Create a new document object
Document document = new Document();
// Load an existing Word file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx");
// Get a specific section
Section section = document.Sections[0];
// Get a specific paragraph
Paragraph paragraph = section.Paragraphs[2];
// Iterate through the child objects in the paragraph
for (int i = 0; i < paragraph.ChildObjects.Count; i++)
{
// Determine if a child object is text range
if (paragraph.ChildObjects[i] is TextRange)
{
// Get a specific text range
TextRange textRange = (TextRange)paragraph.ChildObjects[i];
// Reset font name for it
textRange.CharacterFormat.FontName = "Corbel Light";
// Reset font size for it
textRange.CharacterFormat.FontSize = 11;
// Reset text color for it
textRange.CharacterFormat.TextColor = Color.Blue;
// Apply italic to the text range
textRange.CharacterFormat.Italic = true;
}
}
// Save the document to a different Word file
document.SaveToFile("ChangeFont.docx", FileFormat.Docx);
// Dispose resource
document.Dispose();
}
}
}

Add New Elements to a Word Document in C#
In addition to modifying the existing content in a Word document, you can also insert various types of new elements, such as text, images, tables, lists, and charts. As most elements are paragraph-based, you have the flexibility to add a new paragraph at the end of the document or insert it mid-document. You can then populate this new paragraph with the desired content, whether that's plain text, images, or other elements.
Below are the steps to add new elements (text and images) to a Word document using C#:
- Create a Document object.
- Load a Word file from the given file path.
- Get a specific section through Document.Sections[index] property.
- Add a paragraph to the section using Section.AddParagraph() method.
- Add text to the paragraph using Paragraph.AppendText() method.
- Add an image to the paragraph using Paragraph.AppendPicture() method.
- Save the updated document to a different Word file.
- C#
using Spire.Doc;
using Spire.Doc.Documents;
namespace AddNewElementsToWord
{
class Program
{
static void Main(string[] args)
{
// Create a new document object
Document document = new Document();
// Load an existing Word file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx");
// Get the last section
Section lastSection = document.LastSection;
// Add a paragraph to the section
Paragraph paragraph = lastSection.AddParagraph();
// Add text to the paragraph
paragraph.AppendText("This text and the image shown below are added programmatically using C# and Spire.Doc for .NET.");
// Add an image to the paragraph
paragraph.AppendPicture("C:\\Users\\Administrator\\Desktop\\logo.png");
// Create a paragraph style
ParagraphStyle style = new ParagraphStyle(document);
style.Name = "FontStyle";
style.CharacterFormat.FontName = "Times New Roman";
style.CharacterFormat.FontSize = 12;
document.Styles.Add(style);
// Apply the style to the paragraph
paragraph.ApplyStyle(style.Name);
// Save the document to a different Word file
document.SaveToFile("AddNewElements.docx", FileFormat.Docx);
// Dispose resource
document.Dispose();
}
}
}

Remove Paragraphs from a Word Document in C#
With the Spire.Doc library, you can perform a variety of document operations, including updating existing content, adding new elements, as well as removing elements from a Word document. For example, to remove a paragraph from the document, you can use the Section.Paragraphs.RemoveAt() method.
The following are the steps to remove paragraphs from a Word document using C#:
- Create a Document object.
- Load a Word file from the given file path.
- Get a specific section through Document.Sections[index] property.
- Remove a specific paragraph from the section using Section.Paragraphs.RemoveAt() method.
- Save the updated document to a different Word file.
- C#
using Spire.Doc;
namespace RemoveParagraphs
{
class Program
{
static void Main(string[] args)
{
// Create a new document object
Document document = new Document();
// Load an existing Word file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx");
// Get a specific section
Section section = document.Sections[0];
// Remove a specific paragraph
section.Paragraphs.RemoveAt(0);
// Save the document to a different Word file
document.SaveToFile("RemoveParagraph.docx", FileFormat.Docx);
// Dispose resource
document.Dispose();
}
}
}
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.
Generating Word documents programmatically in C# is a powerful way to automate report creation, invoices, or any other dynamic document. With Spire.Doc for .NET, a robust and easy-to-use library, you can efficiently build Word files from scratch with full control over formatting and content. This guide will walk you through key features such as adding titles, headings, and paragraphs for structured text, inserting images for visual elements, creating tables to organize data, and adding lists for better readability.
By leveraging Spire.Doc, you can seamlessly generate professional, well-formatted Word documents directly from your .NET applications. Let's dive in and explore how to implement these functionalities step by step.
- Add Titles, Headings, and Paragraphs to a Word Document
- Add an Image to a Word Document
- Add a Table to a Word Document
- Add a List to 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 DLL files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.Doc
Add Titles, Headings, and Paragraphs to a Word Document in C#
When creating structured Word documents with Spire.Doc for .NET, the core functionality revolves around the Document and Section classes. New paragraphs are added using AddParagraph(), while text content is inserted via AppendText(). For consistent formatting, you can apply built-in styles such as Title or Heading 1-4, which ensure a professional and standardized layout. Alternatively, custom styles can be defined for precise control over fonts, colors, and sizing, allowing for tailored document design.
Steps for adding titles, headings, and parargraphs to a Word documents in C#:
- Create a Document object.
- Add a section to the document with Document.AddSection().
- Add paragraphs to the section using Section.AddParagraph().
- Use Paragraph.ApplyStyle() to apply built-in styles (Title, Heading1, Heading2, Heading3) to specific paragraphs.
- Define a custom paragraph style with ParagraphStyle() and apply it to a designated paragraph.
- Save the document as a DOCX file.
- C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing;
namespace CreateSimpleWordDocument
{
class Program
{
static void Main(string[] args)
{
// Create a Document object
Document document = new Document();
// Add a section
Section section = document.AddSection();
// Set page margins
section.PageSetup.Margins.All = 60f;
// Add a title paragraph
Paragraph title_para = section.AddParagraph();
TextRange textRange = title_para.AppendText("This Is Title");
title_para.ApplyStyle(BuiltinStyle.Title);
textRange.CharacterFormat.FontName = "Times Now Roman";
// Add a couple of heading paragraphs
Paragraph heading_one = section.AddParagraph();
textRange = heading_one.AppendText("Heading 1");
heading_one.ApplyStyle(BuiltinStyle.Heading1);
textRange.CharacterFormat.FontName = "Times Now Roman";
Paragraph heading_two = section.AddParagraph();
textRange = heading_two.AppendText("Heading 2");
heading_two.ApplyStyle(BuiltinStyle.Heading2);
textRange.CharacterFormat.FontName = "Times Now Roman";
Paragraph heading_three = section.AddParagraph();
textRange = heading_three.AppendText("Heading 3");
heading_three.ApplyStyle(BuiltinStyle.Heading3);
textRange.CharacterFormat.FontName = "Times Now Roman";
Paragraph heading_four = section.AddParagraph();
textRange = heading_four.AppendText("Heading 4");
heading_four.ApplyStyle(BuiltinStyle.Heading4);
textRange.CharacterFormat.FontName = "Times Now Roman";
// Add a normal paragraph
Paragraph normal_para = section.AddParagraph();
normal_para.AppendText("This is a sample paragraph.");
// Create a paragraph style
ParagraphStyle style = new ParagraphStyle(document);
style.Name = "paraStyle";
style.CharacterFormat.FontName = "Times New Roman";
style.CharacterFormat.FontSize = 13f;
style.CharacterFormat.TextColor = Color.Brown;
document.Styles.Add(style);
// Apply the custom style to the paragraph
normal_para.ApplyStyle("paraStyle");
// Save the document
document.SaveToFile("AddText.docx", FileFormat.Docx);
// Dispose resources
document.Dispose();
}
}
}

Add an Image to a Word Document in C#
To insert an image into a Word document, first create a dedicated paragraph element to serve as the image container. By using the AppendPicture() method, you can load an image from the file system and embed it directly into the document structure.
Steps for adding an image to a Word doucment in C#:
- Create a Document object.
- Add a section to the document with Document.AddSection().
- Add a paragraph to the section using Section.AddParagraph().
- Use the Paragraph.AppendPicture() method to add an image to the paragraph.
- Save the document as a DOCX file.
- C#
using Spire.Doc;
using Spire.Doc.Documents;
using System.Drawing;
namespace AddImage
{
class Program
{
static void Main(string[] args)
{
// Create a Document object
Document document = new Document();
// Add a section
Section section = document.AddSection();
// Set page margins
section.PageSetup.Margins.All = 60f;
// Add a paragraph
Paragraph image_para = section.AddParagraph();
// Append an image
image_para.AppendPicture(Image.FromFile("C:\\Users\\Administrator\\Desktop\\logo.png"));
//Save the document
document.SaveToFile("AddImage.docx", FileFormat.Docx);
// Dispose resources
document.Dispose();
}
}
}

Add a Table to a Word Document in C#
The table creation process begins with the AddTable() method, which establishes the basic table structure. You can precisely define the table dimensions by specifying the required number of rows and columns through the ResetCells() method. Once initialized, each cell can be populated by first adding a paragraph element using AddParagraph(), then inserting your textual content with AppendText().
Steps for adding a table to a Word document in C#:
- Create a Document object.
- Add a section to the document with Document.AddSection().
- Create a two-dimensional array to hold the table data, including headers and values.
- Use Section.AddTable() to create a table.
- Call Table.ResetCells() to define the number of rows and columns in the table based on your data.
- Iterate through the data array, adding text to each cell using the TableCell.AddParagraph() and Paragraph.AppendText() methods.
- Save the document as a DOCX file.
- C#
using Spire.Doc;
using Spire.Doc.Documents;
namespace AddTable
{
class Program
{
static void Main(string[] args)
{
// Create a Document object
Document document = new Document();
// Add a section
Section section = document.AddSection();
// Set page margins
section.PageSetup.Margins.All = 60f;
// Define table data as a 2D array
string[,] data = new string[4, 4]
{
{ "Product", "Unit Price", "Quantity", "Sub Total" },
{ "A", "$29", "120", "$3,480" },
{ "B", "$35", "110", "$3,850" },
{ "C", "$68", "140", "$9,520" }
};
// Add a table
Table table = section.AddTable(showBorder: true);
// Set row number and column number
table.ResetCells(data.GetLength(0), data.GetLength(1));
// Write data to cells
for (int r = 0; r < data.GetLength(0); r++)
{
TableRow row = table.Rows[r];
row.Height = 20;
row.HeightType = TableRowHeightType.Exactly;
for (int c = 0; c < data.GetLength(1); c++)
{
var cell = row.Cells[c];
cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle;
var textRange = cell.AddParagraph().AppendText(data[r, c]);
textRange.CharacterFormat.FontName = "Times New Roman";
textRange.CharacterFormat.FontSize = 14;
}
}
// Automatically adjusts the column widths of a table to fit its contents
table.AutoFit(AutoFitBehaviorType.AutoFitToContents);
// Save the document to file
document.SaveToFile("AddTable.docx", FileFormat.Docx);
// Dispose resources
document.Dispose();
}
}
}

Add a List to a Word Document in C#
The ListStyle class provides the foundation for implementing both bulleted and numbered lists in your document. By configuring this class, you can establish consistent visual formatting for all list items. Once your list style is defined, simply apply it to target paragraphs using the ApplyStyle() method.
Steps for adding a list to a Word document in C#:
- Create a Document object.
- Add a section to the document with Document.AddSection().
- Define a list style using Document.Styles.Add().
- Add paragraphs to the section using Section.AddParagraph().
- Apply the defined list style to the paragraphs using Paragraph.ListFormat.ApplyStyle().
- Save the document as a DOCX file.
- C#
// Create a Document object
Document document = new Document();
// Add a section
Section section = document.AddSection();
// Set page margins
section.PageSetup.Margins.All = 60f;
// Create a bulleted list style
ListStyle listStyle = document.Styles.Add(ListType.Bulleted, "bulletedList");
ListLevelCollection Levels = listStyle.ListRef.Levels;
Levels[0].BulletCharacter = "\x00B7";
Levels[0].CharacterFormat.FontName = "Symbol";
Levels[0].TextPosition = 20;
// Add a paragraph
Paragraph paragraph = section.AddParagraph();
TextRange textRange = paragraph.AppendText("Fruits:");
paragraph.Format.AfterSpacing = 5f;
textRange.CharacterFormat.FontName = "Times New Roman";
textRange.CharacterFormat.FontSize = 14;
// Add another five paragraphs as bulleted list items
foreach (var fruit in new[] { "Apple", "Banana", "Watermelon", "Mango" })
{
paragraph = section.AddParagraph();
textRange = paragraph.AppendText(fruit);
paragraph.ListFormat.ApplyStyle(listStyle);
paragraph.ListFormat.ListLevelNumber = 0;
textRange.CharacterFormat.FontName = "Times New Roman";
textRange.CharacterFormat.FontSize = 14;
}
// Save the document to file
document.SaveToFile("AddList.docx", FileFormat.Docx);
// Dispose resources
document.Dispose();

Get a Free License
To fully experience the capabilities of Spire.Doc for .NET without any evaluation limitations, you can request a free 30-day trial license.
Spire.Doc for .NET is a professional Word .NET library specifically designed for developers to create, read, write, convert, compare and print Word documents on any .NET platform (Target .NET Framework, .NET Core, .NET Standard, .NET 5.0, .NET 6.0, Xamarin & Mono Android) with fast and high quality performance.
As an independent Word .NET API, Spire.Doc for .NET doesn't need Microsoft Word to be installed on neither the development nor target systems. However, it can incorporate Microsoft Word document creation capabilities into any developers' .NET applications.
No matter what users want to do on Word document, they should open it. This guide demonstrates several solutions to open Word in C# and VB.NET via Spire.Doc for .NET.
Open Existing Word
Spire.Doc for .NET provides a Document(String) constructor to enable users to initialize a new instance of Document class from the specified existing document.
Document document = new Document(@"E:\Work\Documents\Spire.Doc for .NET.docx");
Dim document As New Document("E:\Work\Documents\Spire.Doc for .NET.docx")
Spire.Doc for .NET also provides Document.LoadFromFile(String) method of Document class to open a Word document. The Word document can be .doc(Word 97-2003), .docx(Word 2007 and 2010) and .docm(Word with macro).
Document document = new Document();
document.LoadFromFile(@"E:\Work\Documents\Spire.Doc for .NET.docx");
Dim document As New Document()
document.LoadFromFile("E:\Work\Documents\Spire.Doc for .NET.docx")
Open Word in Read Mode
Spire.Doc for .NET provides Document.LoadFromFileInReadMode(String, FileFormat) method of Document class to load Word in Read-Only mode.
Document document = new Document();
document.LoadFromFileInReadMode(@"E:\Work\Documents\Spire.Doc for .NET.docx",FileFormat.Docx);
Dim document As New Document()
document.LoadFromFileInReadMode("E:\Work\Documents\Spire.Doc for .NET.docx", FileFormat.Docx)
Load Word from Stream
Spire.Doc for .NET provides the constructor Document(Stream) to initialize a new instance of Document class from specified data stream and the method Document.LoadFromStream(Stream, FileFormat) to open document from Stream in XML or Microsoft Word document.
Stream stream = File.OpenRead(@"E:\Work\Documents\Spire.Doc for .NET.docx");
Document document = new Document(stream);
Stream stream = File.OpenRead(@"E:\Work\Documents\Spire.Doc for .NET.docx");
Document document = new Document();
document.LoadFromStream(stream, FileFormat.Docx);
Dim stream As Stream = File.OpenRead("E:\Work\Documents\Spire.Doc for .NET.docx")
Dim document As New Document(stream)
Dim stream As Stream = File.OpenRead("E:\Work\Documents\Spire.Doc for .NET.docx")
Dim document As New Document()
document.LoadFromStream(stream, FileFormat.Docx)
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.
The sample demonstrates how to work with Word page setup.

The sample demonstrates how to set document properties.

The sample demonstrates how to handle merge event.

The sample demonstrates how to export doc document to PDF file.

The sample demonstrates how to export doc document to XML file.



