Nathan
Nathan

Reputation: 1347

Right-Aligning printed text

I'm working on printing a receipt right now, but I can't figure out how to right align text in graphics mode. I've tried a couple different things, but they're either really inefficient or don't work in my situation. Is there a way I can easily align text like to the right? Here's my code right now.

using (Font printFont = new Font("Courier New", 9.0f))
        {               
            e.Graphics.DrawString("Subtotal:", printFont, Brushes.Black, leftMargin + 80, HeightToPrint, new StringFormat());
            e.Graphics.DrawString(subtotal.ToString(), printFont, Brushes.Black, leftMargin + 150, HeightToPrint, new StringFormat());
        }

Upvotes: 11

Views: 18192

Answers (2)

Chris
Chris

Reputation: 5514

In order for it to be able to right align the text, you need to specify a layout rectangle:

var format = new StringFormat() { Alignment = StringAlignment.Far };
var rect = new RectangleF( x, y, width, height );

e.Graphics.DrawString( text, font, brush, rect, format );

And it will then align the string within that rectangle.

Upvotes: 26

Andrew Morton
Andrew Morton

Reputation: 25013

Use the Graphics.MeasureString Method to get how long the rendered string will be and draw it at rightMargin - measuredStringWidth.

Upvotes: 8

Related Questions