Hot News!

Not Available

Click Like or share to support us!

Jan 13, 2012

Printing Component

Providing support for Printing is one of the common tasks during application development. The .NET Framework provides excellent support for Printing documents.
PrintDocument Component
In the .NET Framework, a printed document is represented by the PrintDocument component. The PrintDocument object encapsulates all the information needed to print a page.  They handle the events and operations of printing. The PrintDocument object exposes three properties which are as follows:
PrinterSettings Property: Contains information about the capabilities and settings of the printers.
DefaultPageSettings Property: Encapsulates the configuration for printing each printed page.
PrintController Property: Describes how each page is guided through the printing process.
How Printing Works?
Printing content is provided directly by the application logic in the .NET Framework. You add a PrintDocument object to the project and handle the PrintPage event which is called every time a new page is to be printed. A print job is initiated by the PrintDocument's Print method. This starts the print job and raises one or more events. When the print job begins, aBeginPrint event occurs, followed by the PrintPage event for each page, followed by the EndPage event when the job is done. If the print job contains multiple pages, one PrintPage event will be raised for each page in the job making the PrintPage event to execute multiple times. The PrintPage event is the main event involved in printing documents. To send content to the printer you must handle this event and provide code to render the content in the PrintPage event handler.
PrintDialogs
Print dialogs are supported by the PrintDialog class and they allow us to print the document. To print a document we need to set the Document property of the PrintDialog to PrintDocument object and PrinterSettings to PrinterSettings object. You can print the document by assigning PrintDialog object's PrinterSettings property to the PrinterSettings property of the PrintDocument object and use the PrintDocument object's Print method.
Properties of the Print Dialog are as follows:
AllowPrintTofile: Gets/Sets whether the Print to file checkbox is enabled.
AllowSelection: Gets/Sets whether the selection radio is enabled.
AllowSomePages: Gets/Sets whether the From...To...Page radio button is enabled.
Document: Gets/Sets the PrintDocument used to obtain PrinterSettings.
PrinterSettings: Gets/Sets the PrinterSettings dialog box to modify.
PrintToFile: Gets/Sets whether the Print to file checkbox is enabled.
ShowHelp: Gets/Sets whether the Help button is displayed.
ShowNetwork: Gets/Sets whether the network button is displayed.
PrintPreviewDialog
Print Preview dialogs are supported by the PrintPreviewDialog class and they allow us to preview the document before printing. You can preview a document by setting the Documentproperty of the PrintPreviewDialog object to the PrintDocument object. Once set, the PrintPreviewDialog provides functionality to zoom, print, to view multiple pages of the preview, etc.
PrintPreviewControl
PrintPreview control allows to create our own custom previews. They display print previews and you can use it to create your own custom print preview windows. To use this control you need to set the print document to it's Document property. 
Notable properties of the PrintPreviewControl are as follows:
AutoZoom: When True (default), resizing the control automatically zooms to make all contents visible.
Columns: Gets/Sets the number of pages displayed horizontally.
Rows: Gets/Sets the number of pages displayed vertically.
StartPage: Gets/Sets the apge number of the upper left page.
Zoom: Gets/Sets a value specifying how large the pages will appear.
PageSetupDialog
Page Setup dialogs are used to specify page details for printing. This dialog allows us to set borders and adjustments, headers and footers, portraits, orientation, etc. You use thePrinterSettings property of this dialog to get a Printer Settings object that holds settings the user specified. The PageSetupDialog exposes a Document property that specifies the PrintDocument to use. Setting the Document property binds the specifed PrintDocument to the PageSetupDialog and any changes made in this dialog are updated in the PrinterSettings property.
Print Dialogs 
Let's work with print related controls provided by the .NET Framework. On a new form drag a PrintDialog, PrintDocument, PrintPreviewControl, PrintPreviewDialog, PageSetupDialog, MainMenu and a RichtTextBox contol. Select MainMenu and In the "Type Here" part, type File and under file type Print, PrintPreview, PageSetup and PPControl. The menu should look like this:File->Print, PrintPreview, PageSetup, PPControl. The RichTextBox control is used to load some text in it which will be ready to print. The Form in design view should look like the image below.

