C# 打印详解

http://vibone.blog.163.com/blog/static/994856802010472592561/ 

  System.Drawing.Printing;命名空間中的類可以幫助在應用程序中打印文檔。

    打印的基類是PrintDocument,方法Print()會啟動一系列調用,最后調用OnPrintPage(),把輸出結果傳送給打印機。

    

    PrintDocument: 是最重要的類。幾乎所有的打印類都與這個類有關係。要打印一個文檔,需要PrintDocument的一個實例。
    PrintController:
 類控製打印任務流。提供了打印開始、打印每個頁面和打印結束的事件。派生於PrintController的具體類有StandardPrintControllerPreviewPrintController
    PrintSettings
: 類可以獲取打印和設置打印機配置。這個類配置由PageSetupDialog類進行。
    PrintDialog
:  類確定使用哪個打印機進行打印和如何配置PrinterSettings
    Graphics
:   可以訪問打印機的設備內容,給打印機發送字符串、線條和曲線。
    PageSetupDialog
:設置打印頁面。
    PrintPreviewDialg:打印預覽頁面。

其中:

   PrintDialog頁面樣式如下圖:
   


 

    PrintSetupDialog頁面格式如下圖:

   


 

PrintPreviewDialog頁面樣式如下圖:

   


  應用程序必須調用PrintDocumentPrint()方法,啟動調用序列。因為PrintDocument本身並不負責打印流,所以由PrintController通過調用這個類的Print()方法完成打印。    打印控制器現在執行操作,通知PrintDocument,通過調用OnBeginPrint()開始打印。如果應用程序在打印任務的開始執行某些操作,就必須在PrintDocument中註冊一個事件處理程序,這樣才會在應用程序類中接到通知。如上圖中,假定註冊了處理程序OnBeginPrint(),所以這個處理程序應在PrintDocument類中調用。

  在開始階段完成后,PrintController就進入PrintLoop(),為每個要打印的頁面調用PrintDocument類中的OnPrintPage()方法。OnPrintPage()調用所有的PrintPage事件處理程序。必須對每個頁面執行這個處理程序,否則就不會打印任何內容。
    可以在
PrintDocument.PrintPage處理程序中執行打印代碼。每個打印頁面都要調用該處理程序。如果打印任務只需要執行一次打印代碼,就必須執行BeginPrintEndprint事件和處理程序。
 
  在打印完成最后一頁后,PrintController就調用PrintDocument類中的OnEndPrint()。也可以執行要在這里調用的處理程序。


如何打印(簡單打印方法)?

    要實現打印必須有如下內容:
        1
、打印文件檔,用於打印機印機。此用PrintDocument類實例化
        2
、被打印的內容。處理用PintDocumentPrintPage事件方法得到被打印內容。

    其方法如下:
       1、實例化
PrintDocument類。聲明需要打印的文檔
        2、增加
PrintDocument.PrintPage事件,此事件的方法用於得到被打印的內容
        3、調用
PrintDocument.Print()方法打印內容,在打印之前,此方法會在PrntController類的幫助下先呼叫PrintPage事件的方法
        4、在
PrintPage事件中繪製打印文本,用於得到打印內容,此方法結束后會回到PrintDocument.Print()方法中,執行打印

代碼如下:
    注:界面中一個多行的
TextBox textBoxEdit
        
和一個打印菜單:MiFilePrint

using System.IO;
using System.Drawing.Printing;

namespace SimpleEditor
{
    public partial class SimpleEditorForm : Form
    {
        /*
        窗體中一個打印菜單:名稱為:MiFilePrint
        一個多行TextBoxG:名稱為:textBoxEdit
        
*/
      
        //1、 實例化PrintDocument類
        PrintDocument pdDocument = new PrintDocument();

        public SimpleEditorForm()
        {
            InitializeComponent();
            //2、 訂閱PrintDocument.PrintPage事件
            pdDocument.PrintPage += new PrintPageEventHandler(OnPrintPage);
        }
        
