- This topic shows how to print text from TextBox or RichTextBox using C# programming.
- Tools needed: Button1 (Button1), TextBox1 (TextBox1), PrintDocument1 (PrintDocument1).
PrintDocument – How to print text using C# programming
- The PrintDocument control defines the various methods that allow you to send output to the printer.
- To incorporate printing functionality into your Windows application, you can either drag and drop the PrintDocument control onto your form, or create an instance of the PrintDocument class during runtime.
- To start the printing process, use the Print() method of the PrintDocument object. To customize the printing process using the PrintDocument object, there are generally three events that you need to get acquainted with. They are:
- BeginPrint Occurs when the Print() method is called and before the first page of the document prints. Typically, you make use of the BeginPrint event to initialize fonts, file streams, and other resources used during the printing process.
- PrintPage Occurs when the output to print for the current page is needed. This is the main event to code the logic required for sending the outputs to the printer.
- EndPrint Occurs when the last page of the document has printed. Typically, you use the EndPrint event to release fonts, file streams, and other resources used during the printing process, like fonts.
How to print text using C# programming – Complete Code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.IO;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
string StringToPrint;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
StringToPrint = richTextBox1.Text;
printDocument1.Print();
}
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
int numChars = 0;
int numLines = 0;
string stringForPage = null;
StringFormat strFormat = new StringFormat();
Font PrintFont = default(Font);
PrintFont = richTextBox1.Font;
RectangleF rectDraw = new RectangleF(e.MarginBounds.Left, e.MarginBounds.Top, e.MarginBounds.Width, e.MarginBounds.Height);
SizeF sizeMeasure = new SizeF(e.MarginBounds.Width, (e.MarginBounds.Height - PrintFont.GetHeight(e.Graphics)));
strFormat.Trimming = StringTrimming.Word;
e.Graphics.MeasureString(StringToPrint, PrintFont, sizeMeasure, strFormat,out numChars,out numLines);
stringForPage = StringToPrint.Substring(0, numChars);
e.Graphics.DrawString(stringForPage, PrintFont, Brushes.Black, rectDraw, strFormat);
if ((numChars < StringToPrint.Length))
{
StringToPrint = StringToPrint.Substring(numChars);
e.HasMorePages = true;
}
else
{
e.HasMorePages = false;
}
}
}
}
How to print text using C#