首先创建一个打印机类,继承PrintDocument.重写OnBeginPrint 方法,和 OnPrintPage方法.
' 使用VB.net操作打印机
@H_502_52@ImportsSystem.Drawing.Printing @H_502_52@ImportsSystem.IO @H_502_52@ImportsBarcodeLib @H_502_52@ @H_502_52@ @H_502_52@PublicClassTextFilePrintDocument @H_502_52@ InheritsPrintDocument @H_502_52@ @H_502_52@ PrivateprintFontAsFont @H_502_52@ PrivatestreamToPrintAsStreamReader @H_502_52@ @H_502_52@ PublicSubNew(ByValstreamReaderAsStreamReader) @H_502_52@ MyBase.New() @H_502_52@ Me.streamToPrint = streamReader @H_502_52@ @H_502_52@ EndSub @H_502_52@ @H_502_52@ ProtectedOverridesSubOnBeginPrint(ByValeAsSystem.Drawing.Printing.PrintEventArgs) @H_502_52@ MyBase.OnBeginPrint(e) @H_502_52@ printFont= NewFont("Arial",10) @H_502_52@ EndSub @H_502_52@ @H_502_52@ ProtectedOverridesSubOnPrintPage(ByValeAsSystem.Drawing.Printing.PrintPageEventArgs) @H_502_52@ MyBase.OnPrintPage(e) @H_502_52@ DimlppAsSingle =e.MarginBounds.Height / printFont.GetHeight(e.Graphics) @H_502_52@ DimyPosAsSingle =0 @H_502_52@ DimcountAsSingle =0 @H_502_52@ DimleftMarginAsSingle =e.MarginBounds.Left @H_502_52@ DimtopMarginAsSingle =e.MarginBounds.Top @H_502_52@ DimlineAsString =streamToPrint.ReadLine() @H_502_52@ @H_502_52@ While (count < lppAndNotlineIsNothing) @H_502_52@ yPos= topMargin + (count * printFont.GetHeight(e.Graphics)) @H_502_52@ e.Graphics.DrawString(line,printFont,Brushes.Black,leftMargin,yPos,NewStringFormat()) @H_502_52@ count= count + 1 @H_502_52@ @H_502_52@ If (count < lpp)Then @H_502_52@ line= streamToPrint.ReadLine() @H_502_52@ EndIf @H_502_52@ @H_502_52@ EndWhile @H_502_52@ @H_502_52@ @H_502_52@ If (line <> Nothing) Then @H_502_52@ e.HasMorePages= True @H_502_52@ Else @H_502_52@ e.HasMorePages= False @H_502_52@ EndIf @H_502_52@ @H_502_52@ @H_502_52@ @H_502_52@ EndSub @H_502_52@ @H_502_52@EndClass @H_502_52@
-----------------
按钮的点击事件如下
@H_502_52@Imports System.IO @H_502_52@Imports System.Drawing.Printing @H_502_52@ @H_502_52@ PrivateSubprintButton_Click(ByValsenderAsSystem.Object,ByValeAsSystem.EventArgs) HandlesprintButton.Click @H_502_52@ Try @H_502_52@ DimstreamToPrintAsStreamReader= NewStreamReader("aa.txt") @H_502_52@ Try @H_502_52@ ' 使用缺省打印机 @H_502_52@ DimpdAsTextFilePrintDocument= NewTextFilePrintDocument(streamToPrint) @H_502_52@ @H_502_52@ @H_502_52@ IfNotstoredPageSettingsIsNothingThen @H_502_52@ pd.DefaultPageSettings = storedPageSettings @H_502_52@ EndIf @H_502_52@ @H_502_52@ DimdlgAsNewPrintDialog() @H_502_52@ dlg.Document= pd @H_502_52@ DimresultAsDialogResult= dlg.ShowDialog() @H_502_52@ @H_502_52@ If (result = System.Windows.Forms.DialogResult.OK) Then @H_502_52@ pd.Print() @H_502_52@ EndIf @H_502_52@ Finally @H_502_52@ streamToPrint.Close() @H_502_52@ EndTry @H_502_52@ CatchexAsException @H_502_52@ MessageBox.Show("error:" + ex.Message) @H_502_52@ EndTry @H_502_52@ EndSub @H_502_52@文件存放目录
这个参数是需要打印文件的目录