PrintDocument實例所有的訂閱事件如下:
- 創建一個PrintDocument的實例.如下: System.Drawing.Printing.PrintDocument docToPrint =
new System.Drawing.Printing.PrintDocument(); - 設置打印機開始打印的事件處理函數.函數原形如下: void docToPrint_PrintPage(object sender,
System.Drawing.Printing.PrintPageEventArgs e) - 將事件處理函數添加到PrintDocument的PrintPage事件中。 docToPrint.PrintPage+=new PrintPageEventHandler(docToPrint_PrintPage);
- 設置PrintDocument的相關屬性,如: PrintDialog1.AllowSomePages = true;PrintDialog1.ShowHelp = true;
- 把PrintDialog的Document屬性設為上面配置好的PrintDocument的實例: PrintDialog1.Document = docToPrint;
- 調用PrintDialog的ShowDialog函數顯示打印對話框: DialogResult result = PrintDialog1.ShowDialog();
- 根據用戶的選擇,開始打印: if (result==DialogResult.OK) { docToPrint.Print(); }
- 打印預覽控件PrintPreviewDialog
- PrintPreviewControl 在窗體中添加打印預覽
例子如下:
使用時先創建PrintService類的實例,然后調用void StartPrint(Stream streamToPrint,string streamType)函數開始打印。其中streamToPrint是要打印的內容(字節流),streamType是流的類型(txt表示普通文本,image表示圖像);
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.IO;
- using System.Drawing.Printing;
- using System.Windows.Forms;
- using System.Drawing;
- namespace ConsoleApplication1
- {
- public partial class PrintTxt:Form
- {
- private PrintPreviewDialog PrintPreview = new PrintPreviewDialog();
- private string StreamType;
- private Image image = null;
- private Stream StreamToPrint = null;
- Font mainFont = new Font("宋體", 12);//打印的字體
- public string Filename =null;
- //1、實例化打印文檔
- PrintDocument pdDocument = new PrintDocument();
- private string[] lines;
- private PrintPreviewControl printPreviewControl1;
- public PrintTxt()
- {
- InitializeComponent();
- }
- private int linesPrinted;
- public PrintTxt(string filepath,string filetype):this()
- {
- Filename = Path.GetFileNameWithoutExtension(filepath);
- //訂閱BeginPrint事件
- pdDocument.BeginPrint += new PrintEventHandler(pdDocument_BeginPrint);
- //訂閱EndPrint事件,釋放資源
- pdDocument.PrintPage += new PrintPageEventHandler(OnPrintPage);
- //訂閱Print打印事件,該方法必須放在訂閱打印事件的最后
- FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read);
- StartPrint(fs, filetype);
- //打印結束
- pdDocument.EndPrint += new PrintEventHandler(pdDocument_EndPrint);
- }
- //2、啟動Print打印方法
- public void StartPrint(Stream streamToPrint, string streamType)
- {
- //聲明返回值的PageSettings A4/A5
- PageSettings ps = new PageSettings();
- //顯示設置打印頁對話框
- PageSetupDialog Psdl = new PageSetupDialog();
- //打印多頁設置
- PrintDialog pt = new PrintDialog();
- pt.AllowCurrentPage = true;
- pt.AllowSomePages = true;
- pt.AllowPrintToFile = true;
- printPreviewControl1.Document = pdDocument;//form中的打印預覽
- printPreviewControl1.Zoom = 1.0;
- printPreviewControl1.Dock = DockStyle.Fill;
- printPreviewControl1.UseAntiAlias = true;
- StreamToPrint = streamToPrint;//打印的字節流
- StreamType = streamType; //打印的類型
- pdDocument.DocumentName = Filename; //打印的文件名
- Psdl.Document = pdDocument;
- PrintPreview.Document = pdDocument;
- PrintPreview.SetDesktopLocation(300, 800);
- Psdl.PageSettings = pdDocument.DefaultPageSettings;
- pt.Document = pdDocument;
- try
- {
- //顯示對話框
- if (Psdl.ShowDialog() == DialogResult.OK)
- {
- ps = Psdl.PageSettings;
- pdDocument.DefaultPageSettings = Psdl.PageSettings;
- }
- if (pt.ShowDialog() == DialogResult.OK)
- {
- pdDocument.PrinterSettings.Copies = pt.PrinterSettings.Copies;
- }
- if (PrintPreview.ShowDialog() == DialogResult.OK)
- //調用打印
- 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' };
- char[] trimParam = { '/r' };//回車
- switch (StreamType)
- {
- case "txt":
- StringBuilder text = new StringBuilder();
- System.IO.StreamReader streamReader = new StreamReader(StreamToPrint, Encoding.Default);
- while (streamReader.Peek() >= 0)
- {
- lines = streamReader.ReadToEnd().Split(param);
- for (int i = 0; i < lines.Length; i++)
- {
- lines[i] = lines[i].TrimEnd(trimParam);
- }
- }
- break;
- case "image":
- image = System.Drawing.Image.FromStream(StreamToPrint);
- break;
- default:
- break;
- }
- }
- /// <summary>
- /// 4、繪制多個打印界面
- /// printDocument的PrintPage事件
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void OnPrintPage(object sender, PrintPageEventArgs e)
- {
- int leftMargin = Convert.ToInt32((e.MarginBounds.Left) * 3 / 4); //左邊距
- int topMargin = Convert.ToInt32(e.MarginBounds.Top * 2 / 3); //頂邊距
- switch (StreamType)
- {
- case "txt":
- while (linesPrinted < lines.Length)
- {
- //向畫布中填寫內容
- e.Graphics.DrawString(lines[linesPrinted++], new Font("Arial", 10), Brushes.Black, leftMargin, topMargin, new StringFormat());
- topMargin += 55;//行高為55,可調整
- //走紙換頁
- if (topMargin >= e.PageBounds.Height - 60)//頁面累加的高度大於頁面高度。根據自己需要,可以適當調整
- {
- //如果大於設定的高
- e.HasMorePages = true;
- printPreviewControl1.Rows += 1;//窗體的打印預覽窗口頁面自動加1
- /*
- * PrintPageEventArgs類的HaeMorePages屬性為True時,通知控件器,必須再次調用OnPrintPage()方法,打印一個頁面。
- * PrintLoopI()有一個用於每個要打印的頁面的序例。如果HasMorePages是False,PrintLoop()就會停止。
- */
- return;
- }
- }
- break;
- case "image"://一下涉及剪切圖片,
- int width = image.Width;
- int height = image.Height;
- if ((width / e.MarginBounds.Width) > (height / e.MarginBounds.Height))
- {
- width = e.MarginBounds.Width;
- height = image.Height * e.MarginBounds.Width / image.Width;
- }
- else
- {
- height = e.MarginBounds.Height;
- width = image.Width * e.MarginBounds.Height / image.Height;
- }
- System.Drawing.Rectangle destRect = new System.Drawing.Rectangle(topMargin, leftMargin, width, height);
- //向畫布寫入圖片
- for (int i = 0; i < Convert.ToInt32(Math.Floor((double)image.Height/ 820)) + 1; i++)
- {
- e.Graphics.DrawImage(image, destRect, i*820,i*1170 , image.Width, image.Height, System.Drawing.GraphicsUnit.Pixel);
- //走紙換頁
- if (i * 1170 >= e.PageBounds.Height - 60)//頁面累加的高度大於頁面高度。根據自己需要,可以適當調整
- {
- //如果大於設定的高
- e.HasMorePages = true;
- printPreviewControl1.Rows += 1;//窗體的打印預覽窗口頁面自動加1
- /*
- * PrintPageEventArgs類的HaeMorePages屬性為True時,通知控件器,必須再次調用OnPrintPage()方法,打印一個頁面。
- * PrintLoopI()有一個用於每個要打印的頁面的序例。如果HasMorePages是False,PrintLoop()就會停止。
- */
- return;
- }
- }
- break;
- }
- //打印完畢后,畫線條,且注明打印日期
- e.Graphics.DrawLine(new Pen(Color.Black), leftMargin, topMargin, e.MarginBounds.Right, topMargin);
- string strdatetime = DateTime.Now.ToLongDateString() + DateTime.Now.ToLongTimeString();
- e.Graphics.DrawString(string.Format("打印時間:{0}", strdatetime), mainFont, Brushes.Black, e.MarginBounds.Right-240, topMargin+40, new StringFormat());
- 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;
- }
- private void InitializeComponent()
- {
- this.printPreviewControl1 = new System.Windows.Forms.PrintPreviewControl();
- this.SuspendLayout();
- //
- // printPreviewControl1
- //
- this.printPreviewControl1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
- | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
- this.printPreviewControl1.Location = new System.Drawing.Point(12, 3);
- this.printPreviewControl1.Name = "printPreviewControl1";
- this.printPreviewControl1.Size = new System.Drawing.Size(685, 511);
- this.printPreviewControl1.TabIndex = 0;
- //
- // PrintTxt
- //
- this.ClientSize = new System.Drawing.Size(696, 526);
- this.Controls.Add(this.printPreviewControl1);
- this.Name = "PrintTxt";
- this.ResumeLayout(false);
- }
- }
- //PrintTxt simple = new PrintTxt("D://Mainsoft//12.txt", "txt");
- }
調用方式 PrintTxt simple = new PrintTxt("D://Mainsoft//12.txt", "txt");
驗證通過;
來自:http://blog.csdn.net/tsapi/article/details/6237695