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

C# 文档元素教程

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

IronWord 是一个功能强大的 Word 文档库,旨在帮助 .NET C# 开发人员将创建、读取和编辑 Word 和 DOCX 文档的功能集成到他们的应用程序中。 在 Word 文档中,文档元素是构成内容的基本组成部分。

快速入门:一次性创建样式文本并嵌入图像

以下是如何使用 IronWord 快速添加丰富的内容——将样式化的文本和嵌入的图像组合在一个段落中,并将文档保存在一个流畅的代码块中。 非常适合想要立即上手而无需编写样板代码的开发人员。

Nuget Icon立即开始使用 NuGet 创建 PDF 文件:

  1. 使用 NuGet 包管理器安装 IronWord

    PM > Install-Package IronWord

  2. 复制并运行这段代码。

    new WordDocument()
      .AddParagraph(new Paragraph(new TextContent("Hello IronWord!")).AddImage(new ImageContent("pic.png")))
      .SaveAs("output.docx");
  3. 部署到您的生产环境中进行测试

    立即开始在您的项目中使用 IronWord,免费试用!
    arrow pointer

目录

-添加文本 -文本内容(添加、追加和拆分) -设置样式(字体和字号、颜色、粗体和斜体、删除线、下划线、上标和下标) -嵌入图片 -添加图片 -加载图像(文件和文件流) -设置自动换行 -设置尺寸(宽度和高度) -设置位置偏移 -设置与角落的距离

添加文本运行

文本内容

Split方法用于根据指定的分隔符将文本运行分割成较小的 TextRun 列表。 这样就可以对文档中的文本信息进行组织和操作。

: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

设置样式

设置 TextRuns 的样式可以定义文本的视觉呈现方式。 这包括指定字体大小、颜色、样式、删除线、下划线、上标和下标等属性。 配置样式可以提升文档中文本的整体外观。

: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

获取文本填充颜色

除了设置样式外,IronWord 还提供了一种获取现有文档 RGBA 颜色值的方法,以保持样式的一致性。

: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

我们首先通过初始化一个新的WordDocument来导入文档,然后访问Paragraphs数组和Texts数组来检索Text属性。 然后, Text类返回FillColor来显示文本现有颜色的 RGBA 值。

嵌入图片

此功能可让您在内容中无缝插入图像,从而增强文档的整体视觉吸引力和沟通效果。

: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

添加图片

加载图像

图片加载是一个至关重要的过程。 这涉及到将外部图像文件导入到文档中。 加载图像的功能有助于添加相关的视觉元素,从而使文档更具吸引力和信息量。

: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

配置映像

使用可配置设置优化图像。 这包括设置文本环绕、尺寸、位置和距角点的距离等属性。 正确的配置可确保图像以赏心悦目且符合上下文的方式显示。

: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 下载 27,129 | Version: 2025.11 刚刚发布