Java条形码标签生成并打印示例

2019-11-14 18:00:54  卢浮宫  阅读量:111  版权声明:本文为站长原创文章,转载请写明出处


一、最近接收到需求:标签打印传入参数,生成标签,然后调用打印机(启锐488)进行打印

二、问题处理步骤

    ①条形码生成 -- 使用zxing

    ②图片生成 -- Graphics

    ③图片打印 -- printService

三、关键点描述

    ①maven引用

        <!--条形码打印-->

     <dependency>
        <groupId>com.google.zxing</groupId>
        <artifactId>core</artifactId>
        <version>3.3.3</version>
    </dependency>
    
    <dependency>
        <groupId>com.google.zxing</groupId>
        <artifactId>javase</artifactId>
        <version>3.3.3</version>
    </dependency>
                 <!--条形码打印-->

          

四、条形码生成代码示例

                   

 package com.hd.common.utils;


import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.oned.Code128Writer;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
* @author XA
* date 2019/11/12 16:34
* description 条形码工具类
* params
* return
*/
@Component
public class BarCodeUtils {

@Value("${print.barCodeWidth}")
private int barCodeWidth;

@Value("${print.barCodeheight}")
private int barCodeheight;

@Value("${print.barCodeAndWordHeight}")
private int barCodeAndWordHeight;

/**
* 功能描述: 条形码参数设置
* Param:
* Return:
*/
private static Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>() {
private static final long serialVersionUID = 1L;
{
// 设置编码方式
put(EncodeHintType.CHARACTER_SET, "utf-8");
}
};

/**
* 功能描述:生成图片缓冲
* Param: [vaNumber]
* Return: java.awt.image.BufferedImage
*/
public BufferedImage getBarCode(String vaNumber){
try {
Code128Writer writer = new Code128Writer();
// 编码内容, 编码类型, 宽度, 高度, 设置参数
BitMatrix bitMatrix = writer.encode(vaNumber, BarcodeFormat.CODE_128, barCodeWidth, barCodeheight, hints);
return MatrixToImageWriter.toBufferedImage(bitMatrix);
} catch (WriterException e) {
e.printStackTrace();
}
return null;
}

/**
* 功能描述: 条形码及文字刻画
* Param: [image, words, verifyCodes]
* Return: java.awt.image.BufferedImage
*/
public BufferedImage insertWords(BufferedImage image, String words,String[] verifyCodes) throws IOException {
if (StringUtils.isNotEmpty(words)) {
BufferedImage outImage = new BufferedImage(barCodeWidth, barCodeAndWordHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = outImage.createGraphics();
// 抗锯齿
setGraphics2D(g2d);
// 设置白色
setColorWhite(g2d);
// 画文字到新的面板
Color color=new Color(0, 0, 0);
g2d.setColor(color);
//文字长度
int strWidth = g2d.getFontMetrics().stringWidth(words);
//总长度减去文字长度的一半 (居中显示)
int wordStartX = (barCodeWidth - strWidth) / 2;
int wordStartY = barCodeheight + 20;
// 画文字
for (int i = 0; i < verifyCodes.length; i++) {
if(i == 0){
// 添加logo
URL resourceUrl = BarCodeUtils.class.getClassLoader().getResource("statics/print/logo.png");
if(resourceUrl == null){
return null;
}
String imgLogoPath = resourceUrl.getPath();
BufferedImage bufferedImage = ImageIO.read(new FileInputStream(imgLogoPath));
g2d.drawImage(bufferedImage, 70, 20, 100, 70, null);
// 添加首行文字
Font font = getFont(27);
int h = getFontHeight(font);
drawWords(g2d, font, verifyCodes[i], 250, i * h + 65);
}else{
Font font = getFont(22);
int h = getFontHeight(font);
drawWords(g2d, font, verifyCodes[i], 200 * (i-1) + 35, 3 * h + 60);
}
}
// 画条形码到新的面板
g2d.drawImage(image, 100, 190, 400, image.getHeight(), null);
// 补充运单号
g2d.drawString(words, 215, 300);
g2d.dispose();
outImage.flush();
return outImage;
}
return null;
}

/**
* 功能描述: 画文字到面板
* Param: [g2d, font, words, x, y]
* Return: void
*/
private void drawWords(Graphics2D g2d, Font font, String words, int x, int y){
g2d.setFont(font);
FontMetrics fm = sun.font.FontDesignMetrics.getMetrics(font);
g2d.drawString(words, x, y);
}

/**
* 功能描述:获取字体高度属性
* Param: [font]
* Return: int
*/
private int getFontHeight(Font font){
FontMetrics fm = sun.font.FontDesignMetrics.getMetrics(font);
return fm.getHeight();
}

private static Font getFont(int size){
return new Font("微软雅黑", Font.PLAIN, size);
}

/**
* 功能描述:设置 Graphics2D 属性(抗锯齿)
* Param: [g2d] Graphics2D提供对几何形状、坐标转换、颜色管理和文本布局更为复杂的控制
* Return: void
*/
private static void setGraphics2D(Graphics2D g2d){
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT);
Stroke s = new BasicStroke(1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER);
g2d.setStroke(s);
}

/**
* 功能描述:设置背景色白色
* Param: [g2d]
* Return: void
*/
private static void setColorWhite(Graphics2D g2d){
g2d.setColor(Color.WHITE);
//填充整个屏幕
g2d.fillRect(0,0,600,600);
//设置笔刷
g2d.setColor(Color.BLACK);
}

}

五、图片打印代码示例

package com.hd.modules.print.controller;

import com.hd.common.utils.BHPrintUtil;
import com.hd.common.utils.BarCodeUtils;
import com.hd.common.utils.R;
import com.hd.modules.print.vo.BHExpressLabelVO;
import com.hd.modules.print.vo.ReqBodyVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;

/**
* @author XA
* date 2019/11/13 10:13
* description 打印控制类
* params
* return
*/
@RestController
@RequestMapping("/api/print")
public class BHPrintController {

@Autowired
private BarCodeUtils barCodeUtils;

@Autowired
private BHPrintUtil bhPrintUtil;

@RequestMapping("/expressLabelPrint")
public R expressLabelPrint(@RequestBody(required = false) ReqBodyVO<BHExpressLabelVO> reqBodyVO){
// 图片生成
BHExpressLabelVO bhExpressLabelVO = reqBodyVO.getData();
String[] verifyWords = new String[4];
verifyWords[0] = "唛头:" + bhExpressLabelVO.getShippingMarks();
verifyWords[1] = "线路:" + bhExpressLabelVO.getLine();
verifyWords[2] = "规格:" + bhExpressLabelVO.getSpecs();
verifyWords[3] = "重量:" + bhExpressLabelVO.getWeight() + "KG";
BufferedImage image = null;
try {
image = barCodeUtils.insertWords(barCodeUtils.getBarCode(bhExpressLabelVO.getOrderMainNo()), bhExpressLabelVO.getOrderMainNo(),verifyWords);
} catch (IOException e) {
e.printStackTrace();
}
String imgPath = BarCodeUtils.class.getClassLoader().getResource("statics/print/expressLabel.png").getPath();
try {
ImageIO.write(image, "jpg", new File(imgPath));
} catch (IOException e) {
e.printStackTrace();
}

// 打印
URL url = BarCodeUtils.class.getClassLoader().getResource("statics/print/expressLabel.png");
if(url != null){
String imgFilePath = url.getPath();
bhPrintUtil.printPicture(imgFilePath);
}else{

}
return R.ok().put("data","标签打印成功!");
}

}

六、打印机参数设置(这个视情况而定)




 七、最终效果如下


最新评论:
强的,铁子! 2019-11-14 18:27:54