如何在 C# 中处理文档元素

Document Element Tutorial

This article was translated from English: Does it need improvement?
Translated
View the article in English

IronWord is a powerful Word document library designed to assist .NET C# developers in integrating the capabilities of creating, reading, and editing Word and DOCX documents into their applications. In the context of a Word document, document elements are the building blocks that make up the content.

Quickstart: Create a Styled TextRun and Embed an Image in One Go

Here’s how you can use IronWord to add rich content fast – combining styled text and an embedded image in a single paragraph and saving the document in just one fluent code block. Perfect for developers who want to get started immediately without boilerplate.

Nuget IconGet started making PDFs with NuGet now:

  1. Install IronWord with NuGet Package Manager

    PM > Install-Package IronWord

  2. Copy and run this code snippet.

    new WordDocument()
      .AddParagraph(new Paragraph(new TextContent("Hello IronWord!")).AddImage(new ImageContent("pic.png")))
      .SaveAs("output.docx");
  3. Deploy to test on your live environment

    Start using IronWord in your project today with a free trial
    arrow pointer

Table of Contents

Add TextRuns

Text Content

The Split method is utilized to divide the text run into a list of smaller TextRuns, based on a specified delimiter. This allows for the organization and manipulation of textual information within the document.

:path=/static-assets/word/content-code-examples/tutorials/add-textrun-text-content.cs
using IronWord;
using IronWord.Models;

WordDocument doc = new WordDocument();

// Add text
TextContent addText = new TextContent("Add text using IronWord");
doc.AddParagraph(new Paragraph(addText));

// Append text
TextContent appendText = new TextContent("The first text.");
appendText.Append(new TextContent("The second text."));
doc.AddParagraph(new Paragraph(appendText));

// Split text
TextContent splitText = new TextContent("Use split to split the sentence.");
splitText.Split(" ");
doc.AddParagraph(new Paragraph(splitText));

// Export docx
doc.SaveAs("textrun.docx");
Imports IronWord
Imports IronWord.Models

Private doc As New WordDocument()

' Add text
Private addText As New TextContent("Add text using IronWord")
doc.AddParagraph(New Paragraph(addText))

' Append text
Dim appendText As New TextContent("The first text.")
appendText.Append(New TextContent("The second text."))
doc.AddParagraph(New Paragraph(appendText))

' Split text
Dim splitText As New TextContent("Use split to split the sentence.")
splitText.Split(" ")
doc.AddParagraph(New Paragraph(splitText))

' Export docx
doc.SaveAs("textrun.docx")
$vbLabelText   $csharpLabel

Set Styling

Setting styling for TextRuns allows you to define the visual presentation of text. This includes specifying attributes such as font size, color, style, strikethrough, underline, superscript, and subscript. Configuring styling enhances the overall appearance of the text in the document.

:path=/static-assets/word/content-code-examples/tutorials/add-textrun-set-styling.cs
using IronWord;
using IronWord.Models;
using IronWord.Models.Enums;

// Load docx
WordDocument doc = new WordDocument("document.docx");

// Configure text
TextContent textRun = new TextContent();
textRun.Text = "Add text using IronWord";
textRun.Style = new TextStyle()
{
    TextFont = new Font()
    {
        FontFamily = "Caveat",
        FontSize = 72,
    },
    Color = Color.Red,
    IsBold = true,
    IsItalic = true,
    Underline = new Underline(),
    Strike = StrikeValue.Strike,
};

Paragraph paragraph = new Paragraph();

// Add text
paragraph.AddText(textRun);

// Add paragraph
doc.AddParagraph(paragraph);

// Export docx
doc.SaveAs("save_document.docx");
Imports IronWord
Imports IronWord.Models
Imports IronWord.Models.Enums

' Load docx
Private doc As New WordDocument("document.docx")

' Configure text
Private textRun As New TextContent()
textRun.Text = "Add text using IronWord"
textRun.Style = New TextStyle() With {
	.TextFont = New Font() With {
		.FontFamily = "Caveat",
		.FontSize = 72
	},
	.Color = Color.Red,
	.IsBold = True,
	.IsItalic = True,
	.Underline = New Underline(),
	.Strike = StrikeValue.Strike
}

Dim paragraph As New Paragraph()

' Add text
paragraph.AddText(textRun)

' Add paragraph
doc.AddParagraph(paragraph)

' Export docx
doc.SaveAs("save_document.docx")
$vbLabelText   $csharpLabel

Obtain Text Fill Color

Aside from setting styling, IronWord provides a way for you to obtain the RGBA color value of the existing document to retain consistency throughout the styling.

:path=/static-assets/word/content-code-examples/tutorials/rgba-color-value.cs
using IronWord;
using IronWord.Models;
using System;

// Open existing Word
WordDocument doc = new WordDocument("Accent1TextThemcolor.docx");

TextContent content = doc.Paragraphs[0].Texts[0];

// This will show the R G B A of the themecolor
var filledColor = content.FillColor;

// Print the filled color variable to the console
Console.WriteLine(filledColor);
Imports IronWord
Imports IronWord.Models
Imports System

' Open existing Word
Private doc As New WordDocument("Accent1TextThemcolor.docx")

Private content As TextContent = doc.Paragraphs(0).Texts(0)

' This will show the R G B A of the themecolor
Private filledColor = content.FillColor

' Print the filled color variable to the console
Console.WriteLine(filledColor)
$vbLabelText   $csharpLabel

