.Net – How to print directly to printer in Winforms application

Recently I was writing a simple Winforms app in C#, which required printing of labels. Printing had to be automatic, without displaying print dialog box, or requiring any extra user input.

First, include System.Drawing.Printing namespace. Then create a PrintDocument object and attach print page event handler to it and add code inside the handler to create content that gets sent to the printer. Finally, call Print() method on PrintDocument object to send contents directly to printer, without displaying print dialog box.

using System.Drawing.Printing;

private void MyProc()
{
     //Do other stuff before printing...
     //...
     //...

     PrintDocument pd = new PrintDocument();
     pd.PrintPage += new PrintPageEventHandler(PrintLabel);
     pd.Print();
}

private void PrintLabel(object o, PrintPageEventArgs e)
{
     string label = "Text that I want to print goes here.";
     System.Drawing.Font font = new System.Drawing.Font(FontFamily.GenericSerif, 20, FontStyle.Regular);
     System.Drawing.Brush brush = new SolidBrush(Color.Black);
     e.Graphics.DrawString(label, font, brush, 10, 10, StringFormat.GenericDefault);
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s