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

Simplified .NET Printing in C#

By , 12 Jan 2005
 

Introduction

This is a .NET approach to Simplified Printing in which, we are going to use a RichTextBox to cache all of our text for printing in printDocument.

Sample screenshot

RichTextBox is our "TextCache"

When I print a file, for example, using a RichTextBox, and printDocument, I drag a richTextBox onto our Windows Form, and then I place the control where it can be hidden. RichTextBox's visible property can be set to false, and its physical dimensions on the form can be made very small. We can write to this control in a number of ways. The RichTextBox.LoadFile will copy a text file to this control, or I can pass a string to the RichTextBox.Text property, and there after use the AppendText method at any point in the code. If I am required to loop through a file, I can write a record to the control, using AppendText at every iteration. I can write literals to the control whenever necessary.

If I print a report ,for example, I write the date and header information at the top of the document, and then use richTextBox.AppendText any time I add text to the report. This greatly simplifies the printing process, and gives the developer an intuitive feel for printing in the .NET environment.

The rest of this Print method is fairly straightforward, and is available from any textbook, or "Microsoft Whitepapers". I have used a Main Menu at the top of the Windows Form with sub menu items as "PageSetup", "PrintPreview", and "Print". The "Print_Click" fires the "OnBeginPrint", and the "OnPrintPage" events. Below is some of the sample codes.

// Form Load
private void Form1_Load(object sender, System.EventArgs e)
{
   // Write to richTextBox
   richTextBox1.Text = "                               " + 
   DateTime.Now.Month + "/" + DateTime.Now.Day + "/" + 
   DateTime.Now.Year + "\r\n\r\n";
   richTextBox1.AppendText("This is a greatly simplified Print " + 
   "Document Method\r\n\r\n");
   richTextBox1.AppendText("We can write text to a richTextBox, " + 
   "or use Append Text, " + "\r\n" + "or Concatenate a String, and " + 
   "write that textBox. The " + "\r\n" + "richTextBox does not " + 
   "even have to be visible. " + "\r\n\r\n" + "Because we use a " + 
   "richTextBox it's physical dimensions are " + "\r\n" +
   "irrelevant. We can place it anywhere on our form, and set the " + 
   "\r\n" + "Visible Property to false.\r\n\r\n");
   richTextBox1.AppendText("This is the document we will print. The " + 
   "rich TextBox serves " + "\r\n" + "as a Cache for our Report, " +
   "or any other text we wish to print.\r\n\r\n");
   richTextBox1.AppendText("I have also included Print Setup " +
   "and Print Preview. ");
}
// Print Event
private void miPrint_Click(object sender, System.EventArgs e)
{
    if (printDialog1.ShowDialog() == DialogResult.OK)
    {
         printDocument1.Print();
    }
}
        
// OnBeginPrint 
private void OnBeginPrint(object sender, 
                  System.Drawing.Printing.PrintEventArgs e)
{
    char[] param = {'\n'};

    if (printDialog1.PrinterSettings.PrintRange == PrintRange.Selection)
    {
         lines = richTextBox1.SelectedText.Split(param);
    }
    else
    {
         lines = richTextBox1.Text.Split(param);
    }
            
    int i = 0;
    char[] trimParam = {'\r'};
    foreach (string s in lines)
    {
         lines[i++] = s.TrimEnd(trimParam);
    }
}
// OnPrintPage
private void OnPrintPage(object sender, 
                           System.Drawing.Printing.PrintPageEventArgs e)
{
    int x = e.MarginBounds.Left;
    int y = e.MarginBounds.Top;
    Brush brush = new SolidBrush(richTextBox1.ForeColor);
            
    while (linesPrinted < lines.Length)
    {
    e.Graphics.DrawString (lines[linesPrinted++],
         richTextBox1.Font, brush, x, y);
    y += 15;
    if (y >= e.MarginBounds.Bottom)
    {
         e.HasMorePages = true;
         return;
    }
    else
    }
         e.HasMorePages = false;
    }
  }
}
// Page Setup
private void miSetup_Click(object sender, System.EventArgs e)
{
     // Call Dialog Box
     pageSetupDialog1.ShowDialog();
}
// Print Preview
private void miPreview_Click(object sender, System.EventArgs e)
{
     // Call Dialog Box
     printPreviewDialog1.ShowDialog();
    
}

Font and Color Dialog Boxes

