views:

703

answers:

5

Hi,

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

A: 

What about Graphics.MeasureString()?

codymanix
+3  A: 

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.

adrianbanks
+2  A: 

Hi!

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.

The best place to ask PDFsharp and MigraDoc Foundation related questions is the PDFsharp forum. The PDFsharp Team will not monitor stackoverflow.com on a regular basis.

PDFsharp Forum:
http://forum.pdfsharp.net/

PDFsharp Website:
http://www.pdfsharp.net/

PDFsharp Team
A: 

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 );
brndnbg
A: 

PDFSharp SUCKS!

Heiko