Blue Theme Orange Theme Green Theme Red Theme
 
DevExpress Free UI Controls
Home | Forums | Videos | Photos | Blogs | Beginners | Advertise with Us
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Discover the top 5 tips for understanding .NET Interop
Search :       Advanced Search »
Home » VB.NET » 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 :
Page Views : 250993
Downloads : 5576
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
PrintExample.zip
 
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 




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.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
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.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
DevExpress Free UI Controls
Become a Sponsor
 Comments
Printer settings by raees On November 6, 2006

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

Reply | Email | Modify 
Printing the string in different font size by Kumar On April 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 | Modify 
Helpful, but... by Hal On July 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 | Modify 
Getting error on using this code please help!! by sudha On August 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 | Modify 
How to print DataGridView ? by Simran On November 23, 2007
Require to print DataGridView contents in tabular format. Simran
Reply | Email | Modify 
Cool Article, but you wrote a lot of code and spent a lot of time by Jorge On February 26, 2008
a better way to print everything you want is here: http://www.neuronlabs.com/sendfile.php?file=nlsw0001.html
Reply | Email | Modify 
i need to print panel content in multi page by samy On March 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 | Modify 
You got THAT right by Tom On April 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 | Modify 
how to print the form in VB.Net by Doug On May 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 | Modify 
print by Leigh On January 17, 2010

whats the best method for printing many texts boxes to a page and positoning them

Reply | Email | Modify 
Count page numbers in a rich textbox? by Tim On March 16, 2010
Hello,

Anybody know how to add the page numbers like word 2007
on the form in a label.text . when i add text to a rich textbox i wanna see how many page's i have
before i print.

Please mail:
Dummy1912@hotmail.com

Thanks

Dummy1912
Reply | Email | Modify 
print problem by abdul shafiq On June 28, 2010
Hi Mike,
I just want to ask.
If i need to print using template paper that contains table and etc,
means  i need to pull data from database to put on that table and print.
Regards.
Reply | Email | Modify 
print document by Indra On July 19, 2010
i want to change paper size dynamic according to tecxt box.
Reply | Email | Modify 
Re: print document by Mike On July 19, 2010
You can alter paper size in the QuerySettings Event handler.  Inside the handler there is an event arguement that will let you drill down to paper size and set it.
Reply | Email | Modify 
Print a datagridview in vb 2005 by Darwin On August 12, 2010
How can i print a datagridview with limint of caracter in the lines
Reply | Email | Modify 
print by Natali On October 12, 2010
how can i change on a click the vb code , to a code when it reaches the printer
so that the printer will not be overloaded
Reply | Email | Modify 
easy way printing by yi On October 24, 2010
is there a easy way for printing in vb
when you have a label and a textbox and also a button
when you click on the button the label text and the textbox text must be printed on paper
greatings from the netherlands Yi
yizouff@gmail.com
Reply | Email | Modify 
i like by sappe On December 14, 2010
i like this site, thanks my friend..
Reply | Email | Modify 
Useful code by John Robin On January 13, 2011
Many thanks for this useful example, the only simple and reusable one I have found.
Reply | Email | Modify 
Doesn't work by Kirk On April 22, 2011
I downloaded this project and opened it in VB2010 and it converted. I ran it and printing two pages worth of text it loads the printer with 27 pages of nothing
Reply | Email | Modify 
Re: Doesn't work by John Robin On April 23, 2011
I've just tested the program in VS2010. As far as I can see it works exactly as it did in VS2008. I had to adapt it to suit the needs of my project. Maybe you need to do this?
Reply | Email | Modify 
listview by Ericko On September 19, 2011
Please could you assist in previewing and printing in list view. i have tried with this code but i only get a blank page. thanks in advance.
Reply | Email | Modify 
listview by Ericko On September 19, 2011
Please could you assist in previewing and printing in list view. i have tried with this code but i only get a blank page. thanks in advance.
Reply | Email | Modify 
6 Months Free & No Setup Fees ASP.NET Hosting!
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.