To print the contents of a RichTextBox
in C#, you can use the PrintDocument
class along with the PrintDialog
class. Here’s an example of how you can achieve this:
using System;
using System.Drawing;
using System.Drawing.Printing;
using System.Windows.Forms;
public class PrintExampleForm : Form
{
private RichTextBox richTextBox;
private Button printButton;
public PrintExampleForm()
{
// Initialize the form and controls
this.richTextBox = new RichTextBox();
this.printButton = new Button();
// Set up the RichTextBox control
this.richTextBox.Dock = DockStyle.Fill;
// Set up the Print button
this.printButton.Text = "Print";
this.printButton.Click += PrintButton_Click;
// Add controls to the form
this.Controls.Add(this.richTextBox);
this.Controls.Add(this.printButton);
}
private void PrintButton_Click(object sender, EventArgs e)
{
// Create a new PrintDocument
PrintDocument pd = new PrintDocument();
pd.PrintPage += Pd_PrintPage;
// Create a new PrintDialog
PrintDialog printDialog = new PrintDialog();
printDialog.Document = pd;
// Show the PrintDialog
DialogResult result = printDialog.ShowDialog();
if (result == DialogResult.OK)
{
// If the user clicks OK, start printing
pd.Print();
}
}
private void Pd_PrintPage(object sender, PrintPageEventArgs e)
{
// Set up the print content
string text = this.richTextBox.Text;
Font font = this.richTextBox.Font;
Brush brush = new SolidBrush(this.richTextBox.ForeColor);
// Calculate the area to print
RectangleF rect = new RectangleF(e.MarginBounds.Left, e.MarginBounds.Top, e.MarginBounds.Width, e.MarginBounds.Height);
// Draw the text on the printer graphics
e.Graphics.DrawString(text, font, brush, rect);
}
public static void Main()
{
Application.Run(new PrintExampleForm());
}
}
In this example, we create a PrintExampleForm
that contains a RichTextBox
and a Print
button. When the user clicks the Print
button, a PrintDialog
is displayed to choose the printer settings. If the user confirms the print settings, the PrintDocument
is created and the PrintPage
event is handled to draw the contents of the RichTextBox
on the printer graphics.
You can customize this example further to suit your specific needs, such as adding page headers, footers, or handling multiple pages if the content exceeds a single page.