Blue Theme Orange Theme Green Theme Red Theme
 
Nevron Chart
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
DevExpress UI Controls
Search :       Advanced Search »
Home » Printing in C# » Printing in C#

Printing in C#

This sample shows you how to print a text box contents in C# and .NET.

Author Rank :
Page Views : 314168
Downloads : 9089
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
PrintExample.zip
 
 
Team Foundation Server Hosting
Become a Sponsor
Discover the top 5 tips for understanding .NET Interop
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 void PrintFile_Click (object sender, System.EventArgs e)
{
printDialog1.Document = ThePrintDocument;
string strText = this.richTextBox1.Text;
myReader =
new StringReader(strText);
if (printDialog1.ShowDialog() == DialogResult.OK)
{
this.ThePrintDocument.Print();
}
}
protected void ThePrintDocument_PrintPage (object sender,System.Drawing.Printing.PrintPageEventArgs ev)
{
float linesPerPage = 0;
float yPosition = 0;
int count = 0;
float leftMargin = ev.MarginBounds.Left;
float topMargin = ev.MarginBounds.Top;
string line = null;
Font printFont =
this.richTextBox1.Font;
SolidBrush myBrush =
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 && ((line=myReader.ReadLine()) != null))
{
// 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++;
}
// If there are more lines, print another page.
if (line != null)
ev.HasMorePages =
true;
else
ev.HasMorePages = false;
myBrush.Dispose();
}

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 their 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 void PreviewFile_Click (object sender, System.EventArgs e)
{
try
{
string strText = this.richTextBox1.Text; // read string from editor window
myReader = new StringReader(strText);
PrintPreviewDialog printPreviewDialog1 =
new PrintPreviewDialog(); // instantiate new print preview dialog
printPreviewDialog1.Document = this.ThePrintDocument ;
printPreviewDialog1.BorderStyle = FormBorderStyle.Fixed3D ;
printPreviewDialog1.ShowDialog();
// Show the print preview dialog, uses print page event to draw preview screen
}
catch(Exception exp)
{
System.Console.WriteLine(exp.Message.ToString());
}
}

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. See Using ListView in C#.  In future articles we will add find/replace functionality to this text editor to make it a bit more powerful.

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:
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
 Comments
Print from textboz by Ahsan On June 18, 2007
Very helpful for me. Hope that he provides more useful feature for C# developer.
Reply | Email | Modify 
Re: Print from textboz by renuka On April 21, 2010
sir printExample works fine in c#...
but when i m trying to do the same in vb.net
it gives me an error-->
Error    6    Attribute specifier is not a complete statement. Use a line continuation to apply the attribute to the following statement.   

on the line -->
 <System.Runtime.InteropServices.DllImport("gdi32.dll")>

Private Sub BitBlt(ByVal hdcDest As IntPtr, ByVal nXDest As Integer, ByVal nYDest As Integer, ByVal nWidth As Integer, ByVal nHeight As Integer, ByVal hdcSrc As IntPtr, ByVal nXSrc As Integer, ByVal nYSrc As Integer, ByVal dwRop As System.Int32) as boolean
Reply | Email | Modify 
printing by jessie On June 28, 2007
i tried this example, 1 thing i notice is that when i type on the textbox 3 to 4 lines without using return key, the lines were printed off bounds. its like being printed on just one line instead of 3 or 4.
Reply | Email | Modify 
peint word documents by Pierse On August 22, 2007
can you help me about preview a word document and print it by addressing the file name
Reply | Email | Modify 
Printing in C# and .NET by ehx On January 6, 2008
Hi Mike, I read your above article and wonder if I can instead of printing to a printer, I create a text file . Is there a component that print a content of a document to a text file. Thanks Al ehx5@yahoo.com
Reply | Email | Modify 
Re: Printing in C# and .NET by Mike On January 7, 2008
It would probably just be easier to stream the data to a text file using the FileStream or StreamWriter classes.
Reply | Email | Modify 
print document by Osama On January 28, 2008
how can i define a print document to print preview in console application cause it returns nothing
Reply | Email | Modify 
Re: print document by Mike On January 29, 2008
you would need to serialize your console to a file and open the file in a windows form.  then you can take advantage of the printdocument, print preview and other great printing facilities in .NET.
Reply | Email | Modify 
Word wrapping by Jamie On February 12, 2008

Edit: I figured out how to do this in an MDI setup.  but my question to you is how do we account for lines of text that are to long for the page, how do we make it so that it will wrap to the next line.

