Introduction

Suppose you have a list of companies in a database table. Someone asked you to print each company name on a different label, using a specified font and font size. You have to be sure that all the company names will fit into the labels, without any word-wrap; you can introduce abbreviations if a company name doesn't fit.

The font you are using is not a fixed-length font but a proportional font, so the character length of each string cannot be used to anticipate the real printed length of the string. How can you do?

You simply have to "measure" each string, computing which width it will have when printed in the specified font and with the specified font size. To do this, you can use the MeasureString() method of the .NET Framework Graphics class.

The application

The simple application I wrote helps you in "measuring" strings, given a font and a font size. The core measuring functionality is in the Measure() subroutine:

once the application is running, choose your preferred font, clicking on the "Set Font" button;

type in the upper textbox one of the longest strings permitted by your label sizes (you have to do a trial print, of course);

in the "Current width" box, you will read the width (in pixel) of the typed string (computed for the given font and font size): this is the maximum width allowed by your label, so you can mark it clicking on the "Set Limit" button;

from now on, all the new strings you will type in the textbox will be measured and their width will be compared with the limit you set, giving you evidence for strings that are "too long", and allowing you to modify them (introducing abbreviations) until their width will fit the maximum allowed width.

Of course, this application is only an example. In a real situation, you will have to integrate a subroutine like Measure() inside a program that will: fetch your data from the database table; measure the string; warn you about "too long" strings and let you modify them, storing them again in the data source.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

Comments and Discussions

Thanks for this article. I had looked off and on for a couple days for this I thought it should be part of the font object. In my case I'm using monospace, the font has a height property but no width. Anyways, 2 lines of code and problem solved, got to love it