Java条形码生成-Barcode4j

背景
目前二维码的应用场景已经遍布各类互联网平台,通常是将产品/商品的唯一编号存储于二维码中以做扫码识别。

而用于生产环境的条形码技术仍然存在,如硬件设备制造、供应、物流运输等等。

在常见的产品信息管理、物料订单系统中,存在多个生成及打印条形码(一维码)的需求场景。

解决方案
Java生成条形码的方案 – barcode4j、zxing

barcode4j

barcode4j开源Java条形码生成库。支持多种编码格式,比如:code-39,code-128等

Welcome to Barcode4J

是由google开源的1D/2D编解码类库。目标是能够对QR编码、Data Matrix、UPC的1D条形码进行解码。 其提供了多种平台下的客户端包括:J2ME、J2SE和Android

本次采用了barcode4j作为解决方案

1.引入pom依赖包

 <dependency>
    <groupId>net.sf.barcode4j</groupId>
    <artifactId>barcode4j-light</artifactId>
    <version>2.0</version>
 </dependency>

2.代码块

import lombok.extern.slf4j.Slf4j;
import org.krysalis.barcode4j.HumanReadablePlacement;
import org.krysalis.barcode4j.impl.AbstractBarcodeBean;
import org.krysalis.barcode4j.impl.codabar.CodabarBean;
import org.krysalis.barcode4j.impl.code128.Code128Bean;
import org.krysalis.barcode4j.impl.code39.Code39Bean;
import org.krysalis.barcode4j.impl.datamatrix.DataMatrixBean;
import org.krysalis.barcode4j.impl.fourstate.RoyalMailCBCBean;
import org.krysalis.barcode4j.impl.fourstate.USPSIntelligentMailBean;
import org.krysalis.barcode4j.impl.int2of5.Interleaved2Of5Bean;
import org.krysalis.barcode4j.impl.pdf417.PDF417Bean;
import org.krysalis.barcode4j.impl.postnet.POSTNETBean;
import org.krysalis.barcode4j.impl.upcean.EAN13Bean;
import org.krysalis.barcode4j.impl.upcean.EAN8Bean;
import org.krysalis.barcode4j.impl.upcean.UPCABean;
import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider;
import org.krysalis.barcode4j.tools.UnitConv;
import org.springframework.util.StringUtils;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;

/**
 * @version 1.0.0
 * @description: 条形码工具类
 * @date 2022/11/24 11:15
 */
@Slf4j
public class BarcodeUtil {
/*                <dependency>
                <groupId>net.sf.barcode4j</groupId>
                <artifactId>barcode4j-light</artifactId>
                  <version>2.0</version>
                      </dependency>*/

    /**
     * 生成code39条形码
     *
     * @param message       要生成的文本
     * @param fontSize      条形码字体大小
     * @param height        条形码的高度
     * @param width         条形码的宽度
     * @param withQuietZone 是否两边留白
     * @param quietZone     withQuietZone为true可用 留白宽度
     * @return
     */
    public static byte[] generateBarCode39(String message, Double fontSize, Double height, Double width, boolean withQuietZone, Double quietZone) {
        if (StringUtils.isEmpty(message)) {
            return null;
        }
        return generateBar(new Code39Bean(), message, fontSize, height, width, withQuietZone, quietZone);
    }

    /**
     * 生成code128条形码
     *
     * @param message       要生成的文本
     * @param fontSize      条形码字体大小
     * @param height        条形码的高度
     * @param width         条形码的宽度
     * @param withQuietZone 是否两边留白
     * @param quietZone     withQuietZone为true可用 留白宽度
     * @return
     */
    public static byte[] generateBarCode128(String message, Double fontSize, Double height, Double width, boolean withQuietZone, Double quietZone) {
        if (StringUtils.isEmpty(message)) {
            return null;
        }
        return generateBar(new Code128Bean(), message, fontSize, height, width, withQuietZone, quietZone);
    }

