Home Contents Search GhostDepot Vb.Net Depot

 Visual Studio Tips VB Printing Samples

 

Home
Up

 

 

VB Printing Tips

 

1. How To Print a Form Image


This example shows how to capture a Windows Form image and print it. The image is resized and centered to fit the Print Margins.

The example shows the Print Preview dialog. To print click the Print button on the dialog.

Many programmers attempt this with the old Power Pack Printform control. However that control is out of date, limited, and not easily modified. There is really no need to use the Power Pack it is all built into VB now.

 

Program Output Print Preview.

 

'prints form fit to page and centered with preview


Public Class Form1

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load


Text = "Print Form Fit to Page Example"
Size = New Size(1500, 700)
BackgroundImage = Image.FromFile("c:\bitmaps\rusty.jpg")
BackgroundImageLayout = ImageLayout.Zoom


Dim preview As New PrintPreviewDialog
Dim pd As New System.Drawing.Printing.PrintDocument
pd.DefaultPageSettings.Landscape = True
AddHandler pd.PrintPage, AddressOf OnPrintPage
preview.Document = pd
preview.ShowDialog()


End Sub


Private Sub OnPrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs)


'create a memory bitmap and size to the form
Using bmp As Bitmap = New Bitmap(Me.Width, Me.Height)


'draw the form on the memory bitmap
Me.DrawToBitmap(bmp, New Rectangle(0, 0, Me.Width, Me.Height))


'draw the form image on the printer graphics sized and centered to margins
Dim ratio As Single = CSng(bmp.Width / bmp.Height)


If ratio > e.MarginBounds.Width / e.MarginBounds.Height Then


e.Graphics.DrawImage(bmp,
e.MarginBounds.Left,
CInt(e.MarginBounds.Top + (e.MarginBounds.Height / 2) - ((e.MarginBounds.Width / ratio) / 2)),
e.MarginBounds.Width,
CInt(e.MarginBounds.Width / ratio))


Else


e.Graphics.DrawImage(bmp,
CInt(e.MarginBounds.Left + (e.MarginBounds.Width / 2) - (e.MarginBounds.Height * ratio / 2)),
e.MarginBounds.Top,
CInt(e.MarginBounds.Height * ratio),
e.MarginBounds.Height)


End If


End Using

End Sub

End Class
 

 

 

 

To use the examples make a new project with one Form. Past the example code into the form as shown. Run the example.

 

 

 

Copyright © 2000 - 2019 Sandia Software