// this method will set properties on the printdialog object and // then display the dialog. public void startprint(stream streamtoprint,string streamtype) {
this.streamtoprint=streamtoprint; this.streamtype=streamtype; // allow the user to choose the page range he or she would // like to print. system.windows.forms.printdialog printdialog1=new printdialog ();//创建一个printdialog的实例。 printdialog1.allowsomepages = true;
// show the help button. printdialog1.showhelp = true;
// set the document property to the printdocument for // which the printpage event has been handled. to display the // dialog, either this property or the printersettings property // must be set printdialog1.document = doctoprint;//把printdialog的document属性设为上面配置好的printdocument的实例
dialogresult result = printdialog1.showdialog();//调用printdialog的showdialog函数显示打印对话框
// if the result is ok then print the document. if (result==dialogresult.ok) { doctoprint.print();//开始打印 }
}
// the printdialog will print the document // by handling the document’s printpage event. private void doctoprint_printpage(object sender, system.drawing.printing.printpageeventargs e)//设置打印机开始打印的事件处理函数 {
// insert code to render the page here. // this code will be called when the control is drawn.
// the following code will render a simple // message on the printed document switch(this.streamtype) { case "txt": string text = null; system.drawing.font printfont = new system.drawing.font ("arial", 35, system.drawing.fontstyle.regular);
// draw the content. system.io.streamreader streamreader=new streamreader(this.streamtoprint); text=streamreader.readtoend(); e.graphics.drawstring(text,printfont,system.drawing.brushes.black,e.marginbounds.x,e.marginbounds.y); break; case "image": system.drawing.image image=system.drawing.image.fromstream(this.streamtoprint); int x=e.marginbounds.x; int y=e.marginbounds.y; 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(x,y,width,height); e.graphics.drawimage(image,destrect,0,0,image.width,image.height,system.drawing.graphicsunit.pixel); break; default: break; }