C # print
Last Update:2018-12-05
Source: Internet
Author: User
Using System;
Using System. Collections. Generic;
Using System. Text;
Using System. Drawing;
Using System. Drawing. Printing;
Using System. Windows. Forms;
Using System. IO;
Namespace MyCCTV
{
Sealed class TextFilePrinter
{
String fileName;
Encoding theEncode;
Font theFont;
StreamReader srToPrint;
Int currPage;
Public TextFilePrinter (string fileName)
: This (fileName, Encoding. GetEncoding (936), new Font ("ms ui Gothic", 9 ))
{
}
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;
}
}
}