There is no new technique or technique in this article. It just makes a summary of Windows Printing, including multi-page printing, print preview, printer settings, and page settings.
I. Print
Using system. Drawing. printing;
Private system. Drawing. Printing. printdocument;
This. printdocument. printpage + = new printpageeventhandler (this. printdocument_printpage );
System. Collections. arraylist infolist = new arraylist ();
Int totalpages = 0;
Int currentpage = 0;
Const int linesperpage = 10;
Private bool readyforprint ()
{
Infolist. Clear ();
Foreach (string line in this. textbox1.lines)
{
Infolist. Add (line );
}
Int COUNT = infolist. count;
If (count> 0)
{
Totalpages = count/linesperpage;
If (count % linesperpage! = 0)
{
Totalpages ++;
}
Currentpage = 1;
Return true;
}
Else
{
Return false;
}
}
Private void print ()
{
If (readyforprint ())
{
This. printdocument. Print ();
}
}
Private void printdocument_printpage (Object sender, system. Drawing. Printing. printpageeventargs E)
{
If (currentpage <= totalpages)
{
Graphics G = E. graphics;
Font drawfont = new font ("Arial", 12 );
Solidbrush drawbrush = new solidbrush (color. Black );
For (INT I = 0; I <linesperpage; I ++)
{
Int line = (CurrentPage-1) * linesperpage + I;
If (line> infolist. Count-1) {break ;}
String STR = (string) infolist [Line];
Int x = 100;
Int y = 200 + 50 * I;
G. drawstring (STR, drawfont, drawbrush, x, y );
}
Currentpage ++;
If (currentpage <= totalpages)
{
E. hasmorepages = true;
}
Else
{
E. hasmorepages = false;
}
}
}
}
When this. printdocument. Print (); is called, the print process starts to execute the content of printdocument_printpage. When the function exits, if E. hasmorepages is true, the print process calls printdocument_printpage again. The print process does not know the total number of pages to be printed and the current page to be printed.
Ii. Print and preview
Private void Preview ()
{
If (readyforprint ())
{
Printpreviewdialog = new printpreviewdialog ();
Printpreviewdialog. Document = printdocument;
Try
{
Printpreviewdialog. showdialog ();
}
Catch (exception excep)
{
MessageBox. Show (excep. message, "print error", messageboxbuttons. OK, messageboxicon. Error );
}
}
}
The print preview process also calls printdocument_printpage. Therefore, you must run readyforprint () so that printdocument_printpage can be correctly executed.
3. printer settings
Private void setprinter ()
{
Printdialog = new printdialog ();
Printdialog. Document = printdocument;
Printdialog. showdialog ();
}
Iv. Page settings
Private void setpage ()
{
Pagesetupdialog = new pagesetupdialog ();
Pagesetupdialog. Document = printdocument;
Pagesetupdialog. showdialog ();
}
Download source code