VB.NET打印Panel异常:仅显示“正在打印”但未实际输出
问题:Panel控件打印仅显示“正在打印”提示,无实际打印输出
尝试打印Panel控件时,仅显示“正在打印”提示,但未完成实际打印操作,相关代码如下:
Private bmp As Bitmap Private Sub PrintDocument2_PrintPage(sender As Object, e As PrintPageEventArgs) Handles PrintDocument2.PrintPage e.Graphics.DrawImage(bmp, 0, 0) End Sub Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click bmp = New Bitmap(rec.Width, rec.Height) Dim G As Graphics = Graphics.FromImage(bmp) rec.DrawToBitmap(bmp, rec.ClientRectangle) G.Dispose() PrintPreviewDialog1.Document = PrintDocument1 PrintPreviewDialog1.ShowDialog() End Sub
问题分析与修复方案
核心错误:PrintDocument绑定不匹配
代码中PrintPage事件绑定的是PrintDocument2,但打印预览对话框关联的却是PrintDocument1,导致打印逻辑根本没有被触发。冗余代码:无用的Graphics对象
创建的G对象没有被实际使用,直接调用rec.DrawToBitmap即可完成Panel的位图绘制,多余的创建和释放操作可以移除。资源泄漏:Bitmap未正确释放
全局的bmp对象如果不及时释放,会导致内存泄漏,建议在打印完成后手动释放资源。
修正后的代码
Private bmp As Bitmap Private Sub PrintDocument2_PrintPage(sender As Object, e As PrintPageEventArgs) Handles PrintDocument2.PrintPage If bmp IsNot Nothing Then e.Graphics.DrawImage(bmp, 0, 0) End If End Sub Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click ' 先释放之前的Bitmap资源 If bmp IsNot Nothing Then bmp.Dispose() bmp = Nothing End If ' 创建对应尺寸的Bitmap并绘制Panel内容 bmp = New Bitmap(rec.ClientSize.Width, rec.ClientSize.Height) rec.DrawToBitmap(bmp, rec.ClientRectangle) ' 绑定正确的PrintDocument到预览对话框 PrintPreviewDialog1.Document = PrintDocument2 Dim dialogResult As DialogResult = PrintPreviewDialog1.ShowDialog() ' 预览完成后释放Bitmap资源 If dialogResult = DialogResult.Cancel Or dialogResult = DialogResult.OK Then bmp.Dispose() bmp = Nothing End If End Sub
额外注意事项
- 如果需要实际打印(而非仅预览),可以在预览确认后调用
PrintDocument2.Print()方法。 - 若打印内容位置或尺寸不符合预期,可以通过
e.Graphics.ScaleTransform调整缩放比例,或者指定DrawImage的目标矩形参数来适配打印纸张。
内容的提问来源于stack exchange,提问作者Aprilanne Ocenar
相关产品推荐
相关产品推荐

