Using System;
Using System. Drawing;
Using System. Drawing. Printing;
Using System. Windows. Forms;
Using System. IO;
Using System. Text;
Namespace Skyiv. Util {
Sealed class TextFilePrinter {
String fileName;
Encoding theEncode;
Font theFont;
StreamReader srToPrint;
Int currPage;
Public TextFilePrinter (
String fileName): this (fileName, Encoding. GetEncoding ("GB18030"), new Font ("" ", 10 )){}
Public TextFilePrinter (string fileName, Encoding theEncode, Font theFont ){
This. fileName = fileName;
This. theEncode = theEncode;
This. theFont = theFont ;}
Public void Print (){
Using (srToPrint = new StreamReader (fileName, theEncode )){
PrintDialog dlg = new PrintDialog ();
Dlg. Document = GetPrintDocument ();
Dlg. AllowSomePages = true;
Dlg. AllowPrintToFile = false;
If (dlg. ShowDialog () = DialogResult. OK)
Dlg. Document. Print ();
}
}
Public void View (){
Using (srToPrint = new StreamReader (fileName, theEncode )){
PrintPreviewDialog dlg = new PrintPreviewDialog ();
Dlg. Document = GetPrintDocument ();
Dlg. ShowDialog ();
}
}
PrintDocument GetPrintDocument (){
CurrPage = 1;
PrintDocument doc = new PrintDocument ();
Doc. DocumentName = fileName;
Doc. PrintPage + = new PrintPageEventHandler (PrintPageEvent );
Return doc;
}
Void PrintPageEvent (object sender, PrintPageEventArgs ev ){
String line = null;
Float linesPerPage = ev. MarginBounds. Height/theFont. GetHeight (ev. Graphics );
Bool isSomePages = ev. PageSettings. PrinterSettings. PrintRange = PrintRange. SomePages;
If (isSomePages ){
While (currPage <ev. PageSettings. PrinterSettings. FromPage ){
For (int count = 0; count <linesPerPage; count ++ ){
Line = srToPrint. ReadLine ();
If (line = null) break ;}
If (line = null) return; currPage ++ ;}
If (currPage> ev. PageSettings. PrinterSettings. ToPage) return ;}
For (int count = 0; count <linesPerPage; count ++ ){
Line = srToPrint. ReadLine (); if (line = null) break;
Ev. Graphics. DrawString (line, theFont, Brushes. Black, ev. MarginBounds. Left,
Ev. MarginBounds. Top + (count * theFont. GetHeight (ev. Graphics), new StringFormat ());}
CurrPage ++;
If (isSomePages & currPage> ev. PageSettings. PrinterSettings. ToPage) return;
If (line! = Null) ev. HasMorePages = true ;}}}