I have a program that is manually generating a PDF using PDFsharp in C#. Although it is rather tedious I have to use it and am nearing completion of the task. Only one issue remains.
Problem: I am wondering how I can find out what the width of a given char is for a given font size in Arial.
I am having trouble coming up with a more precise text wrapping method. Right now one defines a width of box in pixels and then proceeds to write out a string in that box. I kinda just guess at the max length of the string that can fit in the box and there are some visual oddities that crop up from time to time.
Any help?
Thanks
In the days of True Type fonts with kerning etc. there is not a single character width. The width of the string "VA" is probably less then the sum of the widths of the strings "V" and "A". Summing up the widths if individual characters is a starting point - but finally you have to measure the complete string.
PDFsharp includes the class XTextFormatter (with full source code) that does this line wrapping. It can be adapted for specific requirements. It uses
gfx.MeasureString(token, this.font).Width
to measure the width of a string.XGraphics.MeasureString(string s, Font f) does the trick.
I'm not sure from your question whether you want a way to measure the size of a string specifically using PDF#, or just a generic way.
In general .Net, you can use the
MeasureText
method of theTextRenderer
class (from Windows forms):This will return a
Size
instance that will containWidth=12, Height=2
.