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 ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.