How to print an user defined document in VB.net PDF Print E-mail
Written by J. Bijvoets   
Tuesday, 05 January 2010 14:39

Print your own document in Visual Basic

Sometimes you want to print documents you have defined yourself. If you don't know you have to write some events for the PrintDocument object yourself, you can get frustrated quite easily.

The trick is you have to define first a PrintDocument, say MyPrintDocument.

Second, you write the following events:

BeginPrint Event

This event triggers only just before the document will be printed

Private Sub MyPrintDocument_BeginPrint(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintEventArgs) Handles MyPrintDocument.BeginPrint

'Initialisation code goes here

'For example:

CurrentPageNr = 0

End Sub

PrintPage Event

This event will be triggered each time a page will be printed. You use this event to draw each page of the document.You have to keep track of the number of pages to draw, the page you are currently drawing, and if there are more pages to draw after the current page.

If there is a page to be drawn after the current page, you have to set the e.HasMorePages to True. This is the second trick that can drive you crazy if you don't know that.

Private Sub MyPrintDocument_PrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles MyPrintDocument.PrintPage

'This event will be triggered for each and every page

'Keep track of page number

CurrentPageNr += 1

Dim PrintAreaHeight, PrintAreaWidth, marginLeft, marginTop As Int32
With MyPrintDocument.DefaultPageSettings
' initializing local variables that contain the bounds of the printing area rectangle
PrintAreaHeight = .PaperSize.Height - .Margins.Top - .Margins.Bottom
PrintAreaWidth = .PaperSize.Width - .Margins.Left - .Margins.Right
marginLeft = .Margins.Left
marginTop = .Margins.Top
End With

If MyPrintDocument.DefaultPageSettings.Landscape Then

'For landscape mode, swap the printing area height and width

Dim iTmp As Int32
iTmp = PrintAreaHeight
PrintAreaHeight = PrintAreaWidth
PrintAreaWidth = iTmp

End If

'Now do the real drawing

'Assume there is a Function, DrawMyPage, having the Page Number as parameter, that draws to a bitmap a particular page of your document.

e.Graphics.DrawImage(DrawMyPage(CurrentPageNr), 0, 0)

'Now check if there are more pages to draw

If CurrentPageNr < CountOfPages Then
e.HasMorePages = True
End If

End Sub

Last Updated on Wednesday, 06 January 2010 06:17