C# Aspose.Words: 计算固定字体大小字符串在 Word 中的宽度
您可以使用 Aspose.Words 中的 Font 类和 FontMetrics 类来计算字符串的宽度。
以下是一个示例代码,可以计算给定字符串的宽度:
string text = 'Hello, World!';
double fontSize = 12.0;
string fontName = 'Arial';
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// 插入段落并设置字体
builder.Font.Name = fontName;
builder.Font.Size = fontSize;
builder.Writeln(text);
// 获取段落对象
Paragraph para = doc.FirstSection.Body.Paragraphs[0];
// 获取段落中的 Run 对象
Run run = para.Runs[0];
// 获取字体对象
Font font = run.Font;
// 获取字体测量对象
FontMetrics metrics = FontMetrics.GetFontMetrics(font);
// 计算字符串宽度
double width = metrics.GetTextWidth(text);
// 将宽度转换为磅
width /= 72.0;
Console.WriteLine('Width of '{0}' is {1} points ({2} inches).', text, width, width / 72.0);
在上面的代码中,我们使用 DocumentBuilder 对象插入一个段落,并将字体设置为给定的字体和字体大小。然后,我们获取段落中的 Run 对象,并从中获取字体对象。接下来,我们使用字体对象来获取字体测量对象,从而可以计算字符串的宽度。最后,我们将宽度转换为磅,并将其输出到控制台上。
原文地址: https://www.cveoy.top/t/topic/nKcu 著作权归作者所有。请勿转载和采集!