       /// <summary>
        /// 
當按下打印時,此為界面中的打印按鈕事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void OnFilePrint(object sender, EventArgs e)
        {
            try
            {
                /*
                * PrintDocument對象的Print()方法在PrintController類的幫助下,執行PrintPage事件。
                
*/

                //3、調用PrintDocument.Print()方法
                pdDocument.Print();                
        
            }
            catch (InvalidPrinterException ex )
            {
                MessageBox.Show(ex.Message, "Simple Editor", MessageBoxButtons.OK, MessageBoxIcon.Error);
                throw;
            }
        }
        

        /// <summary>
        
/// printDocument的PrintPage事件
        
/// </summary>
        
/// <param name="sender"></param>
        
/// <param name="e"></param>
        private void OnPrintPage(object sender, PrintPageEventArgs e)
        {
            /*
             * 得到TextBox中每行的字符串數組
             * \n換行
             * \r回車
             
*/
            char[] param ={'\n'};
            string[] lines = textBoxEdit.Text.Split(param);

            int i = 0;
            char[] trimParam ={'\r'};
            foreach (string s in lines)
            {
                //刪除每行中的\r
                lines[i++] = s.TrimEnd(trimParam);
            }

            int x = 20;
            int y = 20;
            foreach (string line in lines)
            {
                /*
                 * 4、把文本行發送給打印機,其中e是PrintPageEventArgs類型的一個變量,其屬性連接到打印機關聯文本中。
                 * 打印機關聯文本可以寫到打印機設備上。
                 * 輸出結果的位置用變更X和Y定義。
                 
*/
                e.Graphics.DrawString(line, new Font("Arial"10), Brushes.Black, x, y);
                y += 15;
            }
        }
    }
}
如果要實現多頁打印,就要使用PrintPageEventArgs類的HasMorePages屬性。

我們對之前的代碼作如下變更:
    增加PrintDocument的BeginPrint和EndPrint事件。BeginPrint事件用於得到被打印的內容。EndPrint用於釋放資源。 PrintDocument的PrintPage事件中實現分頁。
    基中:BeginPrint的事件方法在PrintPage事件方法前被呼叫。
           PintPage的事件方法在EndPrintPage事件方法前被呼叫。
           EndPrint事件方法最后被呼叫,EndPrint事件方法結束后會回到PrintDocument.Print()方法中,執行打印

其過程如下:
    1、實例化打印文檔
    2、訂閱事件(訂閱BeginPrint事件,用於得到被打印的內容;PinrtPage事件,用於繪製各個頁內容; EndPrint事件,用於釋放資源)
    3、調用BeginPrint事件的方法,得到打印內容
    4、調用PinrtPage事件的方法,繪制多個打印頁面,並根據判斷,設置是否進行多頁打印
    5、調用EndPrint事件的方法,釋放資源,完成后開始打印

代碼如下:


using System.IO;
using System.Drawing.Printing;

namespace SimpleEditor
{
    public partial class SimpleEditorForm : Form
    {
        private string filename = "Untitled";

        //1、實例化打印文檔
        PrintDocument pdDocument = new PrintDocument();        

        private string[] lines;
        private int linesPrinted;
        public SimpleEditorForm()
        {
            InitializeComponent();

            //2、訂閱事件

            
//訂閱PinrtPage事件,用於繪製各個頁內容
            pdDocument.PrintPage += new PrintPageEventHandler(OnPrintPage);
            //訂閱BeginPrint事件,用於得到被打印的內容
            pdDocument.BeginPrint += new PrintEventHandler(pdDocument_BeginPrint);
            //訂閱EndPrint事件,用於釋放資源
            pdDocument.EndPrint += new PrintEventHandler(pdDocument_EndPrint);
        }

        private void OnFilePrint(object sender, EventArgs e)
        {
            try
            {
                //調用打印
                pdDocument.Print();

                /*
                 * PrintDocument對象的Print()方法在PrintController類的幫助下,執行PrintPage事件。
                 
*/
            }
            catch (InvalidPrinterException ex )
            {
                MessageBox.Show(ex.Message, "Simple Editor", MessageBoxButtons.OK, MessageBoxIcon.Error);
                throw;
            }
        }

        /// <summary>
        
/// 3、得到打印內容
        
/// 每個打印任務衹調用OnBeginPrint()一次。
        
/// </summary>
        
/// <param name="sender"></param>
        
/// <param name="e"></param>
        void pdDocument_BeginPrint(object sender, PrintEventArgs e)
        {
            char[] param ={ '\n' };
            lines = textBoxEdit.Text.Split(param);

            int i = 0;
            char[] trimParam ={ '\r' };
            foreach (string s in lines)
            {
                lines[i++] = s.TrimEnd(trimParam);
            }
        }




        /// <summary>
        
/// 4、繪制多個打印頁面
        
/// printDocument的PrintPage事件
        
/// </summary>
        
/// <param name="sender"></param>
        
/// <param name="e"></param>
        private void OnPrintPage(object sender, PrintPageEventArgs e)
        {
            /*
             * 得到TextBox中每行的字符串數組
             * \n換行
             * \r回車
             
*/

            int x = 20;
            int y = 20;
            while (linesPrinted<lines.Length)
            {
                //繪製要打印的頁面
                e.Graphics.DrawString(lines[linesPrinted++], new Font("Arial"10), Brushes.Black, x, y);

                y += 55;

                //判斷超過一頁時,允許進行多頁打印
                if (y >= e.PageBounds.Height - 80)
                {
                    //允許多頁打印
                    e.HasMorePages = true;

                    /*
                     * PrintPageEventArgs類的HaeMorePages屬性為True時,通知控件器,必須再次調用OnPrintPage()方法,打印一個頁面。
                     * PrintLoopI()有一個用於每個要打印的頁面的序例。如果HasMorePages是False,PrintLoop()就會停止。
                     
*/
                    return;
                }
            }

            linesPrinted = 0;
            //繪制完成後,關閉多頁打印功能
            e.HasMorePages = false;

        }

        /// <summary>  
        
///5、EndPrint事件,釋放資源
        
/// </summary>
        
/// <param name="sender"></param>
        
/// <param name="e"></param>
        void pdDocument_EndPrint(object sender, PrintEventArgs e)
        {
           //變量Lines占用和引用的字符串數組,現在釋放
            lines = null;
        }
    }
}
要進行版面設置需要使用PageSetupDialog類。

PageSetupDialog
    可以配置頁面大小和紙張來源、方向、頁邊距,因為這些選項都依賴於打印機,所以在這個對話框中也可以選擇打印機。

它有一些屬性如下圖:

    

說明:

1、頁面
    AllowPaper
:是否可選擇頁面大小和紙張來源。
    PageSetupDialog.PageSetting.PaperSize
屬性返回一個PaperSize實例,用它的屬性HeightWidthPaperName可以讀取高度、寬度和紙張名稱。
    PaperName
指定諸如LetterA4等名稱。
    Kind
屬性返回一個枚舉,從中可獲取PaperKind枚舉的一個值,PaperKind枚舉包含許多不同的紙張大小,例如A3A4A5LetterLetterPlusLetterRotated
    PageSetupDiaog.PageSettings.PaperSource
屬性返回一個PaperSource實例,其中可以讀取打印機紙張來源和相應的紙張類型(只要打印機用該打印機設置進行了正確的配置)。

2、頁邊距
    AllowMargins
屬性允許用戶設置打印輸出的頁邊距值。
    MinMargins
可以為用戶定義輸入的最小頁邊距值.
    PageSetupDialog.PageSettings.Margins
讀取頁邊距,值有Bottom,Left,RightTop屬性。

3、方向
    AllowOrientation
屬性定義用戶是否可以選擇縱向和橫向打印方式。
    PageSetupDialog.PageSettings.Landscape
值可以讀取選定的值。橫向為True,縱向為False

4、打印機
AllowPrinter屬性指定用戶是否可選擇打印機。



PageSetupDialog的用法

   使用PageSetupDialog的方法比較簡單,只需
    1、在實例化一個
PageSetupDialog
    2、設置
document屬性設置為需要打印的文檔
    3、呼叫
ShowDialog()方法,打開版面設置

如前邊例子中加入版面設置,代碼如下:


using System.IO;
using System.Drawing.Printing;

namespace SimpleEditor
{
    public partial class SimpleEditorForm : Form
    {
        private string filename = "Untitled";

        //實例化打印文檔
        PrintDocument pdDocument = new PrintDocument();   
        
        //1、打印格式設置頁面
        PageSetupDialog dlgPageSetup = new PageSetupDialog();

        private string[] lines;
        private int linesPrinted;
        public SimpleEditorForm()
        {
            InitializeComponent();

            //訂閱事件

            
//訂閱PinrtPage事件,用於繪製各個頁內容
            pdDocument.PrintPage += new PrintPageEventHandler(OnPrintPage);
            //訂閱BeginPrint事件,用於得到被打印的內容
            pdDocument.BeginPrint += new PrintEventHandler(pdDocument_BeginPrint);
            //訂閱EndPrint事件,用於釋放資源
            pdDocument.EndPrint += new PrintEventHandler(pdDocument_EndPrint);

            //2、頁面設置的打印文檔設置為需要打印的文檔
            dlgPageSetup.Document = pdDocument;
        }


        /// <summary>
        
/// 3、在頁面設置按鈕事件中呼叫頁面設置界面,這樣單擊“頁面設置”按鈕就會彈出“頁面設置”界面
        
/// </summary>
        
/// <param name="sender"></param>
        
/// <param name="e"></param>
        private void OnFilePageSetup(object sender, EventArgs e)
        {
            dlgPageSetup.ShowDialog();
        }

        private void OnFilePrint(object sender, EventArgs e)
        {
            try
            {
                //調用打印
                pdDocument.Print();

                /*
                 * PrintDocument對象的Print()方法在PrintController類的幫助下,執行PrintPage事件。
                 
*/
            }
            catch (InvalidPrinterException ex )
            {
                MessageBox.Show(ex.Message, "Simple Editor", MessageBoxButtons.OK, MessageBoxIcon.Error);
                throw;
            }
        }

        /// <summary>
        
/// 得到打印內容
        
/// 每個打印任務衹調用OnBeginPrint()一次。
        
/// </summary>
        
/// <param name="sender"></param>
        
/// <param name="e"></param>
        void pdDocument_BeginPrint(object sender, PrintEventArgs e)
        {
            char[] param ={ '\n' };
            lines = textBoxEdit.Text.Split(param);

            int i = 0;
            char[] trimParam ={ '\r' };
            foreach (string s in lines)
            {
                lines[i++] = s.TrimEnd(trimParam);
            }
        }




        /// <summary>
        
/// 繪制多個打印頁面
        
/// printDocument的PrintPage事件
        
/// </summary>
        
/// <param name="sender"></param>
        
/// <param name="e"></param>
        private void OnPrintPage(object sender, PrintPageEventArgs e)
        {
            /*
             * 得到TextBox中每行的字符串數組
             * \n換行
             * \r回車
             
*/

            int x = 20;
            int y = 20;
            while (linesPrinted<lines.Length)
            {
                //繪製要打印的頁面
                e.Graphics.DrawString(lines[linesPrinted++], new Font("Arial"10), Brushes.Black, x, y);

                y += 55;

                //判斷超過一頁時,允許進行多頁打印
                if (y >= e.PageBounds.Height - 80)
                {
                    //允許多頁打印
                    e.HasMorePages = true;

                    /*
                     * PrintPageEventArgs類的HaeMorePages屬性為True時,通知控件器,必須再次調用OnPrintPage()方法,打印一個頁面。
                     * PrintLoopI()有一個用於每個要打印的頁面的序例。如果HasMorePages是False,PrintLoop()就會停止。
                     
*/
                    return;
                }
            }

            linesPrinted = 0;
            //繪制完成後,關閉多頁打印功能
            e.HasMorePages = false;

        }

        /// <summary>  
        
///EndPrint事件,釋放資源
        
/// </summary>
        
/// <param name="sender"></param>
        
/// <param name="e"></param>
        void pdDocument_EndPrint(object sender, PrintEventArgs e)
        {
           //變量Lines占用和引用的字符串數組,現在釋放
            lines = null;
        }
    }
}

 要想彈出“打印”窗口,可以在程式中呼叫PrintDialog界面。
    PrintDialog類允許用戶從已安裝的打印機中選擇一台打印機,選擇打印機份數和其它一找印設置,例如佈局和打印機紙張來源。

    PrintDialog相關屬性如下圖:


 

 


說明:
    AllowPrintToFile
:允許打印到文件選項
    AllowSelection
:允許打印選中的文本
    PrintRange:允許打印範圍
    AllowSomePage
允許打印頁面範圍
    PrinterSettings.FromPage
從哪頁開始
    PrinterSettings.ToPage
到哪頁結束
      注:
 打印任務的開始可以調用OnBeginPrint(),訪問PrintDialog.PrinterSettings.PrintRage屬性獲得用戶的Selection選項信息。此值為枚舉類型。

PrintDialog的用法以與PageSetupDialog用法類似。

即:

1、在實例化一個PrintDialog
  2
、設置document屬性設置為需要打印的文檔
  3
、呼叫ShowDialog()方法,打開“打印”界面。

代碼如下:(我們對前次的代碼作變變更,在“打印”按鈕事件中加入彈出“打印”界面的代碼。)


using System.IO;
using System.Drawing.Printing;

namespace SimpleEditor
{
    public partial class SimpleEditorForm : Form
    {
        private string filename = "Untitled";

        //實例化打印文檔
        PrintDocument pdDocument = new PrintDocument();   
        
        //打印格式設置頁面
        PageSetupDialog dlgPageSetup = new PageSetupDialog();

        //1、實例化打印頁面
        PrintDialog dlgPrint = new PrintDialog();

        private string[] lines;
        private int linesPrinted;
        public SimpleEditorForm()
        {
            InitializeComponent();

            //訂閱事件

            
//訂閱PinrtPage事件,用於繪製各個頁內容
            pdDocument.PrintPage += new PrintPageEventHandler(OnPrintPage);
            //訂閱BeginPrint事件,用於得到被打印的內容
            pdDocument.BeginPrint += new PrintEventHandler(pdDocument_BeginPrint);
            //訂閱EndPrint事件,用於釋放資源
            pdDocument.EndPrint += new PrintEventHandler(pdDocument_EndPrint);

            //頁面設置的打印文檔設置為需要打印的文檔
            dlgPageSetup.Document = pdDocument;

            //2、打印界面的打印文檔設置為被打印文檔
            dlgPrint.Document = pdDocument;
        }


        /// <summary>
        
/// 在頁面設置按鈕事件中呼叫頁面設置界面,這樣單擊“頁面設置”按鈕就會彈出“頁面設置”界面
        
/// </summary>
        
/// <param name="sender"></param>
        
/// <param name="e"></param>
        private void OnFilePageSetup(object sender, EventArgs e)
        {
            dlgPageSetup.ShowDialog();
        }

        private void OnFilePrint(object sender, EventArgs e)
        {   
            try
            {
                //判斷是否有選擇文本
                if (textBoxEdit.SelectedText != "")
                {
                    //如果有選擇文本,則可以選擇"打印選擇的範圍"
                    dlgPrint.AllowSelection = true;
                }
                else
                {
                    dlgPrint.AllowSelection = false;
                }
                //3、呼叫打印界面
                if (dlgPrint.ShowDialog()==DialogResult.OK)
                {

                    /*
                     * PrintDocument對象的Print()方法在PrintController類的幫助下,執行PrintPage事件。
                     
*/
                    pdDocument.Print();
                }
            }
            catch (InvalidPrinterException ex )
            {
                MessageBox.Show(ex.Message, "Simple Editor", MessageBoxButtons.OK, MessageBoxIcon.Error);
                throw;
            }
        }

        /// <summary>
        
/// 得到打印內容
        
/// 每個打印任務衹調用OnBeginPrint()一次。
        
/// </summary>
        
/// <param name="sender"></param>
        
/// <param name="e"></param>
        void pdDocument_BeginPrint(object sender, PrintEventArgs e)
        {
            char[] param ={ '\n' };
            lines = textBoxEdit.Text.Split(param);

            int i = 0;
            char[] trimParam ={ '\r' };
            foreach (string s in lines)
            {
                lines[i++] = s.TrimEnd(trimParam);
            }
        }




        /// <summary>
        
/// 繪制多個打印頁面
        
/// printDocument的PrintPage事件
        
/// </summary>
        
/// <param name="sender"></param>
        
/// <param name="e"></param>
        private void OnPrintPage(object sender, PrintPageEventArgs e)
        {
            /*
             * 得到TextBox中每行的字符串數組
             * \n換行
             * \r回車
             
*/

            int x = 20;
            int y = 20;
            while (linesPrinted<lines.Length)
            {
                //繪製要打印的頁面
                e.Graphics.DrawString(lines[linesPrinted++], new Font("Arial"10), Brushes.Black, x, y);

                y += 55;

                //判斷超過一頁時,允許進行多頁打印
                if (y >= e.PageBounds.Height - 80)
                {
                    //允許多頁打印
                    e.HasMorePages = true;

                    /*
                     * PrintPageEventArgs類的HaeMorePages屬性為True時,通知控件器,必須再次調用OnPrintPage()方法,打印一個頁面。
                     * PrintLoopI()有一個用於每個要打印的頁面的序例。如果HasMorePages是False,PrintLoop()就會停止。
                     
*/
                    return;
                }
            }

            linesPrinted = 0;
            //繪制完成後,關閉多頁打印功能
            e.HasMorePages = false;

        }

        /// <summary>  
        
///EndPrint事件,釋放資源
        
/// </summary>
        
/// <param name="sender"></param>
        
/// <param name="e"></param>
        void pdDocument_EndPrint(object sender, PrintEventArgs e)
        {
           //變量Lines占用和引用的字符串數組,現在釋放
            lines = null;
        }
    }
}

這樣我們就可以打印界面中選擇相關設定了。現在文件可以打印了,版面也可以設置了,在打印界面中也可作相關設定了,可是我們如何預覽列印呢?


    使用打印預覽界面可以使用PrintPreviewDialog
    .Net
中實現打印可使用PrintPreviewControl類,該類可以用來在窗體中預覽文檔。但這個類沒的提供相關菜單。
    PrintPreviewDialog
PrintPreviewControl有基礎上封裝了一些控件的對話框。它派生於System.Windows.Forms.Form

     這里我們用PrintPreviewDialog界面進行打印預覽。
   PrintPreviewDialog
的用法與PageSetupDiaogPrintDialog用法類似。即:

    1、在實例化一個PrintPreviewDialog
    2、設置document屬性設置為需要打印的文檔

    3、呼叫ShowDialog()方法,打開“打印”界面。

   注:打印DataGridView例子:https://files.cnblogs.com/scottckt/Print_DataGridView.rar   

   我們對前次的代碼作修改,增加預覽功能。代碼如下:

using System.IO;
using System.Drawing.Printing;

namespace SimpleEditor
{
    public partial class SimpleEditorForm : Form
    {
        private string filename = "Untitled";
        //打印文檔
        PrintDocument pdDocument = new PrintDocument();

        //打印格式設置頁面
        PageSetupDialog dlgPageSetup = new PageSetupDialog();

        //打印頁面
        PrintDialog dlgPrint = new PrintDialog();

        //1、實例化打印預覽
        PrintPreviewDialog dlgPrintPreview = new PrintPreviewDialog();


        private string[] lines;
        private int linesPrinted;

        public SimpleEditorForm()
        {
            InitializeComponent();
            pdDocument.PrintPage += new PrintPageEventHandler(OnPrintPage);
            pdDocument.BeginPrint += new PrintEventHandler(pdDocument_BeginPrint);
            pdDocument.EndPrint += new PrintEventHandler(pdDocument_EndPrint);

            //頁面設置的打印文檔設置為需要打印的文檔
            dlgPageSetup.Document = pdDocument;

            //打印界面的打印文檔設置為被打印文檔
            dlgPrint.Document = pdDocument;

            //2、打印預覽的打印文檔設置為被打印文檔
            dlgPrintPreview.Document = pdDocument;
        }

