Search This Blog

Monday, December 2, 2013

PrintPreviewDialog C# Example

C# > Print  > PrintPreviewDialog

PrintPreviewDialog is a dialog box form for printing from a Windows Forms application.






Example

In this example we will create a print document and print using PrintPreviewDialog. We will print some text on Print Page event



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication3
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void btnPrint_Click(object sender, EventArgs e)
        {
            PrintDocument document = new System.Drawing.Printing.PrintDocument();
            PrintPreviewDialog ppd = new PrintPreviewDialog();
            ppd.ClientSize = new System.Drawing.Size(500, 400);
            ppd.Location = new System.Drawing.Point(0, 0);
            document.PrintPage += new PrintPageEventHandler(Doc_PrintPage);
            ppd.Document  = document;
            ppd.ShowDialog();
        }
        private void Doc_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            string text = "Header";
            Font printFont = new  Font("Tahoma", 40, System.Drawing.FontStyle.Bold );
            e.Graphics.DrawString(text, printFont, Brushes.Blue, 0, 0);
            text = "Text";
            printFont = new Font("Tahoma", 30, System.Drawing.FontStyle.Regular);
            e.Graphics.DrawString(text, printFont, Brushes.Black , 0, 100);
        }
    }
}