开发者

Find char width in pixels for various Arial fontsizes

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 开发者_JAVA技巧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


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 the TextRenderer class (from Windows forms):

TextRenderer.MeasureText("some text", new Font("Arial", 1.0f, FontStyle.Regular))

This will return a Size instance that will contain Width=12, Height=2.


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.

  //l_Page is of type PdfPage

  var l_Graphics = XGraphics.FromPdfPage( l_Page );
  var l_TitleFont = new Font( "Arial", 15f, GraphicsUnit.World )
  var l_Title = "Hallo Welt";
  //l_TitleSize will be of type XSize and has properties for Width and Height
  var l_TitleSize = l_Graphics.MeasureString( l_Title, l_TitleFont );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