    /**
     * 生成EAN13条形码
     *
     * @param message       要生成的文本  Valid are 0-9 only length: 11-12
     * @param fontSize      条形码字体大小
     * @param height        条形码的高度
     * @param width         条形码的宽度
     * @param withQuietZone 是否两边留白
     * @param quietZone     withQuietZone为true可用 留白宽度
     * @return
     */
    public static byte[] generateBarEAN13(String message, Double fontSize, Double height, Double width, boolean withQuietZone, Double quietZone) {
        if (StringUtils.isEmpty(message)) {
            return null;
        }
        return generateBar(new EAN13Bean(), message, fontSize, height, width, withQuietZone, quietZone);
    }

    /**
     * 生成EAN8条形码
     *
     * @param message       要生成的文本 Valid are 0-9 only length: 7-8
     * @param fontSize      条形码字体大小
     * @param height        条形码的高度
     * @param width         条形码的宽度
     * @param withQuietZone 是否两边留白
     * @param quietZone     withQuietZone为true可用 留白宽度
     * @return
     */
    public static byte[] generateBarEAN8(String message, Double fontSize, Double height, Double width, boolean withQuietZone, Double quietZone) {
        if (StringUtils.isEmpty(message)) {
            return null;
        }
        return generateBar(new EAN8Bean(), message, fontSize, height, width, withQuietZone, quietZone);
    }

    /**
     * 生成Codabar条形码
     *
     * @param message       要生成的文本 Valid are 0-9 and a-e
     * @param fontSize      条形码字体大小
     * @param height        条形码的高度
     * @param width         条形码的宽度
     * @param withQuietZone 是否两边留白
     * @param quietZone     withQuietZone为true可用 留白宽度
     * @return
     */
    public static byte[] generateBarCodabar(String message, Double fontSize, Double height, Double width, boolean withQuietZone, Double quietZone) {
        if (StringUtils.isEmpty(message)) {
            return null;
        }
        return generateBar(new CodabarBean(), message, fontSize, height, width, withQuietZone, quietZone);
    }

    /**
     * 生成UPCA条形码
     *
     * @param message       要生成的文本 Valid are 0-9 lenth:11-12
     * @param fontSize      条形码字体大小
     * @param height        条形码的高度
     * @param width         条形码的宽度
     * @param withQuietZone 是否两边留白
     * @param quietZone     withQuietZone为true可用 留白宽度
     * @return
     */
    public static byte[] generateBarUPCA(String message, Double fontSize, Double height, Double width, boolean withQuietZone, Double quietZone) {
        if (StringUtils.isEmpty(message)) {
            return null;
        }
        return generateBar(new UPCABean(), message, fontSize, height, width, withQuietZone, quietZone);
    }

    /**
     * 生成POSTNET条形码
     *
     * @param message       要生成的文本 Valid are 0-9
     * @param fontSize      条形码字体大小
     * @param height        条形码的高度
     * @param width         条形码的宽度
     * @param withQuietZone 是否两边留白
     * @param quietZone     withQuietZone为true可用 留白宽度
     * @return
     */
    public static byte[] generateBarPOSTNET(String message, Double fontSize, Double height, Double width, boolean withQuietZone, Double quietZone) {
        if (StringUtils.isEmpty(message)) {
            return null;
        }
        return generateBar(new POSTNETBean(), message, fontSize, height, width, withQuietZone, quietZone);
    }

    /**
     * 生成RoyalMailCBC条形码
     *
     * @param message       要生成的文本 Valid are 0-9
     * @param fontSize      条形码字体大小
     * @param height        条形码的高度
     * @param width         条形码的宽度
     * @param withQuietZone 是否两边留白
     * @param quietZone     withQuietZone为true可用 留白宽度
     * @return
     */
    public static byte[] generateBarRoyalMailCBC(String message, Double fontSize, Double height, Double width, boolean withQuietZone, Double quietZone) {
        if (StringUtils.isEmpty(message)) {
            return null;
        }
        return generateBar(new RoyalMailCBCBean(), message, fontSize, height, width, withQuietZone, quietZone);
    }

