Senin, 26 Agustus 2013

PrintDialog Box Control in Windows Forms

To print any text or image, print Dialog box is used which is in-built control in windows forms. To invoke the default print dialog box, you need to either add the PrintDialog and PrintDocument control from the toolbox or create an instance of the same classes. The following image shows the default Print Dialog box.

PrintDialog box Control in windows forms

Printing Text

In this topic we will print the text from textbox to the printer attached with the computer. Just add a textbox and a button to the form.

Printing text form preview in windows forms

The click event of button should be look like the following code in C# language:
private void button1_Click(object sender, EventArgs e)
{
printDialog1.Document = printDocument1;
DialogResult res = printDialog1.ShowDialog();
if (res == DialogResult.OK)
printDocument1.Print();
}
Now when we check out the above code, text to be print is not specified there. To specify the text to be print printPage event of print document is used. The print page event will be:
private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
{
e.Graphics.DrawString(textBox1.Text, new Font("Tahoma", 25), Brushes.Black, 150, 20);
}
Here above the drawstring method draws the specified text at the given location with given properties. If we don’t want to add print dialog and print document from the toolbox then we have to instantiate both of the classes in our code. Just write the following code (C# language) in the click event of button:
PrintDocument pd = new PrintDocument();
pd.PrintPage += pd_PrintPage;

PrintDialog printDialog = new PrintDialog();
printDialog.Document = pd;

DialogResult res = printDialog.ShowDialog();
if (res == DialogResult.OK)
pd.Print();
The second line in above code will be used to generate the printPage event of printDocument. The code of this event will be the same as written first.
Run the project and write something in the textbox e.g. “Print Example”. It will print a page written the above text on the location given above.
There are some properties of the printDocument class, some of which are DefaultPageSettings, PrinterSettings, DocumentName, PrintController and etc.

See also: Print Image using Print Dialog

Tidak ada komentar:

Posting Komentar