Reply | Email | Modify 
Thank you!!!! by Peter On October 21, 2008
Finally an article that made me understand how the blasted thing works! MSDN is junk, I have been reading it for a day and a half and haven't been able to produce a single printed page. After reading this, thou, I am printing (after 5 minutes of adopting this code to my needs). Thank you very much!
Reply | Email | Modify 
error by Francesc On November 16, 2008
I have a problem with "StringReader(strText);" The complation don't fount de class. Some idea? Thanks
Reply | Email | Modify 
Re: error by Albertto On February 20, 2009

using System.IO;

Reply | Email | Modify 
Printing by Nikhil On March 18, 2009
Please tell me how can i print a form which is containing textboxes,buttons and more controls and i want to print this as it is... help me.... thnks
Reply | Email | Modify 
Thanks by Alex On April 4, 2009
Hey , Thanks, This was very useful. Regards, Alex
Reply | Email | Modify 
Is it possible to change the MArgin Bounds by nandan On May 23, 2009
Nice article. Can we change the default MarginBounds height for Left and Top margins, because I need it in my project
Reply | Email | Modify 
doesn't work by Ken On August 14, 2009
Nice article, but it doesn't work... for multiple pages.  Just prints the first page and quits.
Reply | Email | Modify 
Re: doesn't work by Mike On February 28, 2010
for multiple pages, you'll need to set the HasMultiplePages flag in the app to true, and set it to false when you've printed all the pages in your PrintPage event handler.
Reply | Email | Modify 
Printing the output of a program by Marinus On February 10, 2010
Howzit ive written a program in C++ and now id like to print the output which the program gives me. Currently the last line shown on the window is "Press any key to continue..." so whenever i try to print screen the window vanishes. How can i print the output without losing the information??
Reply | Email | Modify 
Re: Printing the output of a program by Mike On February 28, 2010
it's a different story if you are printing output from a console app.  You'll need to use pinvoke to make direct calls to the printer SDK in order to print text in a console app.
Reply | Email | Modify 
printing by renuka On April 21, 2010
sir printExample works fine in c#...
but when i m trying to do the same in vb.net
it gives me an error-->
Error    6    Attribute specifier is not a complete statement. Use a line continuation to apply the attribute to the following statement.   

on the line -->
 <System.Runtime.InteropServices.DllImport("gdi32.dll")>

Private Sub BitBlt(ByVal hdcDest As IntPtr, ByVal nXDest As Integer, ByVal nYDest As Integer, ByVal nWidth As Integer, ByVal nHeight As Integer, ByVal hdcSrc As IntPtr, ByVal nXSrc As Integer, ByVal nYSrc As Integer, ByVal dwRop As System.Int32) as boolean

please help me to sort his problem...
thank you..

Reply | Email | Modify 
Doubt by divya On April 26, 2010
Hi
 This is a really good article... that helped a lot.