    /**
     * 生成USPSIntelligentMail条形码
     *
     * @param message       要生成的文本 Valid are 0-9 length:20
     * @param fontSize      条形码字体大小
     * @param height        条形码的高度
     * @param width         条形码的宽度
     * @param withQuietZone 是否两边留白
     * @param quietZone     withQuietZone为true可用 留白宽度
     * @return
     */
    public static byte[] generateBarUSPSIntelligentMail(String message, Double fontSize, Double height, Double width, boolean withQuietZone, Double quietZone) {
        if (StringUtils.isEmpty(message)) {
            return null;
        }
        return generateBar(new USPSIntelligentMailBean(), message, fontSize, height, width, withQuietZone, quietZone);
    }

    /**
     * 生成PDF417条形码
     *
     * @param message       要生成的文本 Valid are 0-9 length:20
     * @param fontSize      条形码字体大小
     * @param height        条形码的高度
     * @param width         条形码的宽度
     * @param withQuietZone 是否两边留白
     * @param quietZone     withQuietZone为true可用 留白宽度
     * @return
     */
    public static byte[] generateBarPDF417(String message, Double fontSize, Double height, Double width, boolean withQuietZone, Double quietZone) {
        if (StringUtils.isEmpty(message)) {
            return null;
        }
        return generateBar(new PDF417Bean(), message, fontSize, height, width, withQuietZone, quietZone);
    }

    /**
     * 生成DataMatrix条形码
     *
     * @param message       要生成的文本 Valid are 0-9 length:20
     * @param fontSize      条形码字体大小
     * @param height        条形码的高度
     * @param width         条形码的宽度
     * @param withQuietZone 是否两边留白
     * @param quietZone     withQuietZone为true可用 留白宽度
     * @return
     */
    public static byte[] generateBarDataMatrix(String message, Double fontSize, Double height, Double width, boolean withQuietZone, Double quietZone) {
        if (StringUtils.isEmpty(message)) {
            return null;
        }
        return generateBar(new DataMatrixBean(), message, fontSize, height, width, withQuietZone, quietZone);
    }

    /**
     * 生成Interleaved2Of5条形码
     *
     * @param message       要生成的文本 Valid are 0-9
     * @param fontSize      条形码字体大小
     * @param height        条形码的高度
     * @param width         条形码的宽度
     * @param withQuietZone 是否两边留白
     * @param quietZone     withQuietZone为true可用 留白宽度
     * @return
     */
    public static byte[] generateBarInterleaved2Of5(String message, Double fontSize, Double height, Double width, boolean withQuietZone, Double quietZone) {
        if (StringUtils.isEmpty(message)) {
            return null;
        }
        return generateBar(new Interleaved2Of5Bean(), message, fontSize, height, width, withQuietZone, quietZone);
    }

    /**
     * 生成条形码
     *
     * @param bean          条形码类型
     * @param message       要生成的文本
     * @param fontSize      条形码字体大小
     * @param height        条形码的高度
     * @param width         条形码的宽度
     * @param withQuietZone 是否两边留白
     * @param quietZone     withQuietZone为true可用 留白宽度
     * @return
     */
    private static byte[] generateBar(AbstractBarcodeBean bean, String message, Double fontSize, Double height, Double width, boolean withQuietZone, Double quietZone) {

        // 条码数据显示位置
        bean.setMsgPosition(HumanReadablePlacement.HRP_BOTTOM);

        if (fontSize != null) {
            bean.setFontSize(fontSize);
        } else {
            bean.setFontSize(5);
        }
        // 两端留白宽度
        if (quietZone != null) {
            bean.setQuietZone(quietZone);
        }

        // 精细度
        final int dpi = 256;

        // 设置条码每一条的宽度
        // UnitConv 是barcode4j 提供的单位转换的实体类,用于毫米mm,像素px,英寸in,点pt之间的转换
        // 设置条形码高度和宽度
        if (height != null) {
            bean.setBarHeight(height);
        } else {
            bean.setBarHeight(20);
        }
        if (width != null) {
            bean.setModuleWidth(UnitConv.in2mm(width / dpi));
        } else {
            bean.setModuleWidth(UnitConv.in2mm(5.0f / dpi));
        }

        // 设置两侧是否留白
        bean.doQuietZone(withQuietZone);

        String format = "image/png";
        ByteArrayOutputStream ous = null;
        byte[] imageByte;
        try {
            ous = new ByteArrayOutputStream();
            // 输出到流
            BitmapCanvasProvider canvas = new BitmapCanvasProvider(ous, format, dpi,
                    BufferedImage.TYPE_BYTE_BINARY, false, 0);
            // 生成条形码
            bean.generateBarcode(canvas, message);
            // 结束绘制
            canvas.finish();
            imageByte = ous.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (null != ous) {
                    ous.close();
                }
            } catch (Exception e) {
                log.error("ByteArrayOutputStream流关闭失败,失败原因为:{{}}", e.getMessage());
            }
        }
        return imageByte;
    }

    public static void main(String[] args) {

        byte[] bytes = generateBarDataMatrix("123312", null, null, null, true, null);
        // byte[]转base64
        String base64Str = Base64.getEncoder().encodeToString(bytes);
        System.out.println(base64Str);
    }
}

参考地址
条形码的各种编码格式
在这里插入图片描述

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
生成条形码可以使用一些开源的 Java 库,比如ZXing,可以通过以下步骤进行条形码生成: 1. 引入 ZXing 库 在 `pom.xml` 文件中加入以下依赖: ```xml <dependency> <groupId>com.google.zxing</groupId> <artifactId>core</artifactId> <version>3.4.0</version> </dependency> <dependency> <groupId>com.google.zxing</groupId> <artifactId>javase</artifactId> <version>3.4.0</version> </dependency> ``` 2. 生成条形码 ```java import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.MultiFormatWriter; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix; public class BarcodeGenerator { private static final int BLACK = 0xFF000000; private static final int WHITE = 0xFFFFFFFF; public static void main(String[] args) { String contents = "1234567890"; // 条形码内容 int width = 300; // 条形码宽度 int height = 100; // 条形码高度 String format = "png"; // 条形码格式 // 设置条形码参数 // 可以设置编码方式,错误纠正等级,边距等参数 MultiFormatWriter writer = new MultiFormatWriter(); EncodeHintType hintType = EncodeHintType.ERROR_CORRECTION; BitMatrix bitMatrix = null; try { bitMatrix = writer.encode(contents, BarcodeFormat.CODE_128, width, height); } catch (WriterException e) { e.printStackTrace(); } // 生成条形码图片 BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { image.setRGB(x, y, bitMatrix.get(x, y) ? BLACK : WHITE); } } // 保存条形码图片 File outputFile = new File("barcode.png"); try { ImageIO.write(image, format, outputFile); } catch (IOException e) { e.printStackTrace(); } } } ``` 3. 打印条形码 可以使用 Java 提供的 `PrintService` 和 `PrinterJob` 类进行打印。 ```java import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.print.PageFormat; import java.awt.print.Printable; import java.awt.print.PrinterException; import java.awt.print.PrinterJob; import javax.print.PrintService; import javax.print.PrintServiceLookup; public class BarcodePrinter implements Printable { private BufferedImage image; public BarcodePrinter(BufferedImage image) { this.image = image; } @Override public int print(Graphics g, PageFormat pf, int pageIndex) throws PrinterException { if (pageIndex != 0) { return NO_SUCH_PAGE; } Graphics2D g2d = (Graphics2D) g; g2d.translate(pf.getImageableX(), pf.getImageableY()); g2d.drawImage(image, 0, 0, null); return PAGE_EXISTS; } public static void main(String[] args) { BufferedImage image = null; // 条形码图片 try { image = ImageIO.read(new File("barcode.png")); } catch (IOException e) { e.printStackTrace(); } PrinterJob job = PrinterJob.getPrinterJob(); PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null); if (services.length > 0) { job.setPrintService(services[0]); } job.setPrintable(new BarcodePrinter(image)); try { job.print(); } catch (PrinterException e) { e.printStackTrace(); } } } ``` 注意:打印机需要连接到计算机,并且需要设置为默认打印机。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值