Click here to Skip to main content
15,892,697 members
Articles / Programming Languages / Visual Basic

Printing Reports in .NET

Rate me:
Please Sign up or sign in to vote.
4.85/5 (70 votes)
26 Aug 2008CPOL11 min read 441.1K   15.6K   257  
Using the library presented, you can print reports from C# and other .NET languages
// Copyright (c) 2003, Michael Mayer
// See License.txt that should have been included with this source file.
// or see http://www.mag37.com/csharp/articles/Printing/

using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using System.Drawing.Printing;

namespace ReportPrinting
{
    /// <summary>
    /// A simple control that wraps the functionality of the key buttons required
    /// for printing into a ToolBar
    /// </summary>
    /// <remarks>
    /// <para>
    /// Some code for this class inspired by:
    /// Alex Calvo's article 
    /// "Preview and Print from Your Windows Forms App with the .NET Printing Namespace"
    /// http://msdn.microsoft.com/msdnmag/issues/03/02/PrintinginNET/default.aspx
    /// </para>
    /// <para>
    /// You can customize a few things with the following properties:
    /// 
    /// <list type="table">
    /// <item>
    /// <term>ShowStatusDialog</term>
    /// <description>
    /// The progress of the print job is shown in a status dialog.  Default is true.
    /// </description>
    /// </item>
    /// 
    /// <item>
    /// <term>PrintInBackground</term>
    /// <description>
    /// Indicates that printing should be done in the background.  
    /// Default is true.  
    /// (Note, if your application exits while printing is still in progress, 
    /// it will quit.  Make sure to monitor the PrintInProgress flag).
    /// </description>
    /// </item>
    /// 
    /// <item>
    /// <term>Printing</term>
    /// <description>
    ///	This event is raised prior to printing.  It allows user code 
    ///	to setup for printing.  (This is useful for dumping data from the 
    ///	GUI to a helper class, for instance).
    ///	</description>
    ///	</item>
    ///	</list>
    ///	</para>
    /// </remarks>
    /// 
    /// <example>
    /// To use the print control, place it on a form.
    /// Set the Document property to a valid PrintDocument
    /// (it doesn�t have to just be the ReportDocument).  That�s it!
    /// </example>
    public class PrintControlToolBar : System.Windows.Forms.UserControl
	{
        delegate void PrintInBackgroundDelegate();

        private System.Windows.Forms.PageSetupDialog pageSetupDialog1;
        private System.Windows.Forms.PrintDialog printDialog1;
        private System.Windows.Forms.PrintPreviewDialog printPreviewDialog1;
        private System.Windows.Forms.ToolTip toolTip1;
		private System.Windows.Forms.ToolBar PrintToolBar;
		private System.Windows.Forms.ToolBarButton SetupButton;
		private System.Windows.Forms.ToolBarButton PreviewButton;
		private System.Windows.Forms.ToolBarButton PrintButton;
		private System.Windows.Forms.ImageList imageList1;
		private System.Windows.Forms.ToolBarButton CancelButton;
        private System.ComponentModel.IContainer components;
		/// <summary>
		/// Property to provide access to ToolBar 
		/// </summary>
		public ToolBar ToolBar
		{
			get { return PrintToolBar; }
		}
        /// <summary>
        /// This control is to be placed on a form that enables printing.
        /// It has four buttons: PageSetup, PrintPreview, Cancel and Ok.
        /// Ok will launch the normal PrintDialog for choosing a printer.
        /// </summary>
        /// <remarks>
        /// Simply instantiate this control on a form.
        /// Set the Document property to a valid PrintDocument.
        /// Optionally, subscribe to the event Printing to be notified
        /// of a print job before it is started.
        /// </remarks>
    	public PrintControlToolBar()
		{
			// This call is required by the Windows.Forms Form Designer.
			InitializeComponent();

		}

