Click here to Skip to main content
Click here to Skip to main content

Basic Text and Image Printing

, 17 Aug 2007 CPOL
Rate this:
Please Sign up or sign in to vote.
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:

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:

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.

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

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:

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:

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)

Share

About the Author

MatrixCoder
Software Developer
United States United States
No Biography provided

Comments and Discussions

 
QuestionProblem with Page Setup Pinmemberjdromeiro19-Mar-14 3:47 
AnswerRe: Problem with Page Setup Pinmemberjdromeiro19-Mar-14 4:08 
QuestionText twice on paper PinmemberJohn van der Putte9-Dec-12 4:27 
GeneralMy vote of 5 PinmemberAlberto Molero21-Apr-12 10:10 
GeneralError in selecting printer PinmemberChun219-Sep-07 11:35 
GeneralRe: Error in selecting printer PinmemberChun220-Sep-07 4:12 
GeneralPrint Preview Control Pinmemberpankaj.indore10-Sep-07 2:50 
GeneralRe: Print Preview Control PinmemberMatrixCoder15-Sep-07 18:52 
GeneralRe: Print Preview Control PinmemberChun219-Sep-07 11:15 
GeneralFreshReports PinmemberArtem Smirnov24-Aug-07 7:16 
QuestionImporting the project trouble Pinmembercrampio4-Aug-07 15:37 
AnswerRe: Importing the project trouble PinmemberMatrixCoder8-Aug-07 5:56 
QuestionPrinting dynamic values in C#.net window application Pinmemberkk_upadhyay3-Jul-07 1:58 
AnswerRe: Printing dynamic values in C#.net window application PinmemberMatrixCoder3-Jul-07 6:46 
QuestionLine Spacing PinmemberGustavo Valdes13-Jun-07 14:08 
QuestionUsing Watermarks PinmemberUnmesh Gundecha16-Mar-07 5:09 
AnswerRe: Using Watermarks PinmemberMatrixCoder3-Jul-07 6:47 
QuestionPrinting image over multiple pages PinmemberDiesel1319-Feb-07 1:09 
AnswerRe: Printing image over multiple pages PinmemberDuncan Edwards Jones19-Feb-07 2:23 
GeneralRe: Printing image over multiple pages PinmemberDiesel1319-Feb-07 2:34 
QuestionRe: Printing image over multiple pages Pinmemberyuxuetaoxp4-Mar-09 15:39 
GeneralBug in print setup PinmemberRudolf Jan Heijink14-Jan-07 3:28 
GeneralRe: Bug in print setup Pinmemberjdromeiro19-Mar-14 3:49 
GeneralBasic Text Printing Code Pinmembervp200015-Dec-06 1:58 
GeneralRe: Basic Text Printing Code PinmemberMatrixCoder1-Jan-07 22:17 

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

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

| Advertise | Privacy | Mobile
Web01 | 2.8.141015.1 | Last Updated 17 Aug 2007
Article Copyright 2006 by MatrixCoder
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid