Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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());
        }
like image 940
Nathan Avatar asked Oct 18 '13 20:10

Nathan


2 Answers

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.

like image 122
Chris Avatar answered Oct 20 '22 00:10

Chris


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

like image 31
Andrew Morton Avatar answered Oct 19 '22 22:10

Andrew Morton