首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C# 熱敏打印機打印二維碼:位圖直印方案詳解

     編輯:程式設計綜合問答

方案選型

熱敏打印機通常提供兩種模式:

  1. 指令模式:發送 ESC/POS 指令(如 GS k)讓打印機內部生成二維碼,優點是速度快、不依賴圖片質量。
  2. 位圖模式:客戶端生成二維碼圖片,調用 GcPrintBitmap 打印位圖,優點是通用性強、支持 Logo 嵌入。

本文聚焦 位圖模式,對應廠商 SDK 的 GcPrintBitmap。

關鍵參數解讀

int GcPrintBitmap(char *szBmpFile, int m);
參數含義典型值
szBmpFileBMP 文件完整路徑"C:\\temp\\qrcode.bmp"
m打印模式(垂直點數、密度、數據量)0,1,32,33

模式對照表:

m=0  8點單密度  67.7 DPI  101.6 DPI  數據量 = nL+nH×256
m=1  8點雙密度  67.7 DPI  203.2 DPI  數據量 = nL+nH×256
m=32 24點單密度 203.2 DPI 101.6 DPI  數據量 = (nL+nH×256)×3
m=33 24點雙密度 203.2 DPI 203.2 DPI 數據量 = (nL+nH×256)×3

完整 C# 封裝示例

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;

public class ThermalPrinter {
    [DllImport("Gprinter.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
    private static extern int GcPrintBitmap(string bmpPath, int mode);

    [DllImport("Gprinter.dll")]
    private static extern int GcOpenPrinter(string printerName);

    [DllImport("Gprinter.dll")]
    private static extern int GcClosePrinter();

    public bool PrintQR(string content, int mode = 33) {
        // 1. 生成二維碼圖片 (需引用 QRCoder NuGet)
        using (var qr = new QRCoder.QRCodeGenerator())
        using (var data = qr.CreateQrCode(content, QRCoder.QRCodeGenerator.ECCLevel.Q))
        using (var qrCode = new QRCoder.QRCode(data))
        using (var bmp = qrCode.GetGraphic(4)) {  // 4px per module
            string path = Path.Combine(Path.GetTempPath(), "qr_" + Guid.NewGuid() + ".bmp");
            bmp.Save(path, ImageFormat.Bmp);

            // 2. 打開打印機 (根據實際驅動名稱)
            if (GcOpenPrinter("GP-5890X") != 0) return false;

            // 3. 打印位圖
            int ret = GcPrintBitmap(path, mode);

            // 4. 關閉並清理
            GcClosePrinter();
            File.Delete(path);
            return ret == 0;
        }
    }
}

避坑指南

  • BMP 必須為 1位單色 (Format1bppIndexed),彩色/灰度會打印失敗。
  • 圖片寬度建議為 8 的倍數,高度不超過打印機緩衝區限制。
  • 調用前確保打印機處於 就緒狀態(無缺紙、蓋子關閉)。
  • 模式 m=33 (24點雙密度) 適合 58mm/80mm 寬熱敏紙,清晰度最高。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved