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

Basic Text and Image Printing

By , 17 Aug 2007
 

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)

About the Author

MatrixCoder
Software Developer
United States United States
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionText twice on papermemberJohn van der Putte9 Dec '12 - 4:27 
GeneralMy vote of 5memberAlberto Molero21 Apr '12 - 10:10 
GeneralError in selecting printermemberChun219 Sep '07 - 11:35 
GeneralRe: Error in selecting printermemberChun220 Sep '07 - 4:12 
GeneralPrint Preview Controlmemberpankaj.indore10 Sep '07 - 2:50 
GeneralRe: Print Preview ControlmemberMatrixCoder15 Sep '07 - 18:52 
GeneralRe: Print Preview ControlmemberChun219 Sep '07 - 11:15 
GeneralFreshReportsmemberArtem Smirnov24 Aug '07 - 7:16 
QuestionImporting the project troublemembercrampio4 Aug '07 - 15:37 
I like the printing project. But I'm having difficulties making it work. If I import the project I do not know or can't access the window. If I add the form to the project, the print preview does not show and I'm stuck. I'm new to VS. Any suggestions? Thanks!Frown | :(
AnswerRe: Importing the project troublememberMatrixCoder8 Aug '07 - 5:56 
QuestionPrinting dynamic values in C#.net window applicationmemberkk_upadhyay3 Jul '07 - 1:58 
AnswerRe: Printing dynamic values in C#.net window applicationmemberMatrixCoder3 Jul '07 - 6:46 
QuestionLine SpacingmemberGustavo Valdes13 Jun '07 - 14:08 
QuestionUsing WatermarksmemberUnmesh Gundecha16 Mar '07 - 5:09 
AnswerRe: Using WatermarksmemberMatrixCoder3 Jul '07 - 6:47 
QuestionPrinting image over multiple pagesmemberDiesel1319 Feb '07 - 1:09 
AnswerRe: Printing image over multiple pagesmemberDuncan Edwards Jones19 Feb '07 - 2:23 
GeneralRe: Printing image over multiple pagesmemberDiesel1319 Feb '07 - 2:34 
QuestionRe: Printing image over multiple pagesmemberyuxuetaoxp4 Mar '09 - 15:39 
GeneralBug in print setupmemberRudolf Jan Heijink14 Jan '07 - 3:28 
GeneralBasic Text Printing Codemembervp200015 Dec '06 - 1:58 
GeneralRe: Basic Text Printing CodememberMatrixCoder1 Jan '07 - 22:17 
GeneralRe: Basic Text Printing CodememberSilver-Grey3 Jan '07 - 8:04 
GeneralRe: Basic Text Printing CodememberMatrixCoder4 Jan '07 - 11:36 
GeneralPositioning the text on the formmembergurdeeptoor3 Oct '07 - 2:31 

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

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