Click here to Skip to main content
15,879,474 members
Articles / Programming Languages / Visual Basic
Article

Basic Text and Image Printing

Rate me:
Please Sign up or sign in to vote.
4.45/5 (19 votes)
17 Aug 2007CPOL3 min read 195.8K   7.5K   80   31
This article will teach you the basics of printing text and graphics with the PrintDocument, PrintDialog, PrintPreview, and PageSetup controls.

Sample Image - Screen1.jpg

Introduction

Printing can be a complicated process, depending on what you want to print, and how you want to configure it. Luckily, .NET 2.0 has helped make the process easier, but it can still be a little confusing at times, especially when dealing with advanced printing configuration. So, this article will show you where to begin the printing process.

Beginning

Now to start, you will have to include a major part of the .NET Framework, System.Drawing.Printing, which handles all generic printing. And, there are four controls that have to be added to your form, the PrintDocument, PrintDialog, PrintPreview, and the PageSetup controls. Now, the PrintDialog control is not required, but is a good thing to include because it allows the user to select printer properties, page numbers, and many other essential options.

Setting Up to Print

Now, you will have to prepare everything to print your document. The TextPrint procedure will set the text that will be printed, the font, and the color to print in, and the Brush color. Like so:

VB
Private Sub TextPrint(ByVal sender As Object, ByVal e As PrintPageEventArgs)
    e.Graphics.DrawString(TextToPrint.Text, _
        New Font(TextToPrint.Font, TextToPrint.Font.Style), Brushes.Black, 120, 120)
    e.HasMorePages = False
End Sub

Next, you will call the PrintPreview control, which will allow you to see how the text looks before the page is printed. The actual dialog used for this isn't as nice looking as all the other dialogs. The dialog will look like this:

Screenshot - Screen2.jpg

Now, to call the code that will send the preview control the text and the font settings:

VB
Private Sub PreviewText_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles PreviewText.Click
  Try
    PrintTextControl.DefaultPageSettings = PrintPageSettings
    PrintString = TextToPrint.Text
    PreviewPrint.Document = PrintTextControl
    PreviewPrint.ShowDialog()
  Catch ex As Exception
    MsgBox(ex.Message)
  End Try
End Sub

The PageSetup control is next, and is very simple. All you do is send all the selected settings in the control to the PrintDocument control.

VB
Private Sub PageSetup_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles PageSetup.Click
  Try
    SetupPage.PageSettings = PrintPageSettings
    SetupPage.ShowDialog()
  Catch ex As Exception
    MsgBox(ex.Message)
  End Try
End Sub

And the window will look like this:

Screenshot - Screen3.jpg

Finally, before getting to the actual printing, you have to call the PrintDocument control to start the printing. Here, when the button BeginTextPrint is clicked, it will show a Print dialog, which will look like this:

Screenshot - Screen4.jpg

VB
Private Sub BeginTextPrint_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles BeginTextPrint.Click
  If PrintWin.ShowDialog = Windows.Forms.DialogResult.OK Then
    Try
      AddHandler PrintTextControl.PrintPage, AddressOf Me.TextPrint
      PrintTextControl.Print()
    Catch ex As Exception
      MsgBox(ex.Message)
    End Try
  End If
End Sub

Printing Text

We are now done with all the preparation, and are ready to do the actual printing. This is where it can get confusing for some people. In the PrintDocument.PrintPage (PrintTextControl), you will use the following code:

VB
Private Sub PrintTextControl_PrintPage(ByVal sender As System.Object, _
        ByVal e As System.Drawing.Printing.PrintPageEventArgs)_
        Handles PrintTextControl.PrintPage

  PrintTextControl.DocumentName = "Test Document"

  Dim PrintFont As New Font(TextToPrint.Font, TextToPrint.Font.Style)
  Dim numChars As Integer
  Dim numLines As Integer
  Dim stringForPage As String
  Dim strFormat As New StringFormat

  Dim rectDraw As New RectangleF(e.MarginBounds.Left, _
    e.MarginBounds.Top, e.MarginBounds.Width, e.MarginBounds.Height)

    'Determine maximum text ammount and spaces lines
    Dim sizeMeasure As New SizeF(e.MarginBounds.Width, _
        e.MarginBounds.Height - PrintFont.GetHeight(e.Graphics))

    'Break in between words
     strFormat.Trimming = StringTrimming.Word

     'Determines ammount of words and lines that can fit on a page
     e.Graphics.MeasureString(PrintString, PrintFont, sizeMeasure, _
        strFormat, numChars, numLines)
 
    stringForPage = PrintString.Substring(0, numChars)

    'Print strings to page
    e.Graphics.DrawString(stringForPage, PrintFont, _
                          Brushes.Black, rectDraw, strFormat)

    'Determine whether or not there are more pages to print
    If numChars < PrintString.Length Then
      'Remove printed text from string
      PrintString = PrintString.Substring(numChars)
      e.HasMorePages = True
    Else
      e.HasMorePages = False

      'Restore string after printing
      PrintString = TextToPrint.Text
    End If
End Sub

Everything in the code above sets page properties and takes settings set by other controls, users, and dialogs, puts them together, sets the page up (line/letter spacing) and the font. This is where most of the configuration goes on.

Now, about all the settings. The PrintTextControl.DocumentName sets the name of the document that will be printed. This is also useful if the user has multiple documents standing in line in the Print Spooler so they can distinguish which document is which. And the StringTrimming sets the amount of words and lines that can fit on a single page.

Printing Graphics

Printing graphics isn't much different than printing text (for a basic configuration). All you will have to do is use the following code:

VB
Private Sub GraphicPrint(ByVal sender As Object, ByVal e As PrintPageEventArgs)
    e.Graphics.DrawImage(Image.FromFile(GraphicLocation.Text), _
        e.Graphics.VisibleClipBounds)
    e.HasMorePages = False
End Sub

Private Sub BeginGraphicPrint_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles BeginGraphicPrint.Click
    Try
      AddHandler PrintGraphicControl.PrintPage, AddressOf Me.GraphicPrint
      PrintGraphicControl.Print()
    Catch ex As Exception
      MsgBox(ex.Message)
    End Try
End Sub

This is basically the same as the first bit of code used for the text printing, with only a few modifications. The main key is that you will have to use a separate PrintDocument control for the graphic printing. And, you won't need to add any settings to it (for a basic configuration). The reason that printing graphics doesn't require properties to be set in its PrintDocument control is because the program doesn't have to set fonts, line/letter spacing and etc., to the print control, unlike text printing.

Conclusion

Besides the coding, the explanation of printing is difficult. The comments inside the code should provide you with further explanations of how everything works. Also, inside the example program, I included a Font dialog to give you an example of how to print different types of fonts as well as different colors.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Praisefor thanx Pin
RaHu00730-Jun-16 17:20
professionalRaHu00730-Jun-16 17:20 
QuestionProblem with Page Setup Pin
jdromeiro19-Mar-14 3:47
jdromeiro19-Mar-14 3:47 
AnswerRe: Problem with Page Setup Pin
jdromeiro19-Mar-14 4:08
jdromeiro19-Mar-14 4:08 
QuestionText twice on paper Pin
John van der Putte9-Dec-12 4:27
John van der Putte9-Dec-12 4:27 
GeneralMy vote of 5 Pin
Alberto M.21-Apr-12 10:10
Alberto M.21-Apr-12 10:10 
GeneralError in selecting printer Pin
Chun219-Sep-07 11:35
Chun219-Sep-07 11:35 
GeneralRe: Error in selecting printer Pin
Chun220-Sep-07 4:12
Chun220-Sep-07 4:12 
nevermind... i got it
GeneralPrint Preview Control Pin
Pankaj - Joshi10-Sep-07 2:50
Pankaj - Joshi10-Sep-07 2:50 
GeneralRe: Print Preview Control Pin
MatrixCoder15-Sep-07 18:52
MatrixCoder15-Sep-07 18:52 
GeneralRe: Print Preview Control Pin
Chun219-Sep-07 11:15
Chun219-Sep-07 11:15 
GeneralFreshReports Pin
Artem Smirnov24-Aug-07 7:16
professionalArtem Smirnov24-Aug-07 7:16 
QuestionImporting the project trouble Pin
crampio4-Aug-07 15:37
crampio4-Aug-07 15:37 
AnswerRe: Importing the project trouble Pin
MatrixCoder8-Aug-07 5:56
MatrixCoder8-Aug-07 5:56 
QuestionPrinting dynamic values in C#.net window application Pin
kk_upadhyay3-Jul-07 1:58
kk_upadhyay3-Jul-07 1:58 
AnswerRe: Printing dynamic values in C#.net window application Pin
MatrixCoder3-Jul-07 6:46
MatrixCoder3-Jul-07 6:46 
QuestionLine Spacing Pin
Gustavo Valdes13-Jun-07 14:08
Gustavo Valdes13-Jun-07 14:08 
QuestionUsing Watermarks Pin
Unmesh Gundecha16-Mar-07 5:09
Unmesh Gundecha16-Mar-07 5:09 
AnswerRe: Using Watermarks Pin
MatrixCoder3-Jul-07 6:47
MatrixCoder3-Jul-07 6:47 
QuestionPrinting image over multiple pages Pin
GreenShoes19-Feb-07 1:09
GreenShoes19-Feb-07 1:09 
AnswerRe: Printing image over multiple pages Pin
Duncan Edwards Jones19-Feb-07 2:23
professionalDuncan Edwards Jones19-Feb-07 2:23 
GeneralRe: Printing image over multiple pages Pin
GreenShoes19-Feb-07 2:34
GreenShoes19-Feb-07 2:34 
QuestionRe: Printing image over multiple pages Pin
yuxuetaoxp4-Mar-09 15:39
yuxuetaoxp4-Mar-09 15:39 
GeneralBug in print setup Pin
Rudolf Jan14-Jan-07 3:28
Rudolf Jan14-Jan-07 3:28 
GeneralRe: Bug in print setup Pin
jdromeiro19-Mar-14 3:49
jdromeiro19-Mar-14 3:49 
GeneralBasic Text Printing Code Pin
vp200015-Dec-06 1:58
vp200015-Dec-06 1:58 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.