PrintDocument執行個體所有的訂閱事件如下:
1.建立一個PrintDocument的執行個體.如下:
System.Drawing.Printing.PrintDocument docToPrint =
new System.Drawing.Printing.PrintDocument();
2.設定印表機開始列印的事件處理函數.函數原形如下:
void docToPrint_PrintPage(object sender,
System.Drawing.Printing.PrintPageEventArgs e)
3.將事件處理函數添加到PrintDocument的PrintPage事件中。
docToPrint.PrintPage+=new PrintPageEventHandler(docToPrint_PrintPage);
4.設定PrintDocument的相關屬性,如:
PrintDialog1.AllowSomePages = true;PrintDialog1.ShowHelp = true;
5.把PrintDialog的Document屬性設為上面配置好的PrintDocument的執行個體:
PrintDialog1.Document = docToPrint;
6.調用PrintDialog的ShowDialog函數顯示列印對話方塊:
DialogResult result = PrintDialog1.ShowDialog();
7.根據使用者的選擇,開始列印:
if (result==DialogResult.OK)
{
docToPrint.Print();
}
8.預覽列印控制項PrintPreviewDialog
例子如下:
使用時先建立PrintService類的執行個體,然後調用void StartPrint(Stream streamToPrint,string streamType)函數開始列印。其中streamToPrint是要列印的內容(位元組流),streamType是流的類型(txt表示普通文本,image表示映像);
public partial class PrintTxt { 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 int linesPrinted; public PrintTxt(string filepath,string filetype) { 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(); //列印多份設定,注意,該方法需放在printpage方法後面。 PrintDialog pt = new PrintDialog(); pt.AllowCurrentPage = true; pt.AllowSomePages = true; pt.AllowPrintToFile = true; StreamToPrint = streamToPrint;//列印的位元組流 StreamType = streamType; //列印的類型 pdDocument.DocumentName = Filename; //列印的檔案名稱 Psdl.Document = pdDocument; PrintPreview.Document = pdDocument; pt.Document = pdDocument; Psdl.PageSettings = pdDocument.DefaultPageSettings; try { //顯示對話方塊 if (Psdl.ShowDialog() == DialogResult.OK) { ps = Psdl.PageSettings; pdDocument.DefaultPageSettings = Psdl.PageSettings; } if (pt.ShowDialog() == DialogResult.OK) { pdDocument.PrinterSettings.Copies = pt.PrinterSettings.Copies; pdDocument.Print(); } 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; /* * 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; /* * 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; } } //PrintTxt simple = new PrintTxt("D:\\Mainsoft\\12.txt", "txt");