65.9K
CodeProject is changing. Read more.
Home

Simplified .NET Printing in C#

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.54/5 (32 votes)

Jan 12, 2005

2 min read

viewsIcon

410164

downloadIcon

21908

Uses a RichtextBox to cache our text for printing.

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.