You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VB.NET打印成绩单遇异常:不同尺寸显示器下内容边缘被裁切

问题分析与修复方案

你的问题核心是直接将窗体的像素尺寸Bitmap原封不动绘制到打印页面,不同显示器的DPI、窗体实际像素尺寸存在差异,而打印页面的可打印区域是固定的(A4横向的可打印范围),导致高分辨率大尺寸显示器上的窗体内容超出打印边界被裁切。

具体修复步骤

  1. 使用系统标准纸张尺寸:避免自定义PaperSize,直接用内置的A4枚举值,确保和打印机驱动的纸张定义一致。
  2. 基于打印页面的可打印区域做缩放适配:获取打印页面的可打印边界,计算窗体内容到打印区域的缩放比例,保证内容完整适配打印范围,同时保持比例不变。
  3. 处理DPI差异:打印设备的DPI(通常为300)和屏幕DPI(如96、120)不同,通过高质量绘制参数避免内容缩放失真。

修改后的完整代码

打印初始化代码

Dim printDoc As New PrintDocument()
' 使用系统标准A4纸张,设置横向
printDoc.DefaultPageSettings.PaperSize = New PaperSize(PaperSizeName.A4, 827, 1169)
printDoc.DefaultPageSettings.Landscape = True
AddHandler printDoc.PrintPage, AddressOf PrintPageHandler

printDoc.Print()
Me.FormBorderStyle = FormBorderStyle.Sizable

Printbtn.Visible = True
Prevbtn.Visible = True
Nextbtn.Visible = True
Firstbtn.Visible = True
Lastbtn.Visible = True

打印页面处理方法

Private Sub PrintPageHandler(sender As Object, e As PrintPageEventArgs)
    ' 获取打印页面的可打印区域
    Dim printArea As RectangleF = e.MarginBounds
    
    ' 创建窗体的Bitmap(若窗体超出屏幕,可提前设置窗体尺寸为打印适配大小)
    Using formBitmap As New Bitmap(Me.Width, Me.Height, Imaging.PixelFormat.Format64bppArgb)
        Me.DrawToBitmap(formBitmap, New Rectangle(0, 0, Me.Width, Me.Height))
        
        ' 计算缩放比例:取宽高比例的最小值,保证内容完全放入打印区域且不拉伸
        Dim scaleX As Single = printArea.Width / formBitmap.Width
        Dim scaleY As Single = printArea.Height / formBitmap.Height
        Dim scale As Single = Math.Min(scaleX, scaleY)
        
        ' 计算居中绘制的坐标(若需要左上角对齐,直接设为printArea.Left和printArea.Top即可)
        Dim drawX As Single = printArea.Left + (printArea.Width - formBitmap.Width * scale) / 2
        Dim drawY As Single = printArea.Top + (printArea.Height - formBitmap.Height * scale) / 2
        
        ' 设置高质量绘制参数
        e.Graphics.SmoothingMode = Drawing2D.SmoothingMode.HighQuality
        e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
        e.Graphics.PixelOffsetMode = Drawing2D.PixelOffsetMode.HighQuality
        
        ' 按比例绘制Bitmap到打印区域
        e.Graphics.DrawImage(formBitmap, drawX, drawY, formBitmap.Width * scale, formBitmap.Height * scale)
    End Using

    e.HasMorePages = False
End Sub

额外说明

  • 使用Using语句自动释放Bitmap资源,比手动调用Dispose更安全可靠。
  • 若你的成绩单内容是动态生成的,建议直接在PrintPageHandler中绘制内容(而非捕获窗体Bitmap),完全基于打印页面坐标绘制,从根源避免屏幕尺寸差异问题。

内容的提问来源于stack exchange,提问作者Sujay Ghosh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 19:37:02