I have a doubt , am new to c#, tell me how can i catch exception raised while printing through Printpreview dialog.
FOreg.  through pagesetup, i changed my printer to a Pdf convertor.
next through Print preview i clicked on Print icon since i had selectd the Pdf convertor, it will ask me to give the filename to be p[rinted as pdf.
But  instead of giving the filename, i click on cancel.
Now... this raises a unhandled exception... i cannot directly catch in the print preview dialog. Cam u help me..
Reply | Email | Modify 
Re: Doubt by walter On May 7, 2010
ciao mike .
thanks for your example .
I'm doing some exercise about the printing and i'm readin a book , programming windows in c# written by mr. petzold .
Well i had converted your program and test it .
It is working but when i print the document , i don't know why ,the pages printed are strange .
Some characters aren't drawen and the document is printed out of the page bounds  .
Let me understand ....does the informations got by eventargs are about the printer after setting it ?
Thanks for your answer
walter
Reply | Email | Modify 
Regarding printing problem by Kiran On August 15, 2010
Dear sir, The above example work for me. My another problem is : I want to print a receipt of supermarket through dot matrix printer. We use Paper in roll for that. How to stop feeding page rolling just at the end of last line??

Currently it is throwing whole role after printing.
Reply | Email | Modify 
Re: Regarding printing problem by Mike On August 15, 2010
My guess is you will need to use a lower level SDK in the case of a matrix printer and probably access the text driver directly.  You'll need to wrap your SDK in pinvoke calls if you are using C#
Reply | Email | Modify 
Printing PDF File by WAQAR On August 25, 2010
http://waqarahmadbhatti.blogspot.com/
Reply | Email | Modify 
thanks for this great article by Aniket On December 9, 2010
thanks.. this really works.
Reply | Email | Modify 
Printing problem by shashi On December 15, 2010
i am trying to print the contant of richTextBox which has many lables all lables taking data from data now i am try to take print but i am getting only blank pages, using this code here is my code' plz tell me why i getting this message on my id deepak.pandit3@gmail.com plz check this code below [ protected void printToolStripMenuItem_Click(object sender, System.EventArgs e) { try { string strText = this.richTextBox1.Text; myReader = new StringReader(strText); PrintPreviewDialog printPreviewDialog1 = new PrintPreviewDialog(); printPreviewDialog1.Document = this.ThePrintDocument; printPreviewDialog1.FormBorderStyle = FormBorderStyle.Fixed3D; printPreviewDialog1.ShowDialog(); } catch (Exception exp) { System.Console.WriteLine(exp.Message.ToString()); } } protected void ThePrintDocument_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs ev) { float linesPerPage = 0; float yPosition = 0; int count = 0; float leftMargin = ev.MarginBounds.Left; float topMargin = ev.MarginBounds.Top; string line = null; Font printFont = this.richTextBox1.Font; SolidBrush myBrush = 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 && ((line = myReader.ReadLine()) != null)) { // 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++; } // If there are more lines, print another page. if (line != null) ev.HasMorePages = true; else ev.HasMorePages = false; myBrush.Dispose(); } private void fileToolStripMenuItem_Click(object sender, EventArgs e) { } protected void exitToolStripMenuItem_Click(object sender, EventArgs e) { printDialog1.Document = ThePrintDocument; string strText = this.richTextBox1.Text; myReader = new StringReader(strText); if (printDialog1.ShowDialog() == DialogResult.OK) { try { this.ThePrintDocument.Print(); } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { MessageBox.Show("Printer nt inistall"); } } } protected void printToolStripMenuItem_Click(object sender, System.EventArgs e) { try { string strText = this.richTextBox1.Text; myReader = new StringReader(strText); PrintPreviewDialog printPreviewDialog1 = new PrintPreviewDialog(); printPreviewDialog1.Document = this.ThePrintDocument; printPreviewDialog1.FormBorderStyle = FormBorderStyle.Fixed3D; printPreviewDialog1.ShowDialog(); } catch (Exception exp) { System.Console.WriteLine(exp.Message.ToString()); } } protected void ThePrintDocument_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs ev) { float linesPerPage = 0; float yPosition = 0; int count = 0; float leftMargin = ev.MarginBounds.Left; float topMargin = ev.MarginBounds.Top; string line = null; Font printFont = this.richTextBox1.Font; SolidBrush myBrush = 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 && ((line = myReader.ReadLine()) != null)) { // 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++; } // If there are more lines, print another page. if (line != null) ev.HasMorePages = true; else ev.HasMorePages = false; myBrush.Dispose(); } private void fileToolStripMenuItem_Click(object sender, EventArgs e) { } protected void exitToolStripMenuItem_Click(object sender, EventArgs e) { printDialog1.Document = ThePrintDocument; string strText = this.richTextBox1.Text; myReader = new StringReader(strText); if (printDialog1.ShowDialog() == DialogResult.OK) { try { this.ThePrintDocument.Print(); } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { MessageBox.Show("Printer nt inistall"); } } } ]//closed
Reply | Email | Modify 
hai mr.mike gold by raam On February 19, 2011
ur all example code very usefull to me.. thank u very much
Reply | Email | Modify 
what about .doc by marut On April 6, 2011
this project only print .txt file but what about other types of file like docs. , pdf. is it possible to print these type of file also? reply asap
Reply | Email | Modify 
Printing exeeding page sige by Arun On May 28, 2011
My printing size exeed or cut the top and bottom of the pdf when I try printing it with C# background code, but it fits correctly or prints correctly when I print by right clicking the pdf. Please help me. Thanks in advance. Here is ma code. ProcessStartInfo startInfo =new ProcessStartInfo(); startInfo.FileName = fileName; //try to keep Window hidden - work in background startInfo.UseShellExecute = true; startInfo.WindowStyle=ProcessWindowStyle.Hidden; startInfo.CreateNoWindow = true; //set process to startInfo and execute start process.StartInfo = startInfo; process.Start(); process.WaitForExit(10000); process.CloseMainWindow(); process.Close();
Reply | Email | Modify 
Printing exeeding page sige by Arun On May 30, 2011
hjkjhk
Reply | Email | Modify 
. by Harvy On June 28, 2011
.
Reply | Email | Modify 
Great Article by Keith On September 5, 2011
Thanks for the article it really helped me to complete an exercise in adding print capabilities to a project. I'm working through an Element K course entitled "Visual C#.NET: Advanced" and your example is eerily similar. I do not have access to the source code so it is very difficult to try the exercises where the topic is beyond what I've already learned so your example really filled in the blanks. Thanks again.
Reply | Email | Modify 
You are GREAT! by michael On September 23, 2011
thank you! it has been very helpful. I appreciate your posts specially this one.
Reply | Email | Modify 
Mindcracker MVP Summit 2012
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.