Right aligning text when printing from a .net program

In a program I am writing, I need to print directly to a couple of label printers.

My God these things are a pain in the ass to work with, but I will leave that rant to another post.

One thing I ran into was how to right align text when using the DrawString method of the System.Drawing.Graphics class off of the PrintPageEventArgs.

The solutions I was coming across seemed about as bad as I was expecting.

They involved measuring the width of the line of string using some System.Drawing.Graphics.MeasureString to figure out the length, and then dynamically position the text to make it appear right aligned.  So what that means is that for short text, X would be greater and for long text X would be less.

Fortunately, I came across the most simple solution:

Dim s As New StringFormat()
s.Alignment = StringAlignment.Far

e.Graphics.DrawString("por que?", New Font("Tahoma", 8), Brushes.Black, 50, 50, s)

Very simple.  But you have to wonder, why did MS pick “Far” as the alignment name instead of “Right”, as you would expect.  Maybe “Far” is more of a graphics term for alignment?  Who knows.

 

Advertisement

One thought on “Right aligning text when printing from a .net program

  1. I know this is an old post, but I saw this and I am pretty sure that the reasoning behind using "Far" is to accomodate for all languages, some read left to right, others right to left, in which case "Far" will be more universally correct… Just my 2cents….

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s