'声明一个PrintDocument
Public WithEvents prtDocument As New PrintDocument'打印预览代码
Dim ppd As New PrintPreviewDialog
Try
ppd.Document = prtDocument
ppd.ShowDialog()
Catch exp As Exception
MessageBox.Show(exp.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
Dim ppd As New PrintPreviewDialog
Try
ppd.Document = prtDocument
ppd.ShowDialog()
Catch exp As Exception
MessageBox.Show(exp.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
'打印代码
Protected Sub Print(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles prtDocument.PrintPage
Dim intPrintAreaHeight As Integer '打印区域的高度
Dim intPrintAreaWidth As Integer '打印区域的宽度
Dim marginLeft As Integer '左边距--
Dim marginTop As Integer '顶边距
With prtDocument.DefaultPageSettings
intPrintAreaHeight = .PaperSize.Height - .Margins.Top - .Margins.Bottom '实际高度 = 页面高度 - 顶边距-底边距
intPrintAreaWidth = .PaperSize.Width - .Margins.Left - .Margins.Right '实际宽度 = 页面宽度-左边距- 右边距
marginLeft = .Margins.Left
marginTop = .Margins.Top
End With
Static currentChar As Integer '记录已经打印里多少的字符。
'打印的区域
Dim areaRectangle As New RectangleF(marginTop, marginTop, intPrintAreaWidth, intPrintAreaHeight)
'打印的字体
Dim font As New Font("宋体", CInt(Me.TextBox1.Text))
'打印的格式
Dim fmt As New StringFormat(StringFormatFlags.LineLimit)
Dim printCount As Integer '一页中可以打印的行数。
printCount = Fix(intPrintAreaHeight / font.Height)
Dim charCount As Integer '一页能打印的字符数。
Dim lineCount As Integer '一页中可以打印的行数。
'测试一页能打印的信息
e.Graphics.MeasureString(Mid(Me.txtDocument.Text, currentChar + 1), font, New SizeF(intPrintAreaWidth, intPrintAreaHeight), fmt, charCount, lineCount)
e.Graphics.DrawString(Mid(Me.txtDocument.Text, currentChar + 1), font, Brushes.Black, areaRectangle, fmt)
'记录已经打印字符的位置
currentChar += charCount
'如果一页没有打完,则通知打印机,需要打印下一页。
If currentChar < Me.txtDocument.Text.Length Then
e.HasMorePages = True
Else
e.HasMorePages = False
currentChar = 0
End If
End Sub
测试一页能打印多少东东的方法有2种。
一、如果要打印的东东都是同一种字体,利用
e.Graphics.MeasureString 方法,得到一页能打印的字符数,和行数。
然后用一个static 变量 记录已经打印的字符数(或者是行数),判断一下是否打完了 ?
没有的话,就继续(e.HasMorePage =true)
二如果打印的东西字体格式不同(就象这个项目里面的,有条形码还有文字)
那么就得判断一页里能打多少行 来判断是否打印完毕了。
每一页能打印的行数 = Fix(页面实际打印高度/每一项字体的高度)
再程序里做个判断 也可以实现。
打印效果如下:
(Code-39码说前后要加 * 号,目前手上没有枪 没有试,但是csdn网友说是可以的,有枪的时候验证一下 2006-12-20)
浙公网安备 33010602011771号