Introduction
I have tried to search and download few application but that code is working but there is rare guide available for the setting up the printcontrol and adding code for the method I will try to elaborate as much so any one can easily update code even after latest version of Visual Studio
Background
Just article you can try to use for the multiline text box or richtextbox control or with just minor tweaks you can use for any custom control too.
Using the code
First of all I would say down load the source code and I will traverse you across that .
- Create a Visual Studio WinForms project
- Place the richtextbox over Form from the toolbox panel
- Add (Drag on form) the PrintDialog from the toolbox => printing panel on the Form
- Add the
PrintDocument
from the toolbox => printing panel on the Form - Add the Button. Now your Windows Would look like this:
Now have a look at the code its very simple to get idea. simple print code behind the print button and that will call all
printDocument1_BeginPrint
and OnPrintPage
page methods.private void button1_Click(object sender, EventArgs e)
{
if (printDialog1.ShowDialog() == DialogResult.OK)
{
printDocument1.Print();
}
}
private void printDocument1_BeginPrint(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);
}
}
private int linesPrinted;
private string[] lines;
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;
}
}
linesPrinted = 0;
e.HasMorePages = false;
}
Comments
Post a Comment