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());
}
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.
Use the Graphics.MeasureString Method to get how long the rendered string will be and draw it at rightMargin - measuredStringWidth
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With