Printing a Document
The Print method of the PrintDocument class prints a document to the printer specified in the PrinterSettings property. When you call the Print method of the PrintDocument class, the PrintPage event is raised for each page as it prints. Therefore, you would need to create a procedure for that event and add an event handler for it. The procedure that you would create for the PrintPage event does the actual reading of your text file using the StreamReader object that you define.
Printing using the PrintDocument class requires a lot of coding and knowledge of how actual printing works. Fortunately, the .NET Framework provides the My.Computer.Printers namespace, which simplifies your job as a developer.
This namespace wraps up all the complexities of printing and provides you with methods and properties that allow you to print a text document with ease and just a few lines of code. You can use the DefaultPrinter method of this namespace to print to the default printer, or you can use the Item property to specify the printer that you want to print to. Using either one, you can print a text document with as little as two lines of code, as shown in this code snippet:
With My.Computer.Printers.DefaultPrinter
.WriteLine(txtFile.Text)
.Print()
End With |
Now that you know a little bit about how printing works, look at how all this fits together in a Exercise.
Exercise - Working with the PrintDialog Control
1. Open the Dialogs project.
2. On the form, add another button from the Toolbox and set its properties according to the values shown:
-
Set Name to btnPrint.
-
Set Anchor to Top, Right.
-
Set Location to 367, 128.
-
Set Text to Print.
3. Now add a PrintDialog control to the project, dragging and dropping it from the Toolbox onto the form. It will be added to the workspace below the form, and you will accept all default properties for this control.
4. Now switch to the Code Editor so that you can add the required namespaces for printing a file. Add these namespaces to the top of your class:
Imports System.IO
Imports System.Drawing.Printing
Public Class Dialogs |
5. Now add the following variable declarations to the top of your class:
‘Declare variable
Private strFileName As String
Private objStreamToPrint As StreamReader
Private objPrintFont As Font |
6. Select btnPrint in the Class Name combo box and the Click event in the Method Name combo box. Add the following highlighted code to the btnPrint_Click event procedure:
Private Sub btnPrint_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles btnPrint.Click
‘Declare an object for the PrintDocument class
Dim objPrintDocument As PrintDocument = New PrintDocument()
‘Set the DocumentName property
objPrintDocument.DocumentName = “Text File Print Demo”
‘Set the PrintDialog properties
PrintDialog1.AllowPrintToFile = False
PrintDialog1.AllowSelection = False
PrintDialog1.AllowSomePages = False
‘Set the Document property to the objPrintDocument object
PrintDialog1.Document = objPrintDocument
‘Show the Print dialog
If PrintDialog1.ShowDialog() = DialogResult.OK Then
‘If the user clicked on the OK button then set the StreamReader
‘object to the file name in the strFileName variable
objStreamToPrint = New StreamReader(strFileName)
‘Set the print font
objPrintFont = New Font(“Arial”, 10)
‘Add an event handler for the PrintPage event of the
‘objPrintDocument object
AddHandler objPrintDocument.PrintPage, _
AddressOf objPrintDocument_PrintPage
‘Set the PrinterSettings property of the objPrintDocument
‘object to the PrinterSettings property returned from the
‘PrintDialog control
objPrintDocument.PrinterSettings = PrintDialog1.PrinterSettings
‘Print the text file
objPrintDocument.Print()
‘Clean up
objStreamToPrint.Close()
objStreamToPrint = Nothing
End If
End Sub |
7. Now add the following procedure to perform the actually printing:
Private Sub objPrintDocument_PrintPage(ByVal sender As Object, _
ByVal e As System.Drawing.Printing.PrintPageEventArgs)
‘Declare variables
Dim sngLinesPerpage As Single = 0
Dim sngVerticalPosition As Single = 0
Dim intLineCount As Integer = 0
Dim sngLeftMargin As Single = e.MarginBounds.Left
Dim sngTopMargin As Single = e.MarginBounds.Top
Dim strLine As String
‘Work out the number of lines per page.
‘Use the MarginBounds on the event to do this
sngLinesPerpage = _
e.MarginBounds.Height / objPrintFont.GetHeight(e.Graphics)
‘Now iterate through the file printing out each line.
‘This assumes that a single line is not wider than the page
‘width. Check intLineCount first so that we don’t read a line
‘that we won’t print
strLine = objStreamToPrint.ReadLine()
While (intLineCount < sngLinesPerpage And Not (strLine Is Nothing))
‘Calculate the vertical position on the page
sngVerticalPosition = sngTopMargin + _
(intLineCount * objPrintFont.GetHeight(e.Graphics))
‘Pass a StringFormat to DrawString for the
‘Print Preview control
e.Graphics.DrawString(strLine, objPrintFont, Brushes.Black, _
sngLeftMargin, sngVerticalPosition, New StringFormat())
‘Increment the line count
intLineCount = intLineCount + 1
‘If the line count is less than the lines per page then
‘read another line of text
If (intLineCount < sngLinesPerpage) Then
strLine = objStreamToPrint.ReadLine()
End If
End While
‘If we have more lines then print another page
If (strLine <> Nothing) Then
e.HasMorePages = True
Else
e.HasMorePages = False
End If
End Sub |
8. You are now ready to test your code, so run the project.
9. Click the Open button to open a file, and then click the Print button to display the Print dialog box shown in below Figure.
Notice that the Print to file check box as well as the Selection and Pages radio buttons are disabled. This is because you set the AllowPrintToFile, AllowSelection, and AllowSomePages properties in the PrintDialogno control to False.
If you have more than one printer installed, you can choose the name of the printer that you want to use in the list.
10. Click the Print button in the Print dialog box to have your text printed.
click next Page - How It Works. |