We first import the document by initializing a new WordDocument, then access the Paragraphs array and the Texts Array to retrieve the Text property. The Text class then returns the FillColor to showcase the RGBA value of the existing color of the text.

Embed Images

This feature allows you to seamlessly include images within the content, enhancing the overall visual appeal and communicative power of the document.

:path=/static-assets/word/content-code-examples/tutorials/add-textrun-embed-images.cs
using IronWord;
using IronWord.Models;

// Load docx
WordDocument doc = new WordDocument();

// Configure image
ImageContent image = new ImageContent("image.jpg");
image.Width = 200; // In unit pixel
image.Height = 200; // In unit pixel
TextContent textRun = new TextContent();

// Add image
Paragraph para = new Paragraph(textRun);
para.AddImage(image);

// Add paragraph
doc.AddParagraph(new Paragraph(textRun));

// Export docx
doc.SaveAs("save_document.docx");
Imports IronWord
Imports IronWord.Models

' Load docx
Private doc As New WordDocument()

' Configure image
Private image As New ImageContent("image.jpg")
image.Width = 200 ' In unit pixel
image.Height = 200 ' In unit pixel
Dim textRun As New TextContent()

' Add image
Dim para As New Paragraph(textRun)
para.AddImage(image)

' Add paragraph
doc.AddParagraph(New Paragraph(textRun))

' Export docx
doc.SaveAs("save_document.docx")
$vbLabelText   $csharpLabel

Add Images

Load Image

Loading images is a crucial process. This involves bringing external image files into the document. The ability to load images facilitates the inclusion of relevant visuals, contributing to a more engaging and informative document.

:path=/static-assets/word/content-code-examples/tutorials/add-image-load-image.cs
using IronWord;
using IronWord.Models;

// Load docx
WordDocument doc = new WordDocument();

Paragraph paragraph = new Paragraph();

// Add image
paragraph.AddImage("image.jpg");

// Add paragraph
doc.AddParagraph(paragraph);

// Export docx
doc.SaveAs("document.docx");
Imports IronWord
Imports IronWord.Models

' Load docx
Private doc As New WordDocument()

Private paragraph As New Paragraph()

' Add image
paragraph.AddImage("image.jpg")

' Add paragraph
doc.AddParagraph(paragraph)

' Export docx
doc.SaveAs("document.docx")
$vbLabelText   $csharpLabel

Configure Image

Optimize the images with configurable settings. This includes setting properties such as text wrapping, dimensions, position, and distance from corners. Proper configuration ensures that images are displayed in a visually pleasing and contextually appropriate manner.

:path=/static-assets/word/content-code-examples/tutorials/add-image-configure-image.cs
using IronWord;
using IronWord.Models;
using IronWord.Models.Enums;

// Load docx
WordDocument doc = new WordDocument();

// Configure image
ImageContent image = new ImageContent("image.jpg");
image.WrapText = WrapText.Square;
image.Width = 100;
image.Height = 100;
image.DistanceFromTop = 50;

var position = new ElementPosition();
position.X = 50;
position.Y = 50;
image.Position = position;

Paragraph paragraph = new Paragraph();

// Add image
paragraph.AddImage(image);

// Add paragraph
doc.AddParagraph(paragraph);

// Export docx
doc.SaveAs("document.docx");
Imports IronWord
Imports IronWord.Models
Imports IronWord.Models.Enums

' Load docx
Private doc As New WordDocument()

' Configure image
Private image As New ImageContent("image.jpg")
image.WrapText = WrapText.Square
image.Width = 100
image.Height = 100
image.DistanceFromTop = 50

Dim position = New ElementPosition()
position.X = 50
position.Y = 50
image.Position = position

Dim paragraph As New Paragraph()

' Add image
paragraph.AddImage(image)

' Add paragraph
doc.AddParagraph(paragraph)

' Export docx
doc.SaveAs("document.docx")
$vbLabelText   $csharpLabel

常见问题解答

我如何使用 C# 向 Word 文档添加文本?

您可以使用 IronWord 向 Word 文档添加文本,创建一个文本段,然后将其附加到文档中的段落。

将文本拆分为 Word 文档的方法是什么?

IronWord 提供了 Split 方法,使您可以根据指定的分隔符将文本段分成更小的部分,从而更轻松地操作文本。

如何使用 IronWord 在 Word 文档中设置文本样式?

您可以通过设置字体大小、颜色及粗体、斜体、删除线、下划线、上标和下标样式等各种属性,使用 IronWord 为文本设置样式。

如何使用 C# 在 Word 文档中嵌入图像?

要在 Word 文档中嵌入图像,可以使用 IronWord 从文件中加载图像并将其作为内嵌图像添加到文档内的段落中。

将图像加载到 Word 文档中的步骤是什么?

使用 IronWord,您可以从文件或文件流中加载图像,从而将视觉内容纳入 Word 文档中。

如何配置 Word 文档中的图像属性?

使用 IronWord,您可以配置图像属性,如文本环绕、尺寸、位置偏移以及与角落的距离,以确保图像在文档中正确显示。

我可以检索 Word 文档中文本的 RGBA 颜色值吗?

是的,IronWord 允许您获取文档中现有文本的 RGBA 颜色值,以保持一致的样式。

如何开始使用 IronWord 操作 Word 文档?

要开始使用 IronWord,您可以将其集成到您的 .NET C# 应用程序中,以创建、读取和编辑 Word 文档,利用其完整的库功能。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。

准备开始了吗?
Nuget 下载 25,807 | 版本: 2025.11 刚刚发布