Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Blogs | Beginners
 | Consulting  
Submit an Article 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
New MS SQL 2008 Available - DiscountASP.NET
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » Printing » Printing in VB.NET

Printing in VB.NET

This article explains about Printing in VB.NET.Printing is all carried out through components included in the toolbox. The main component that talks to the printer is the PrintDocument component.

Author Rank:
Technologies: .NET 1.0/1.1, .NET 1.0/1.1,Visual Basic .NET
Total downloads : 2014
Total page views :  104998
Rating :
 3.5/5
This article has been rated :  2 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
PrintExample.zip
 
ArticleAd
Become a Sponsor


Related EbooksTop Videos




Components, components, components.  Using components is the difference between writing an application in one week vs. an application in a few hours.  Printing is all carried out through components included in the toolbox.   The main component that talks to the printer is the PrintDocument component.  To use this component, just call the Print function and intercept the PrintPage event.  Below are the routines that do this:

Protected Sub PrintFile_Click(sender As Object, e As
System.EventArgs)printDialog1.Document = ThePrintDocument
Dim strText As String = Me.richTextBox1.Text
myReader =
New StringReader(strText)
If printDialog1.ShowDialog() = DialogResult.OK Then
Me
.ThePrintDocument.Print()
End If
End
Sub 'PrintFile_Click
Protected Sub ThePrintDocument_PrintPage(sender As Object, ev As System.Drawing.Printing.PrintPageEventArgs)
Dim linesPerPage As Single = 0
Dim yPosition As Single = 0
Dim count As Integer = 0
Dim leftMargin As Single = ev.MarginBounds.Left
Dim topMargin As Single = ev.MarginBounds.Top
Dim line As String = Nothing
Dim
printFont As Font = Me.richTextBox1.Font
Dim myBrush As New SolidBrush(Color.Black)
' Work out the number of lines per page, using the MarginBounds.
linesPerPage = ev.MarginBounds.Height / printFont.GetHeight(ev.Graphics)
' Iterate over the string using the StringReader, printing each line.
While count < linesPerPage And Not ((line <<= myReader.ReadLine()) Is Nothing) 'ToDo: Unsupported feature: assignment within expression. "=" changed to "<="
' calculate the next line position based on
' the height of the font according to the printing device yPosition = topMargin + (count * printFont.GetHeight(ev.Graphics));// draw the next line in the rich edit control
ev.Graphics.DrawString(line, printFont, myBrush, leftMargin, yPosition, New StringFormat())
count += 1
End While ' If there are more lines, print another page. if (line != null)ev.HasMorePages = True
ev.HasMorePages = False
myBrush.Dispose()
End Sub 'ThePrintDocument_PrintPage

PrintFile_Click is called from the Print Menu.This routine first assigns the PrintDialog component to the document being printed.  The dialog is shown using ShowDialog so the user can set their print settings and to decide whether to print or not.  After ThePrintDocument.Print is called, the printing process begins.  The PrintPage event is automatically called by the system to print the desired page information.  The PrintPageEventArgs ev contains the Device Contexts ev.Graphics to use for drawing to the Printer.  In this example we read each line of text from the rich text edit control using a StringReader.  The StringReader class gives us the ability to treat a string like a stream and take advantage of the ReadLine function of the StringReader for reading each line out of the text edit control.  We can calculate the position of the lines based on margins and the height of the font.  It's interesting to note, that in order to predict the font height for the printer, we pass it the Device context of the printer in the GetHeight function (printFont.GetHeight(ev.Graphics())).  This is because the font height on the screen pixels is different than the font height in printer pixels.  The PrintPageEventArg attribute HasMorePages is continually set so that the PrintPage Event is triggered if there are more lines in the textbox than the current page can hold.

Print Preview

PrintPreview behaves a heck of a lot like Print as seen below:

