醫療項目需生成包含漢字的條碼標籤(如藥品名、劑量、病人信息),單純條碼庫無法直接編碼漢字,採用「條碼圖 + 文字圖拼接」方案完美解決。
Graphics2D) 繪製漢字信息(字體、大小、對齊)。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() 打印。GS k 打印條碼,ESC 3 設置行距打印文字),速度更快、無驅動依賴。此方案靈活性高,支持任意版面佈局、多語言混排,是 Java 生成複雜標籤的通用模式。