zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Word控件Spire.Doc 【文本】教程(9) ;如何在C#中获取word文档中文本的高度和宽度

c#文档教程 如何 获取 控件 文本 word
2023-09-11 14:14:49 时间

通过使用 Spire.Doc,开发人员可以找到并突出显示文本,提取word 文档中的文本。本文将向您展示如何借助 Spire.Doc 在 C# 中获取 word 文档中文本的高度和宽度。

Spire.Doc for.NET 最新下载icon-default.png?t=M85Bhttps://www.evget.com/product/3368/download

首先,下载并安装 Spire.Doc for .NET,然后通过以下路径在下载的 Bin 文件夹中添加 Spire.Doc.dll 作为参考:“..\Spire.Doc\Bin\NET4.0\ Spire.Doc.dll ”。下面详细介绍如何在C#中获取word文档中文本的高度和宽度。

首先查看原word文档:

第 1 步:创建一个新文档并从文件加载。

Document doc = new Document();
doc.LoadFromFile("Word.doc");

第 2 步:定义我们需要获取高度和宽度的文本字符串。

string text = "Microsoft Word is a word processor designed by Microsoft.";

string text = "Microsoft Word is a word processor designed by Microsoft.";

第 3 步:获取文本字符串并测量字符串。

//finds and returns the string with formatting
TextSelection selection = doc.FindString(text, true, true);
//get the font
Font font = selection.GetAsOneRange().CharacterFormat.Font;
//initialize graphics object
Image fakeImage = new Bitmap(1, 1);
Graphics graphics = Graphics.FromImage(fakeImage);
//measure string
SizeF size = graphics.MeasureString(text, font);

第 4 步:获取文本高度和宽度并阅读。

Console.WriteLine("text width:{0}", size.Width); Console.ReadLine();

有效截图

Console.WriteLine("text height:{0}",size.Height);
Console.WriteLine("text width:{0}", size.Width);
Console.ReadLine();

完整代码

using Spire.Doc;
using Spire.Doc.Documents;
using System;
using System.Drawing;
namespace GetHeightandWidth
{

class Program
{
static void Main(string[] args)
{
Document doc = new Document();
doc.LoadFromFile("Word.doc");
string text = "Microsoft Word is a word processor designed by Microsoft.";

TextSelection selection = doc.FindString(text, true, true);
Font font = selection.GetAsOneRange().CharacterFormat.Font;
Image fakeImage = new Bitmap(1, 1);
Graphics graphics = Graphics.FromImage(fakeImage);
SizeF size = graphics.MeasureString(text, font);

Console.WriteLine("text height:{0}", size.Height);
Console.WriteLine("text width:{0}", size.Width);
Console.ReadLine();
}
}
}