views:

330

answers:

1

I'm generating a receipt and am using the Graphics object to call the DrawString method to print out the required text.

graphics.DrawString(string, font, brush, widthOfPage / 2F, yPoint, stringformat);

This works fine for what I needed it to do. I always knew what I was printing out, so I could manually trim any strings so it would fit properly on 80mm receipt paper. Then I had to add an extra bit of functionality that would make this more flexible. The user could pass in strings that would be added to the bottom.

Since I didn't know what they were going to put, I just created my own word wrap function that takes in a number of characters to wrap at and the string itself. In order to find out the number of characters, I was doing something like this:

float width = document.DefaultPageSettings.PrintableArea.Width;
int max = (int)(width / graphics.MeasureString("a", font).Width);

Now the width is returning me 283, which in mm is about 72, which makes sense when you account for margins on 80mm paper.

But the MeasureString method is returning 10.5 on a Courier New 8pt font. So instead of getting around what I expected to be 36 - 40, I'm getting 26, resulting in 2 lines of text being turned into 3-4.

The units for PrintableArea.Width are 1/100th of an inch, and the PageUnit for the graphics object is Display (which says is typically 1/100th of an inch for printers). So why am I only getting 26 back?

+1  A: 

It probably depends on the rendering engine used. See here:

How to determine the size of a string given a font

0xA3
Using TextRenderer returns 14, which gives back 20 for the max characters. Also, how do I know which rendering engine I'm using?
Brandon