        /// <summary>
        
/// 打印預覽按鈕事件
        
/// </summary>
        
/// <param name="sender"></param>
        
/// <param name="e"></param>
        private void OnFilePrintPreview(object sender, EventArgs e)
        {
            //3、顯示打印預覽界面
            dlgPrintPreview.ShowDialog();
        }

        /// <summary>
        
/// 頁面設置
        
/// </summary>
        
/// <param name="sender"></param>
        
/// <param name="e"></param>
        private void OnFilePageSetup(object sender, EventArgs e)
        {
            dlgPageSetup.ShowDialog();
        }

        private void OnExit(object sender, EventArgs e)
        {

        }

        /// <summary>
        
/// 當按下打印時,此為界面中的打印按鈕事件
        
/// </summary>
        
/// <param name="sender"></param>
        
/// <param name="e"></param>
        private void OnFilePrint(object sender, EventArgs e)
        {
            try
            {
                //判斷是否有選擇文本
                if (textBoxEdit.SelectedText != "")
                {
                    //如果有選擇文本,則可以選擇"打印選擇的範圍"
                    dlgPrint.AllowSelection = true;
                }
                else
                {
                    dlgPrint.AllowSelection = false;
                }
                //呼叫打印界面
                if (dlgPrint.ShowDialog()==DialogResult.OK)
                {

                    /*
                     * PrintDocument對象的Print()方法在PrintController類的幫助下,執行PrintPage事件。
                     
*/
                    pdDocument.Print();
                }
            }
            catch (InvalidPrinterException ex )
            {
                MessageBox.Show(ex.Message, "Simple Editor", MessageBoxButtons.OK, MessageBoxIcon.Error);
                throw;
            }
        }

        /// <summary>
        
/// 每個打印任務衹調用OnBeginPrint()一次。
        
/// 所有要打印的內容都在此設置
        
/// </summary>
        
/// <param name="sender"></param>
        
/// <param name="e"></param>
        void pdDocument_BeginPrint(object sender, PrintEventArgs e)
        {
            char[] param ={ '\n' };
            //lines = textBoxEdit.Text.Split(param);
            
//判斷是否選取 列印被選擇的範圍
            if (dlgPrint.PrinterSettings.PrintRange==PrintRange.Selection)
            {
                lines = textBoxEdit.SelectedText.Split(param);
            }
            else
            {
                lines = textBoxEdit.Text.Split(param);
            }

            int i = 0;
            char[] trimParam ={ '\r' };
            foreach (string s in lines)
            {
                lines[i++] = s.TrimEnd(trimParam);
            }
        }




        /// <summary>
        
/// printDocument的PrintPage事件
        
/// </summary>
        
/// <param name="sender"></param>
        
/// <param name="e"></param>
        private void OnPrintPage(object sender, PrintPageEventArgs e)
        {
            /*
             * 得到TextBox中每行的字符串數組
             * \n換行
             * \r回車
             
*/

            int x = e.MarginBounds.Left;
            int y = e.MarginBounds.Top;
            while (linesPrinted<lines.Length)
            {
                e.Graphics.DrawString(lines[linesPrinted++], new Font("Arial"10), Brushes.Black, x, y);

                y += 55;

                //判斷超過一頁時,列印其它頁面
                if (y >= e.PageBounds.Height - 80)
                {
                    //多頁打印
                    e.HasMorePages = true;

                    /*
                     * PrintPageEventArgs類的HaeMorePages屬性為True時,通知控件器,必須再次調用OnPrintPage()方法,打印一個頁面。
                     * PrintLoopI()有一個用於每個要打印的頁面的序例。如果HasMorePages是False,PrintLoop()就會停止。
                     
*/
                    return;
                }
            }

            linesPrinted = 0;
            e.HasMorePages = false;

        }

        /// <summary>
        
/// EndPrint事件釋放BeginPrint方法中佔用的資源
        
/// </summary>
        
/// <param name="sender"></param>
        
/// <param name="e"></param>
        void pdDocument_EndPrint(object sender, PrintEventArgs e)
        {
           //變量Lines占用和引用的字符串數組,現在釋放
            lines = null;
        }
    }
}
posted @ 2012-03-09 09:10  swjm119  阅读(2584)  评论(0编辑  收藏  举报