O'Reilly logo

Microsoft® Visual Basic® .NET Programmer's Cookbook by Matthew MacDonald

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Print Centered Text

Problem

You want to center text vertically or horizontally on a page.

Solution

Calculate the available space between the margins, subtract the width or height of the text you want to print (using the Graphics.MeasureString and Font.GetHeight methods), and divide by two to find the appropriate coordinate.

Discussion

Printing centered text is easy. The only caveat is that you need to perform the coordinate calculations, as with all print operations.

Here is a code snippet that prints a block of three lines of text that are centered horizontally and vertically:

Private Sub MyDoc_PrintPage(ByVal sender As Object, _ ByVal e As PrintPageEventArgs) ' Define the font and text. Dim Font As New Font("Arial", 35) Dim Text As String = "This is ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required