Protected Sub PreviewFile_Click(sender As Object, e As System.EventArgs)
Try
Dim
strText As String = Me.richTextBox1.Text ' read string from editor window
myReader = New StringReader(strText)
Dim printPreviewDialog1 As New PrintPreviewDialog() ' instantiate new print preview dialog
printPreviewDialog1.Document = Me.ThePrintDocument
printPreviewDialog1.BorderStyle = FormBorderStyle.Fixed3D
printPreviewDialog1.ShowDialog()
' Show the print preview dialog, uses print page event to draw preview screen
Catch exp As Exception
System.Console.WriteLine(exp.Message.ToString())
End Try
End
Sub 'PreviewFile_Click

The PrintPreview component also triggers the PrintPage event, but instead of outputting to the printer it outputs to the Print Preview Screen. 

Other Editor Functions

The Open and Save menu items use streams to read and write the files.  The persistence of files is discussed in other articles on this site.


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
Mike Gold
Michael Gold is President of Microgold Software Inc., makers of the WithClass UML Tool. His company is a Microsoft VBA Partner and Borland Partner. Mike is a Microsoft MVP and founding member of C# Corner. He has a BSEE and MEng EE from Cornell University and has consulted for Chase Manhattan Bank, JP Morgan, Merrill Lynch, and Charles Schwab. Currently he is a senior developer at Finisar Corp. He has been involved in several .NET book projects, and is currently working on a book for using .NET with embedded systems. He can be reached at mike@c-sharpcorner.com
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Boost the performance of your .NET applications
“ANTS Profiler took us straight to the specific areas of our code which were the cause of our performance issues." Terry Phillips, Sr. Developer, Harley-Davidson Dealer Systems. Download your free trial of ANTS Profiler.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
PrintExample.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
ArticleAd
Become a Sponsor
Latest Comments:
Subject Posted By Posted On
Printer settingsraees11/6/2006

How can i increase the printable area dynamically in vb.net?

Reply | Email | Delete | Modify | 
Printing the string in different font sizeKumar4/19/2007
Hi I want to Pint a string in different text size.... for the first line I want to give the size as 15pt and bold and the next line in 11pt and regular.... Is this possible ............ If so how
Reply | Email | Delete | Modify | 
Helpful, but...Hal7/11/2007
I notice that this app doesn't allow the user to print a selected portion of the text. Any chance you could add that capability?
Reply | Email | Delete | Modify | 
Getting error on using this code please help!!sudha8/6/2007
Hi First i should say thanks for posting such useful topic. every thing is working fine but i am getting an error at last. what actually i need is to print the text of a richtextbox on a button click. i am getting error at printdocument1.print() stating "Your file waiting to be printed was deleted". Actually i dont have a printer connected to my system but i am printing with msoffice document imaging. can you please help me in solving this error.
Reply | Email | Delete | Modify | 
How to print DataGridView ?Simran11/23/2007
Require to print DataGridView contents in tabular format. Simran
Reply | Email | Delete | Modify | 
Cool Article, but you wrote a lot of code and spent a lot of timeJorge2/26/2008
a better way to print everything you want is here: http://www.neuronlabs.com/sendfile.php?file=nlsw0001.html
Reply | Email | Delete | Modify | 
i need to print panel content in multi pagesamy3/4/2008
hi mike i have one Q I need to print panel content put in multi page thnx yours samy samy4u@hotmail.com
Reply | Email | Delete | Modify | 
You got THAT rightTom4/3/2009
You wrote Components, components, components. Using components is the difference between writing an application in one week vs. an application in a few hours. you sure got that part right -- from what I've been reading (and experiencing) using components to generate printed output requires weeks of programming vs. a few hours as it did before... [BTW: I did find a microsoft support entry that makes available the "old" method of printing as a library component; unfortunately, I didn't tag it in my history]
Reply | Email | Delete | Modify | 
how to print the form in VB.NetDoug5/27/2009
How am I able to print the form on VB.Net, meaning, my user gets the option of printing that form by the way it looks when he clicks print in my tool bar.
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved