
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 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.

Mario RodríguezPosted Jun 18, 2019, 8:01 PM
Thanks a lot Mike, I learned something new today.
Giovanni SiccardiPosted Mar 14, 2019, 9:05 AM
Adding a [STAThread] it works perfectly
Giovanni SiccardiPosted Mar 14, 2019, 9:03 AM
By using your PrintExample.zip, I've found the menu Item1 not working.
Ramesh PalaniappanPosted Aug 24, 2016, 10:20 AM
Nice
kalu singh raoPosted Jul 9, 2016, 11:02 AM
Nice...
Shubham KumarPosted Feb 5, 2016, 1:58 AM
nice
Shubham KumarPosted Feb 5, 2016, 1:57 AM
very helpful.
Joe WilsonPosted Dec 28, 2015, 2:02 AM
Well, it's so great.
Kumar SangamPosted Apr 24, 2013, 4:44 AM
thanx sir
Kumar SangamPosted Apr 24, 2013, 4:43 AM
thanx sir
Reginald TapoPosted Sep 2, 2012, 5:44 AM
Huge help Mike. I got print working in Microsoft Visual C# 2010. My code DOES print multiple pages from the print dialog. Currently I get only a blank page when printing from printPreview dialog.
abdul muqeetPosted Jun 12, 2012, 2:04 AM
how can i put my data base table in this print
winner comPosted Mar 7, 2012, 1:23 PM
Hi, doesn't work for multiple pages:( If somebody is interesting I found one great solution for printing pdf files, it is CLPRINT tool. Take a look at http://www.commandlinepdf.com/
michael andresPosted Sep 23, 2011, 12:41 AM
thank you! it has been very helpful. I appreciate your posts specially this one.
Keith BadeauPosted Sep 5, 2011, 7:50 PM
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.
pankaj parwaniPosted Aug 11, 2011, 11:48 AM
Hi, I need to print a Form in the paper in the Format I design.. For example, Form to be printed in the format of BILL..
Harvy AckermanseditedPosted Jun 28, 2011, 5:21 PMEdited Jun 28, 2011, 6:11 PM
.
Arun PSPosted May 30, 2011, 2:35 AM
hjkjhk
Arun PSPosted May 28, 2011, 2:26 AM
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();
marut mahajanPosted Apr 6, 2011, 4:56 AM
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
raam chandranPosted Feb 19, 2011, 1:02 AM
ur all example code very usefull to me.. thank u very much
shashi gandhieditedPosted Dec 15, 2010, 1:50 AMEdited Dec 15, 2010, 4:16 AM
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 [email protected] 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
Aniket GujrathiPosted Dec 9, 2010, 5:16 AM
thanks.. this really works.
WAQAR AHMADPosted Aug 25, 2010, 3:15 AM
http://waqarahmadbhatti.blogspot.com/
Kiran NeupanePosted Aug 15, 2010, 5:43 AM
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.
divya mehtaPosted Apr 26, 2010, 2:37 AM
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..
renuka salaviPosted Apr 21, 2010, 1:11 AM
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..
Marinus JohannesPosted Feb 10, 2010, 9:35 AM
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??
Sunil KumarPosted Nov 16, 2009, 11:22 PM
Thank's, I m glad to reciev this file and this code is solution of my problem.. I have ane another que about it.Que is...How to print A form containt is same manner as it appeare in the form like this.
Ken BarretteditedPosted Aug 14, 2009, 7:52 PMEdited Aug 14, 2009, 7:53 PM
Nice article, but it doesn't work... for multiple pages. Just prints the first page and quits.
nandanPosted May 23, 2009, 2:11 PM
Nice article. Can we change the default MarginBounds height for Left and Top margins, because I need it in my project
Alex PetaPosted Apr 4, 2009, 5:47 PM
Hey , Thanks, This was very useful. Regards, Alex
Nikhil KumarPosted Mar 18, 2009, 12:47 AM
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
Francesc MarquillasPosted Nov 16, 2008, 5:05 PM
I have a problem with "StringReader(strText);" The complation don't fount de class. Some idea? Thanks
PeterPosted Oct 21, 2008, 4:14 PM
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!
Jamie CoopereditedPosted Feb 12, 2008, 3:29 PMEdited Feb 12, 2008, 5:00 PM
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.
Osama RabiePosted Jan 28, 2008, 3:26 PM
how can i define a print document to print preview in console application cause it returns nothing
AalhusseinPosted Jan 6, 2008, 2:06 AM
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 [email protected]
Pierse DoilPosted Aug 22, 2007, 2:23 AM
can you help me about preview a word document and print it by addressing the file name
jessie matillanoPosted Jun 28, 2007, 8:49 PM
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.
Ahsan MurshedPosted Jun 18, 2007, 1:09 AM
Very helpful for me. Hope that he provides more useful feature for C# developer.
Charumathy ThyagarajanPosted Feb 28, 2007, 3:08 AM
I think the code isnt perfect and would not print all the lines and words as it should. Definitely printing in C# is more complicated than this.