When I am printing a file, or writing a report, I generally use the RichTextBox properties to set the Font Size and Style at design time. I leave the fontDialogBox, and the colorDialogBox for Windows Graphics. The fontDialogBox does not update the printPreviewDialogBox in .NET version 7.0, but then there are later versions available.

Summary

This is an easy approach to printing in .NET. Printing files, or even reports, is a breeze, and is an enjoyable task.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Dave Brighton
Web Developer
United States United States
Member
I studied Fortran IV in HighSchool where we had 2 keypunch machines, and access to an IBM 1100 at the Community College. We ran our programs batch, and compiled our programs on paper tape.
 
Years later when PC's became affordable, I gave programming another shot. This time I studied RPG with the IBM AS-400 computer. I could access the College Computer with Emulator Software( Mocha Soft MW 5250 ) and my home PC.
 
C++ came later, then VB-6, C#.Net, and Managed C++. I am currently studying VB.Net

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

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5membermanoj kumar choubey26 Feb '12 - 21:36 
Nice
BugTypo errormemberMacumbero7 Nov '11 - 5:27 
There is an typo in the function OnPrintPage.
 
after the else clause there is an "}" instead of the expected "{"
QuestionFont SizememberBW6426 Sep '11 - 3:30 
I tried setting the font size in the code, but received a compile error - it is read only. It would be nice to wrie a line with the font set to a particular size, then write the next line withthe font set to a different size. I looked at the properties of the rich text box and can't see where it is being set to read only.
GeneralMy vote of 2memberFilippoCSM9 Jan '11 - 14:59 
not so useful
Generalsource Code For AllmemberAliroosta200813 Apr '10 - 12:32 
namespace Print
{
    using System;
    using System.ComponentModel;
    using System.Drawing;
    using System.Drawing.Printing;
    using System.Resources;
    using System.Windows.Forms;
 
    public class frmPrint : Form
    {
        private Container components = null;
        private string[] lines;
        private int linesPrinted;
        private MainMenu mainMenu1;
        private MenuItem miFile;
        private MenuItem miPreview;
        private MenuItem miPrint;
        private MenuItem miSetup;
        private PageSetupDialog pageSetupDialog1;
        private PrintDialog printDialog1;
        private PrintDocument printDocument1;
        private PrintPreviewDialog printPreviewDialog1;
        private RichTextBox richTextBox1;
 
        public frmPrint()
        {
            this.InitializeComponent();
        }
 
        protected override void Dispose(bool disposing)
        {
            if (disposing && (this.components != null))
            {
                this.components.Dispose();
            }
            base.Dispose(disposing);
        }
 
        private void Form1_Load(object sender, EventArgs e)
        {
            this.richTextBox1.Text = string.Concat(new object[] { "                               ", DateTime.Now.Month, "/", DateTime.Now.Day, "/", DateTime.Now.Year, "\r\n\r\n" });
            this.richTextBox1.AppendText("This is a greatly simplified Print Document Method\r\n\r\n");
            this.richTextBox1.AppendText("We can write text to a richTextBox, or use Append Text,\r\nor Concatenate a String, and write that textBox. The \r\nrichTextBox does not even have to be visible. \r\n\r\nBecause we use a richTextBox it's physical dimensions are \r\nirrelevant. We can place it anywhere on our form, and set the \r\nVisible Property to false.\r\n\r\n");
            this.richTextBox1.AppendText("This is the document we will print. The rich TextBox serves \r\nas a Cache for our Report, or any other text we wish to print.\r\n\r\n");
            this.richTextBox1.AppendText("I have also included Print Setup and Print Preview. ");
        }
 
        private void InitializeComponent()
        {
            ResourceManager manager = new ResourceManager(typeof(frmPrint));
            this.richTextBox1 = new RichTextBox();
            this.printDialog1 = new PrintDialog();
            this.printDocument1 = new PrintDocument();
            this.pageSetupDialog1 = new PageSetupDialog();
            this.printPreviewDialog1 = new PrintPreviewDialog();
            this.mainMenu1 = new MainMenu();
            this.miFile = new MenuItem();
            this.miSetup = new MenuItem();
            this.miPreview = new MenuItem();
            this.miPrint = new MenuItem();
            base.SuspendLayout();
            this.richTextBox1.Location = new Point(8, 0x10);
            this.richTextBox1.Name = "richTextBox1";
            this.richTextBox1.Size = new Size(0x128, 240);
            this.richTextBox1.TabIndex = 0;
            this.richTextBox1.Text = "richTextBox1";
            this.printDialog1.Document = this.printDocument1;
            this.printDocument1.BeginPrint += new PrintEventHandler(this.OnBeginPrint);
            this.printDocument1.PrintPage += new PrintPageEventHandler(this.OnPrintPage);
            this.pageSetupDialog1.Document = this.printDocument1;
            this.printPreviewDialog1.AutoScrollMargin = new Size(0, 0);
            this.printPreviewDialog1.AutoScrollMinSize = new Size(0, 0);
            this.printPreviewDialog1.ClientSize = new Size(400, 300);
            this.printPreviewDialog1.Document = this.printDocument1;
            this.printPreviewDialog1.Enabled = true;
            this.printPreviewDialog1.Icon = (Icon) manager.GetObject("printPreviewDialog1.Icon");
            this.printPreviewDialog1.Location = new Point(0x58, 0x74);
            this.printPreviewDialog1.MaximumSize = new Size(0, 0);
            this.printPreviewDialog1.Name = "printPreviewDialog1";
            this.printPreviewDialog1.Opacity = 1.0;
            this.printPreviewDialog1.TransparencyKey = Color.Empty;
            this.printPreviewDialog1.Visible = false;
            this.mainMenu1.MenuItems.AddRange(new MenuItem[] { this.miFile });
            this.miFile.Index = 0;
            this.miFile.MenuItems.AddRange(new MenuItem[] { this.miSetup, this.miPreview, this.miPrint });
            this.miFile.Text = "File";
            this.miSetup.Index = 0;
            this.miSetup.Text = "Page Setup";
            this.miSetup.Click += new EventHandler(this.miSetup_Click);
            this.miPreview.Index = 1;
            this.miPreview.Text = "Print Preview";
            this.miPreview.Click += new EventHandler(this.miPreview_Click);
            this.miPrint.Index = 2;
            this.miPrint.Text = "Print";
            this.miPrint.Click += new EventHandler(this.miPrint_Click);
            this.AutoScaleBaseSize = new Size(5, 13);
            this.BackColor = Color.FromArgb(0x80, 0xff, 0x80);
            base.ClientSize = new Size(320, 0x115);
            base.Controls.AddRange(new Control[] { this.richTextBox1 });
            base.Menu = this.mainMenu1;
            base.Name = "frmPrint";
            this.Text = "Simple Print";
            base.Load += new EventHandler(this.Form1_Load);
            base.ResumeLayout(false);
        }
 
        [STAThread]
        private static void Main()
        {
            Application.Run(new frmPrint());
        }
 
        private void miPreview_Click(object sender, EventArgs e)
        {
            this.printPreviewDialog1.ShowDialog();
        }
 
        private void miPrint_Click(object sender, EventArgs e)
        {
            if (this.printDialog1.ShowDialog() == DialogResult.OK)
            {
                this.printDocument1.Print();
            }
        }
 
        private void miSetup_Click(object sender, EventArgs e)
        {
            this.pageSetupDialog1.ShowDialog();
        }
 
        private void OnBeginPrint(object sender, PrintEventArgs e)
        {
            char[] separator = new char[] { '\n' };
            if (this.printDialog1.PrinterSettings.PrintRange == PrintRange.Selection)
            {
                this.lines = this.richTextBox1.SelectedText.Split(separator);
            }
            else
            {
                this.lines = this.richTextBox1.Text.Split(separator);
            }
            int num = 0;
            char[] trimChars = new char[] { '\r' };
            foreach (string str in this.lines)
            {
                this.lines[num++] = str.TrimEnd(trimChars);
            }
        }
 
        private void OnPrintPage(object sender, PrintPageEventArgs e)
        {
            int left = e.MarginBounds.Left;
            int top = e.MarginBounds.Top;
            Brush brush = new SolidBrush(this.richTextBox1.ForeColor);
            while (this.linesPrinted < this.lines.Length)
            {
                e.Graphics.DrawString(this.lines[this.linesPrinted++], this.richTextBox1.Font, brush, (float) left, (float) top);
                top += 15;
                if (top >= e.MarginBounds.Bottom)
                {
                    e.HasMorePages = true;
                    return;
                }
            }
            this.linesPrinted = 0;
            e.HasMorePages = false;
        }
    }
}
 

GeneralThank You!memberA.Maru3 Feb '10 - 2:31 
You are excellent man! Keep it up!
GeneralLong linesmemberJohnny J.13 Sep '09 - 22:22 
This example doesn't take into consideration that the lines in the textbox can be longer than what can be printed on the paper. Longer lines will simply be cut off on the right hand side.
 
Does anybody know of an example that can handle this and split long lines correctly?
 
Cheers,
Johnny J.
Generalimage in RTFmemberlaziale14 Sep '08 - 22:37 
hi! Is it possible to put images in the rtf by meaning of appending in html code or no? Thx ahead
GeneralRe: image in RTFmemberAnt210017 Jul '11 - 12:56 
You can't put html code itself in the RichTextBox, but you can insert images without too much trouble - try having a look at Advanced Text Editor with Ruler[^]. The editor control allows you to embed images programmatically. Alternatively you could look for a html to rtf converter to convert the html code into the rtf format that the RichTextBox accepts.
 
Anthony
SoftwareStats - A new runtime intelligence solution for .NET

Generala similar projectmemberBenetz11 Sep '08 - 2:56 
great!! but...
 
there are a similar project to print .doc file??
GeneralDraw a linememberctrell39 Jul '08 - 10:46 
Thanks for the code. It is a big help.
 
I do have one small question that maybe someone can help with. How can I either draw a line into the richTextBoxCtrl or draw a line at the top of the page before all of the text in the richTextBoxCtrl is printed?
 
Here is what I am trying to do... I want to add a one line of text in a header to my printed document. Directly below this header text I would like a solid line between the header text and the text in the richTextBoxCtrl. If I can just add the line into the richTextBoxCtrl that would be fine. I have tried to underline the header text but the underline is small in comparison to the large font size I am using for the header text. Any other suggestions?
Generalprinting problemmemberNeetu Maheshwari19 Mar '08 - 20:55 
hello i m working on windows application in c#..
i m having record of users in database..now i want to print some fields like name,contact,mail and address of the users like label on a page...now what i want that the at runtime it will be decided that on a page how many users' detail should print....so please help me..
Generaljustification of text in rectangle while printing....memberkiran gaaaaaaaaaaa10 Feb '08 - 22:36 
Hi frnds,
 
i have a small problem while printing multiple lines of text.
 
suppose...
 
if i have to print 10 lines with left aligned
 
e.graphics.drawstring("string",font,brushes.black,rectangle,stringformat); where as left stringformat=stringformat.alignment.left;
 
i dont have any property for Full Justification(left nd right alignment--like in MS Word justification).
 
please let me know if any one know the solution for this...
 
Thanks in advance..
GeneralRe: justification of text in rectangle while printing....membervinod minhas17 Feb '08 - 6:51 
it is very simple.for this you use simple for loop. in my menner this is work like that. if you use any function then it will be very complex so for the better you use simple way like for loop.
i don't know in which language you doing it. in .net(c#) i made it very easy.
for any suggition you contect me at Sucess.hand@gmail.com
GeneralHelp! Richtextbox giving 'System.NullReferenceException'memberdvo_198826 Sep '07 - 8:20 
Hello, thanks for the article. I downloaded the source and tried to execute it but it does not work, it's giving a 'System.NullReferenceException' on the line where the richtextbox is initialized... What could be the problem? I use VS2003
GeneralRe: Help! Richtextbox giving 'System.NullReferenceException'memberPortatofe2 Oct '08 - 8:34 
Same problem here.Any progress?
 

GeneralWant to use Dot Matrix printermemberAbdul Basir21 Jul '07 - 0:26 
Hello dave!
 
Thanks for the easy way to solution, but I want to use Dot Matrix printer. This will work for .Matrix or not? How I can lay out my report while Im performing printing in Dot Matrix.
 
Thanks
GeneralPlease update the sample and put necessary filesmemberwinheart14 Mar '07 - 2:29 
Please update the sample and put necessary files
GeneralPrintig with C#membergjuanzz22 Dec '06 - 4:43 
Hello dave, and hello to the others memebers....jajajaja...
 
well my problem is that I can't make the code work, why... meybe is because i'm using linux, and the program named monodevelop, I need help, how can I make the code work whit linux
 
By the way the program works with C#...
 

well I hope that somebody can help me....
 

Cry | :((
 
desperate Programer
QuestionDoes it print all lines?memberCharuT25 Jan '07 - 16:13 
Does the code print all lines? When I preview it, it misses out on some lines and obviously that requires handling more variables. Please clarify.
 
Charu.

AnswerRe: Does it print all lines?membergjuanzz6 Feb '07 - 6:39 

thanks for your answer, but i fix that problem, now my other problem is how i can make my page go landscape instead vertical... how, how, how.....jajaja
 
sorry for my desesperation and my bad english...jajajajaj...;P
 
well i hope you can help me...Confused | :confused: Unsure | :~
 

by the way, i'm using monodevelop with C#....Big Grin | :-D
GeneralRe: Does it print all lines?memberCodeWatch27 Feb '07 - 20:59 
Using PrintPageEventArgs PageSettings cuold help.
 
Regards,
CodeWatch.

Generalprinting data in a richtextboxmembershobinmathew5 May '06 - 9:23 
I have to enter data to a richtextbox at run time
then by clicking the print menu i have to print the data in the richtextbox.
how can i do it ?
QuestionRe: printing data in a richtextboxmemberSreenivas00327 Nov '07 - 21:15 
Just do it by handling On Print!
 
sreenivas003@yahoo.co.in

GeneralJust thanksmemberArturoMM24 Jan '06 - 9:56 
I've been writing code like crazy whithout giving a time to share, thank you for having that kind of time.
 
What is the grass? A child asked bringing to me a handful of it, How can I answer him? I also do not know what the grass is.
GeneralJust printmemberVictor M. Bello A.20 Sep '05 - 5:10 
Can i configure by code the page without the need of the print dialogs? The thing is i need to send some information to one printer and other information to another printer, can i just say print and select which printer i'm going to use without the Print Dialog?
 
Thanks
 
Victor M. Bello A.
GeneralRe: Just printmemberDepetunias7 Nov '05 - 19:37 
NO
GeneralRe: Just printmemberVictor M. Bello A.27 Jul '06 - 9:37 
yes you can.
Questionhow can I print the page num at bottom ??memberjostse3 Aug '05 - 21:05 
how can I print the page num at bottom if more than 1 page please?
 
for example : page 2 of 5
GeneralMulti Lanuage/Multi fontmemberPradeep K V22 Jul '05 - 1:40 
Hi,
I want to show the contents of richtext box in printprieview dialog.I am using multiple languages(many fonts).How i should show this content in printpreview .

GeneralThanksmemberadrian_adi6 Jul '05 - 9:53 
It's work. This code help me very much.
Thank you.
 
ADRIAN
GeneralPrinting justify textmembermjramon15 Feb '05 - 3:19 
How can I print the text justify (right and left) like a Justify Align Text in Microsoft Word
GeneralRe: Printing justify textmemberDave Brighton15 Feb '05 - 8:50 
When you AppendText to the richTextBox after using an escape character "\r\n", newline character, then the text will be left justified. If you want to "center" the text then then concantenate an appropriate number of blank spaces prior to the text you want to print. Example:
 
string Sample = "\r\n" + " " + txtSample.Text;
richTextBox1.AppendText( Sample );
 
I read a printing alogrithm in VB.Net 2003 that looked like somone with a PhD after their name wrote it. It worked, but why, when printing can be this simple. It should be this simple.
 
Good Programming,
Dave Brighton/ KD7GIM
GeneralPrinting more than one pagememberHarold Clements6 Feb '05 - 23:50 
Hello,
 
I am trying to print on multiple pages but I can not seem to be able to get it right. I have a while loop that is pulling info from a database (the results of an SQL search).
I know where the bottom of the page is so I added this:

(line > maxPage)
{
e.hasMorePages(true);
line = 0;
}
else
{
e.hasMorePages(false);
}

However, I do not get a new page. It prints over the original.
 
If anyone has any ideas I would be very grateful.
 
Thanks,
Harold Clements
 
(Please note that I am using J# but I can translate answers in C# or VB.NET.)

AnswerRe: Printing more than one pagemembergjuanzz6 Feb '07 - 6:56 
All you have to do is to make a new page, example:
 
ContextoImp.BeginPage("Page 1");
 
and show the page with:
 
ContextoImp.ShowPage();
 
ContextoImp is just the name of my variable yuo can change it.. Smile | :)
 
void ComponerPagina (PrintContext ContextoImp, PrintJob trabajoImpresion)
{
ContextoImp.BeginPage("Page 1");
ContextoImp.ShowPage();
}
 
This is a code in C# that I'm using in a recent program.... I hope it be helpfulBig Grin | :-D

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

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130516.1 | Last Updated 12 Jan 2005
Article Copyright 2005 by Dave Brighton
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid