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

JavaWeb 生成帶漢字條碼:圖片拼接法解決打印需求

     編輯:程式設計綜合問答

醫療項目需生成包含漢字的條碼標籤(如藥品名、劑量、病人信息),單純條碼庫無法直接編碼漢字,採用「條碼圖 + 文字圖拼接」方案完美解決。

技術方案

  1. 生成條碼圖:用 ZXing/Barcode4j 生成 Code128/QR Code 圖片(僅編碼數字/字母 ID)。
  2. 生成文字圖:用 Java2D (Graphics2D) 繪製漢字信息(字體、大小、對齊)。
  3. 圖片拼接:將條碼圖與文字圖垂直/水平拼合為單一 BufferedImage。
  4. 輸出/打印:輸出 PNG 供網頁預覽,或直接發送到打印機(ESC/POS 指令或 Java Print Service)。

核心代碼片段

public BufferedImage createLabel(String barcodeData, String[] textLines) {
    // 1. 生成條碼
    BufferedImage barcodeImg = BarcodeUtil.generateCode128(barcodeData, 300, 100);
    
    // 2. 計算文字區域高度
    Font font = new Font("微軟雅黑", Font.PLAIN, 24);
    FontMetrics fm = new BufferedImage(1,1,BufferedImage.TYPE_INT_ARGB).getGraphics().getFontMetrics(font);
    int lineHeight = fm.getHeight();
    int textHeight = textLines.length * lineHeight + 20;
    
    // 3. 創建畫布拼接
    int totalWidth = Math.max(barcodeImg.getWidth(), 400);
    int totalHeight = barcodeImg.getHeight() + textHeight;
    BufferedImage combined = new BufferedImage(totalWidth, totalHeight, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = combined.createGraphics();
    g.setColor(Color.WHITE); g.fillRect(0, 0, totalWidth, totalHeight); // 白底
    
    // 繪製條碼(居中)
    int bx = (totalWidth - barcodeImg.getWidth()) / 2;
    g.drawImage(barcodeImg, bx, 10, null);
    
    // 繪製文字
    g.setFont(font);
    g.setColor(Color.BLACK);
    for (int i = 0; i < textLines.length; i++) {
        int tx = (totalWidth - fm.stringWidth(textLines[i])) / 2;
        int ty = barcodeImg.getHeight() + 20 + (i + 1) * lineHeight;
        g.drawString(textLines[i], tx, ty);
    }
    g.dispose();
    return combined;
}

打印集成建議

  • 網頁預覽:將 BufferedImage 轉 Base64 Data URL 或保存臨時文件供 <img> 顯示,用 window.print() 打印。
  • 標籤打印機:直接發送 ESC/POS 指令(GS k 打印條碼,ESC 3 設置行距打印文字),速度更快、無驅動依賴。
  • 字體授權:商業項目使用微軟雅黑等字體需確認授權,或改用開源字體(思源黑體、Noto Sans SC)。

此方案靈活性高,支持任意版面佈局、多語言混排,是 Java 生成複雜標籤的通用模式。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved