Click here to Skip to main content
11,925,851 members (63,322 online)
Click here to Skip to main content
Add your own
alternative version


74 bookmarked

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


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.


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
    PrintTextControl.DefaultPageSettings = PrintPageSettings
    PrintString = TextToPrint.Text
    PreviewPrint.Document = PrintTextControl
  Catch ex As Exception
  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
    SetupPage.PageSettings = PrintPageSettings
  Catch ex As Exception
  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
      AddHandler PrintTextControl.PrintPage, AddressOf Me.TextPrint
    Catch ex As Exception
    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
      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.HasMorePages = False
End Sub

Private Sub BeginGraphicPrint_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles BeginGraphicPrint.Click
      AddHandler PrintGraphicControl.PrintPage, AddressOf Me.GraphicPrint
    Catch ex As Exception
    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.


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.


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


About the Author

Software Developer
United States United States
No Biography provided

You may also be interested in...

Comments and Discussions

QuestionProblem with Page Setup Pin
jdromeiro19-Mar-14 4:47
memberjdromeiro19-Mar-14 4:47 
AnswerRe: Problem with Page Setup Pin
jdromeiro19-Mar-14 5:08
memberjdromeiro19-Mar-14 5:08 
QuestionText twice on paper Pin
John van der Putte9-Dec-12 5:27
memberJohn van der Putte9-Dec-12 5:27 
i tried to run the project in VS2010 but all my text is printed twice on the paper. First i thought that the problem was the printerdriver. I tried another printer (PDF-printer DoPDF) but it gave me the same result: the printpreview is good but printing gave the wrong results.
GeneralMy vote of 5 Pin
Alberto Molero21-Apr-12 11:10
memberAlberto Molero21-Apr-12 11:10 
GeneralError in selecting printer Pin
Chun219-Sep-07 12:35
memberChun219-Sep-07 12:35 
GeneralRe: Error in selecting printer Pin
Chun220-Sep-07 5:12
memberChun220-Sep-07 5:12 
GeneralPrint Preview Control Pin
pankaj.indore10-Sep-07 3:50
memberpankaj.indore10-Sep-07 3:50 
GeneralRe: Print Preview Control Pin
MatrixCoder15-Sep-07 19:52
memberMatrixCoder15-Sep-07 19:52 
GeneralRe: Print Preview Control Pin
Chun219-Sep-07 12:15
memberChun219-Sep-07 12:15 
GeneralFreshReports Pin
Artem Smirnov24-Aug-07 8:16
memberArtem Smirnov24-Aug-07 8:16 
QuestionImporting the project trouble Pin
crampio4-Aug-07 16:37
membercrampio4-Aug-07 16:37 
AnswerRe: Importing the project trouble Pin
MatrixCoder8-Aug-07 6:56
memberMatrixCoder8-Aug-07 6:56 
QuestionPrinting dynamic values in window application Pin
kk_upadhyay3-Jul-07 2:58
memberkk_upadhyay3-Jul-07 2:58 
AnswerRe: Printing dynamic values in window application Pin
MatrixCoder3-Jul-07 7:46
memberMatrixCoder3-Jul-07 7:46 
QuestionLine Spacing Pin
Gustavo Valdes13-Jun-07 15:08
memberGustavo Valdes13-Jun-07 15:08 
QuestionUsing Watermarks Pin
Unmesh Gundecha16-Mar-07 6:09
memberUnmesh Gundecha16-Mar-07 6:09 
AnswerRe: Using Watermarks Pin
MatrixCoder3-Jul-07 7:47
memberMatrixCoder3-Jul-07 7:47 
QuestionPrinting image over multiple pages Pin
Diesel1319-Feb-07 2:09
memberDiesel1319-Feb-07 2:09 
AnswerRe: Printing image over multiple pages Pin
Duncan Edwards Jones19-Feb-07 3:23
memberDuncan Edwards Jones19-Feb-07 3:23 
GeneralRe: Printing image over multiple pages Pin
Diesel1319-Feb-07 3:34
memberDiesel1319-Feb-07 3:34 
QuestionRe: Printing image over multiple pages Pin
yuxuetaoxp4-Mar-09 16:39
memberyuxuetaoxp4-Mar-09 16:39 
GeneralBug in print setup Pin
Rudolf Jan Heijink14-Jan-07 4:28
memberRudolf Jan Heijink14-Jan-07 4:28 
GeneralRe: Bug in print setup Pin
jdromeiro19-Mar-14 4:49
memberjdromeiro19-Mar-14 4:49 
GeneralBasic Text Printing Code Pin
vp200015-Dec-06 2:58
membervp200015-Dec-06 2:58 
GeneralRe: Basic Text Printing Code Pin
MatrixCoder1-Jan-07 23:17
memberMatrixCoder1-Jan-07 23:17 

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.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.151126.1 | Last Updated 17 Aug 2007
Article Copyright 2006 by MatrixCoder
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid