You need to enable JavaScript to run this app. 如何在VB.NET中通过HTML&CSS打印POS小票并添加底部二维码
优惠活动
大模型
产品
解决方案
定价
更多

如何在VB.NET中通过HTML&CSS打印POS小票并添加底部二维码

POS小票打印(含二维码)优化方案

一、HTML结构与小票适配调整

POS小票多为窄幅(比如80mm),先固定页面宽度避免排版混乱:

@media print {
  body {
    width: 80mm; /* 匹配小票纸实际宽度 */
    margin: 0;
    padding: 5mm;
    font-family: "Courier New", monospace; /* 用等宽字体保证文字、数字对齐 */
    font-size: 12px;
  }
}
  • 必须用等宽字体,这是小票排版对齐的核心,避免因字体宽度不一致导致错位
  • 清空默认页面边距,用padding控制内边距,防止内容被打印控件裁剪

二、二维码渲染与打印兼容

二维码模糊或不显示是高频问题,按以下方式处理:

  1. 用<img>引入二维码时,指定固定像素尺寸,禁用百分比:
<div style="text-align: center; margin-top: 10px;">
  <img src="你的二维码生成地址" width="80" height="80" style="image-rendering: pixelated;" />
</div>
  • image-rendering: pixelated能让低分辨率二维码打印时更清晰
  • 优先用PNG/JPG格式的二维码,部分打印控件对SVG支持不佳
  1. 动态生成二维码(比如用ZXing库)时,直接转Base64嵌入HTML:
' VB.NET中用ZXing生成二维码并转为Base64嵌入
Dim writer As New BarcodeWriterPixelData With {
  .Format = BarcodeFormat.QR_CODE,
  .Options = New QrCode.QrCodeEncodingOptions With {
    .Width = 80,
    .Height = 80,
    .Margin = 1
  }
}
Dim pixelData = writer.Write("二维码内容")
Using bitmap = New Bitmap(pixelData.Width, pixelData.Height)
Using ms = New MemoryStream()
  Dim bitmapData = bitmap.LockBits(New Rectangle(0, 0, pixelData.Width, pixelData.Height), Imaging.ImageLockMode.WriteOnly, PixelFormat.Format32bppRgb)
  System.Runtime.InteropServices.Marshal.Copy(pixelData.Pixels, 0, bitmapData.Scan0, pixelData.Pixels.Length)
  bitmap.UnlockBits(bitmapData)
  bitmap.Save(ms, Imaging.ImageFormat.Png)
  Dim base64 = Convert.ToBase64String(ms.ToArray())
  htmlContent &= $"<img src='data:image/png;base64,{base64}' width='80' height='80' />"
End Using
End Using

三、VB.NET打印控件配置

别用WebBrowser默认打印,必须调整打印参数匹配小票纸:

Dim printDialog As New PrintDialog()
' 设置自定义小票尺寸(80mm宽,200mm长,可按需修改)
printDialog.PrinterSettings.DefaultPageSettings.PaperSize = New PaperSize(PaperName.Custom, MillimetersToHundredthsOfInch(80), MillimetersToHundredthsOfInch(200))
printDialog.PrinterSettings.DefaultPageSettings.Margins = New Margins(0, 0, 0, 0)

If printDialog.ShowDialog() = DialogResult.OK Then
  webBrowser1.Print()
End If

' 辅助转换:毫米转打印API用的百分之一英寸单位
Private Function MillimetersToHundredthsOfInch(mm As Integer) As Integer
  Return CInt(mm * 3.937)
End Function
  • 必须设置自定义纸张尺寸,否则内容会被分页或强制缩放
  • 禁用边距,避免浪费小票打印区域

四、调试技巧

  • 先在浏览器中打开HTML内容,按Ctrl+P看打印预览,确认排版正常再用VB控件打印
  • 临时给所有元素加边框调试:* { border: 1px solid red; },检查是否有元素超出小票宽度
  • 避免用flex/grid等复杂CSS,部分老打印控件支持差,用表格布局更稳妥:
<table width="100%" border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td align="left">商品名称</td>
    <td align="right">¥19.9</td>
  </tr>
</table>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 14:57:23