		/// <summary> 
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if(components != null)
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Component Designer generated code
		/// <summary> 
		/// Required method for Designer support - do not modify 
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.components = new System.ComponentModel.Container();
			System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(PrintControlToolBar));
			this.pageSetupDialog1 = new System.Windows.Forms.PageSetupDialog();
			this.printDialog1 = new System.Windows.Forms.PrintDialog();
			this.toolTip1 = new System.Windows.Forms.ToolTip(this.components);
			this.printPreviewDialog1 = new System.Windows.Forms.PrintPreviewDialog();
			this.PrintToolBar = new System.Windows.Forms.ToolBar();
			this.SetupButton = new System.Windows.Forms.ToolBarButton();
			this.PreviewButton = new System.Windows.Forms.ToolBarButton();
			this.PrintButton = new System.Windows.Forms.ToolBarButton();
			this.CancelButton = new System.Windows.Forms.ToolBarButton();
			this.imageList1 = new System.Windows.Forms.ImageList(this.components);
			this.SuspendLayout();
			// 
			// printPreviewDialog1
			// 
			this.printPreviewDialog1.AutoScrollMargin = new System.Drawing.Size(0, 0);
			this.printPreviewDialog1.AutoScrollMinSize = new System.Drawing.Size(0, 0);
			this.printPreviewDialog1.ClientSize = new System.Drawing.Size(400, 300);
			this.printPreviewDialog1.Enabled = true;
			this.printPreviewDialog1.Icon = ((System.Drawing.Icon)(resources.GetObject("printPreviewDialog1.Icon")));
			this.printPreviewDialog1.Location = new System.Drawing.Point(34, 0);
			this.printPreviewDialog1.MinimumSize = new System.Drawing.Size(375, 250);
			this.printPreviewDialog1.Name = "printPreviewDialog1";
			this.printPreviewDialog1.TransparencyKey = System.Drawing.Color.Empty;
			this.printPreviewDialog1.Visible = false;
			// 
			// PrintToolBar
			// 
			this.PrintToolBar.Buttons.AddRange(new System.Windows.Forms.ToolBarButton[] {
																							this.SetupButton,
																							this.PreviewButton,
																							this.PrintButton,
																							this.CancelButton});
			this.PrintToolBar.Divider = false;
			this.PrintToolBar.DropDownArrows = true;
			this.PrintToolBar.ImageList = this.imageList1;
			this.PrintToolBar.Location = new System.Drawing.Point(0, 0);
			this.PrintToolBar.Name = "PrintToolBar";
			this.PrintToolBar.ShowToolTips = true;
			this.PrintToolBar.Size = new System.Drawing.Size(210, 39);
			this.PrintToolBar.TabIndex = 4;
			this.PrintToolBar.ButtonClick += new System.Windows.Forms.ToolBarButtonClickEventHandler(this.PrintToolBar_ButtonClick);
			// 
			// SetupButton
			// 
			this.SetupButton.ImageIndex = 0;
			this.SetupButton.Text = "&Setup";
			this.SetupButton.ToolTipText = "Printer Setup";
			// 
			// PreviewButton
			// 
			this.PreviewButton.ImageIndex = 1;
			this.PreviewButton.Text = "Pre&view";
			this.PreviewButton.ToolTipText = "Print Preview";
			// 
			// PrintButton
			// 
			this.PrintButton.ImageIndex = 2;
			this.PrintButton.Text = "&Print";
			this.PrintButton.ToolTipText = "Print";
			// 
			// CancelButton
			// 
			this.CancelButton.ImageIndex = 3;
			this.CancelButton.Text = "&Cancel";
			this.CancelButton.ToolTipText = "Cancel Printing";
			// 
			// imageList1
			// 
			this.imageList1.ImageSize = new System.Drawing.Size(16, 15);
			this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream")));
			this.imageList1.TransparentColor = System.Drawing.Color.Silver;
			// 
			// PrintControlToolBar
			// 
			this.Controls.Add(this.PrintToolBar);
			this.Name = "PrintControlToolBar";
			this.Size = new System.Drawing.Size(210, 40);
			this.ResumeLayout(false);

		}
		#endregion


        private PrintDocument document;

        /// <summary>
        /// Gets or sets the PrintDocument used by the dialog.
        /// </summary>
        public PrintDocument Document
        {
            get { return this.document; }
            set { this.document = value; }
        }

        private bool showStatusDialog = true;

        /// <summary>
        /// The progress of the print job is shown in a status dialog.
        /// Default is true.
        /// When true, the PrintControllerWithStatusDialog is used.  Otherwise,
        /// a StandardPrintController is used for printing.
        /// </summary>
        public bool ShowStatusDialog
        {
            get { return this.showStatusDialog; }
            set { this.showStatusDialog = value; }
        }

        private bool printInBackground = false;

        /// <summary>
        /// Indicates that printing should be done in the background.
        /// Default is true.
        /// </summary>
        public bool PrintInBackground
        {
            get { return this.printInBackground; }
            set { this.printInBackground = value; }
        }

        private bool printInProgress = false;

        /// <summary>
        /// Indicates that a print job is currently in progress.
        /// </summary>
        public bool PrintInProgress
        {
            get { return this.printInProgress; }
        }

        /// <summary>
        /// This event is raised prior to printing.  
        /// It allows user code to setup for the printing.
        /// Perhaps disable any Print buttons, etc.
        /// </summary>
        public event EventHandler Printing;

        /// <summary>
        /// This event is raised after printing.
        /// It allows user code to cleanup after printing.
        /// Perhaps enable any Print buttons, etc.
        /// </summary>
        public event EventHandler Printed;

        /// <summary>
        /// Called prior to printing.  It raises the Printing event.
        /// </summary>
        protected virtual void onPrinting()
        {
            if (Printing != null)
            {
                Printing(this, new EventArgs());
            }
        }

		/// <summary>
		/// Called after printing.  It raises the Printed event.
		/// </summary>
		protected virtual void onPrinted()
		{
			if (Printed != null)
			{
				Printed(this, new EventArgs());
			}
		}
		/// <summary>
		/// A button in the Tool Bar has been Pressed
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void PrintToolBar_ButtonClick(object sender, System.Windows.Forms.ToolBarButtonClickEventArgs e)
		{
			switch (PrintToolBar.Buttons.IndexOf(e.Button))
			{			
				case 0 :  //Page Setup
				{
					btnPageSetup_Click();
					break;
				}
				case 1 :  //Preview
				{
					btnPreview_Click();
					break;
				}	
				case 2 :  //Print
				{
					btnOK_Click();
					break;
				}				
				case 3 :  //Cancel
				{
					btnCancel_Click();
					break;
				}			
			}

		}	
		/// <summary>
        /// The PageSetup button has been clicked.  (Standard button click event handler).
        /// Shows the PageSetup dialog.
        /// </summary>
        public virtual void btnPageSetup_Click()
        {
            if (!this.printInProgress)
            {
                this.pageSetupDialog1.Document = this.document;
                this.pageSetupDialog1.ShowDialog(this);
            }
        }

        /// <summary>
        /// The Preview button has been clicked.  (Standard button click event handler).
        /// Shows the Preview dialog.
        /// </summary>
        public virtual void btnPreview_Click()
        {
            if (!this.printInProgress)
            {
                this.printPreviewDialog1.Document = this.document;
                onPrinting();
                this.printPreviewDialog1.ShowDialog(this);
            }
        }

        /// <summary>
        /// The Ok button has been clicked.  (Standard button click event handler).
        /// Hide the parent form and show the standard PrintDialog.
        /// If ok is pressed on that dialog, then:
        /// Set the Document's PrintController based on ShowStatusDialog property.
        /// Start the print job (asyncronously if PrintInBackground is true).
        /// </summary>
        public virtual void btnOK_Click()
        {
            if (!this.printInProgress)
            {
                this.printDialog1.Document = this.document;
                this.ParentForm.Hide();
                DialogResult result = this.printDialog1.ShowDialog();
                if (result == DialogResult.OK)
                {
                    PrintController printController;
                    printController = new StandardPrintController();

                    if (this.ShowStatusDialog)
                    {
                        this.document.PrintController = new PrintControllerWithStatusDialog(
                            printController, "Please wait...");
                    }
                    else
                    {
                        this.document.PrintController = printController;
                    }

                    onPrinting();
                    if (this.PrintInBackground)
                    {
                        // disable buttons or else the user could get into trouble!
                        PrintInBackgroundDelegate d = new PrintInBackgroundDelegate(
                            BeginBackgroundPrint);
                        d.BeginInvoke(new AsyncCallback(PrintInBackgroundComplete), null);
                    }
                    else
                    {
                        this.printInProgress = true;
                        this.document.Print();
                        this.printInProgress = false;
						onPrinted();
                    }

                }
                //this.ParentForm.Close();
            }
        }

        /// <summary>
        /// The Cancel button has been clicked.  (Standard button click event handler).
        /// Closes the parent form.
        /// </summary>
        public virtual void btnCancel_Click()
        {
            this.ParentForm.Hide();
            //this.ParentForm.Close();
        }

        /// <summary>
        /// Start a background print job
        /// </summary>
        protected virtual void BeginBackgroundPrint()
        {
            this.printInProgress = true;
            try
            {
                this.document.Print();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, Application.ProductName,
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// A background print job is complete
        /// </summary>
        protected virtual void PrintInBackgroundComplete(IAsyncResult r)
        {
            this.printInProgress = false;
			onPrinted();
        }





	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions