By using Spire.Doc, developers can find and highlight the text, extract the text in word document. This article will show you how to get the height and width of text in a word document in C# with the help of Spire.Doc.
Firstly, Download and install Spire.Doc for .NET and then add Spire.Doc.dll as reference in the downloaded Bin folder though the below path: "..\Spire.Doc\Bin\NET4.0\ Spire.Doc.dll". Here comes to the details of how to get the height and width of text in a word document in C#.
Check the original word document at first:
Step 1: Create a new document and load from file.
Document doc = new Document(); doc.LoadFromFile("Word.doc");
Step 2: Define the text string that we need to get the height and width.
string text = "Microsoft Word is a word processor designed by Microsoft.";
Step 3: Get the text string and measure the string.
//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);
Step 4: Get the text height and width and read it.
Console.WriteLine("text height:{0}",size.Height); Console.WriteLine("text width:{0}", size.Width); Console.ReadLine();
Effective screenshot:
Full codes:
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(); } } }