Before proceeding further you need to set properties for these dialogs in their properties window. You can set these properties at run time if you wish. Setting them at design time will reduce some lines of code. The necessary changes are listed below.
For PrintDialog1, set the AllowSelection and AllowSomePages properties to True and the Document property to PrintDocument1.
For PrintPreviewDialog1, PageSetupDialog1 and PrintPreviewControl1, set the Document property to PrintDocument1 (for all of them).
Code
Imports System.Drawing.Printing
Public Class Form1 Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "

#End Region

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles MyBase.Load
RichTextBox1.Text = "Programmers have undergone a major change in many years of _
programming various machines. For example, what could take days to create an _
application in other programming languages like C, C++ could be done in hours with _
Visual Basic. Visual Basic provides many interesting sets of tools to aid us in _
building exciting applications. Visual Basic provides these tools to make our _
life far more easier because all the real hard code is already written for us."
'filling the richtextbox with some text that can be used readily
End Sub

Private Sub MenuItem2_Click(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles MenuItem2.Click
If PrintDialog1.ShowDialog = DialogResult.OK Then
'showDialog method makes the dialog box visible at run time
PrintDocument1.Print()
End If
End Sub

Private Sub MenuItem3_Click(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles MenuItem3.Click
Try
PrintPreviewDialog1.ShowDialog()
Catch es As Exception
MessageBox.Show(es.Message)
End Try
End Sub

Private Sub MenuItem4_Click(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles MenuItem4.Click
With PageSetupDialog1
.PageSettings = PrintDocument1.DefaultPageSettings
End With
Try
If PageSetupDialog1.ShowDialog = DialogResult.OK Then
PrintDocument1.DefaultPageSettings = PageSetupDialog1.PageSettings
End If
Catch es As Exception
MessageBox.Show(es.Message)
End Try
End Sub

Private Sub MenuItem5_Click(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles MenuItem5.Click
Try
PrintPreviewControl1.Document = PrintDocument1
Catch es As Exception
MessageBox.Show(es.Message)
End Try
End Sub

Private Sub PrintDocument1_PrintPage(ByVal sender As Object, ByVal e As_
System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
'PrintPage is the foundational printing event. This event gets fired for every
' page that will be printed
Static intCurrentChar As Int32
' declaring a static variable to hold the position of the last printed char
Dim font As New Font("Verdana", 14)
' initializing the font to be used for printing
Dim PrintAreaHeight, PrintAreaWidth, marginLeft, marginTop As Int32
With PrintDocument1.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
' initializing local variables to hold margin values that will serve
' as the X and Y coordinates for the upper left corner of the printing
' area rectangle.
marginLeft = .Margins.Left
marginTop = .Margins.Top
' X and Y coordinate
End With

If PrintDocument1.DefaultPageSettings.Landscape Then
Dim intTemp As Int32
intTemp = PrintAreaHeight
PrintAreaHeight = PrintAreaWidth
PrintAreaWidth = intTemp
' if the user selects landscape mode, swap the printing area height and width
End If

Dim intLineCount As Int32 = CInt(PrintAreaHeight / font.Height)
' calculating the total number of lines in the document based on the height of
' the printing area and the height of the font
Dim rectPrintingArea As New RectangleF(marginLeft, marginTop, PrintAreaWidth, PrintAreaHeight)
' initializing the rectangle structure that defines the printing area
Dim fmt As New StringFormat(StringFormatFlags.LineLimit)
'instantiating the StringFormat class, which encapsulates text layout information
Dim intLinesFilled, intCharsFitted As Int32
e.Graphics.MeasureString(Mid(RichTextBox1.Text, intCurrentChar + 1), font,_
New SizeF(PrintAreaWidth, PrintAreaHeight), fmt, intCharsFitted, intLinesFilled)
' calling MeasureString to determine the number of characters that will fit in
' the printing area rectangle
e.Graphics.DrawString(Mid(RichTextBox1.Text, intCurrentChar + 1), font,_
Brushes.Black, rectPrintingArea, fmt)
' print the text to the page
intCurrentChar += intCharsFitted
'advancing the current char to the last char printed on this page
< TextBox1.Text.Length Then
If intCurrentChar e.HasMorePages=True
'HasMorePages tells the printing module whether another PrintPage event should be fired
Else
e.HasMorePages = False
intCurrentChar = 0
End If
End Sub

End Class

The above code will throw exceptions if you don't have a printer attached to your machine.

No comments:

Post a Comment