Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitlePrint a drawing centered on the printer in VB .NET
DescriptionThis example shows how to print a drawing centered on the printer in VB .NET. It shows how to define a transformation on the Graphics object to center the drawing.
Keywordsprint, preview, center, print preview, VB .NET
CategoriesGraphics, VB.NET
 
Subroutine CenterPictureInMargins defines a transformation that translates the object with bounds picture_bounds so it is centered within the margins defined by margin_bounds.
 
' Transform the Graphics object to center the rectangle
' picture_bounds within margin_bounds.
Private Sub CenterPictureInMargins(ByVal gr As Graphics, _
    ByVal picture_bounds As RectangleF, ByVal margin_bounds _
    As RectangleF)
    ' Remove any existing transformation.
    gr.ResetTransform()

    ' Apply the transformation.
    Dim dx As Single = _
        margin_bounds.Left - picture_bounds.Left + _
        (margin_bounds.Width - picture_bounds.Width) / 2
    Dim dy As Single = _
        margin_bounds.Top - picture_bounds.Top + _
        (margin_bounds.Height - picture_bounds.Height) / 2
    gr.TranslateTransform(dx, dy)
End Sub
 
The following code shows how the program uses this routine. It draws the untransformed margins for debugging purposes. Then it calls CenterPictureInMargins passing it the picture's bounds and the margins' bounds. Next it calls subroutine DrawFace to draw the graphics within the indicate picture bounds. The Graphics object's transformation automatically centers the results.
 
' Print the page.
Private Sub Print_PrintPage(ByVal sender As Object, ByVal e _
    As System.Drawing.Printing.PrintPageEventArgs)
    ' Draw the margins (for debugging). Be sure 
    ' to do this before transforming the Graphics object.
    e.Graphics.DrawRectangle(Pens.Red, e.MarginBounds)

    ' We draw in the area (0, 0) - (400, 400). 
    ' Transform the Graphics object to center the results.
    Dim picture_rect As New RectangleF(0, 0, 400, 400)
    Dim margin_rect As New RectangleF( _
        e.MarginBounds.X, _
        e.MarginBounds.Y, _
        e.MarginBounds.Width, _
        e.MarginBounds.Height)
    CenterPictureInMargins(e.Graphics, picture_rect, _
        margin_rect)

    ' Draw the graphics.
    DrawFace(e.Graphics)

    ' There are no more pages.
    e.HasMorePages = False
End Sub
 
This program prints or previews the result.
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated