欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

(019)IText制作条形码

程序员文章站 2024-03-24 12:20:52
...

一、说几句

机关单位的公文条形码生成,统一根据《机关公文二维条码使用规范细则》规范制作。

二、引入工具包

<dependency>
    <groupId>com.lowagie</groupId>
    <artifactId>itext</artifactId>
    <version>2.1.7</version>
</dependency>

三、上代码

1、测试demo

package com.barcode;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.lowagie.text.pdf.BarcodePDF417;
import jj2000.j2k.util.MathUtil;
import org.apache.commons.lang.StringUtils;
import org.json.JSONString;

import javax.imageio.ImageIO;
import javax.imageio.stream.FileImageOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class BarcodeDemo {

    public static void main(String[] args) throws IOException {
        createPdf417();
    }

    private static final String codeString = "GB0626-2005^GD000014001300000871^广东省**单位^通知^粤**函〔2013〕1**号^**单位^***标题^无^无^20131031^^打字室^20131031^^|";

    public static void createPdf417() throws IOException {
        BarcodePDF417 pdf = new BarcodePDF417();
        pdf.setText(codeString.getBytes("GBK"));
        Image pdfImg = pdf.createAwtImage(Color.black, Color.white);
        BufferedImage img = new BufferedImage(pdfImg.getWidth(null), pdfImg.getHeight(null), BufferedImage.TYPE_INT_RGB);
        Graphics g = img.getGraphics();

        g.drawImage(pdfImg, 0, 0, Color.white, null);
//        OutputStream os = new BufferedOutputStream(new FileOutputStream("C:/Users/admin/Desktop/pdf417.bmp"));
//        ImageIO.write(img, "PNG", os);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(img, "PNG", baos);
        byte[] data = baos.toByteArray();
        InputStream is = new ByteArrayInputStream(baos.toByteArray());
        System.out.println("图像输出流:");
        System.out.println(baos.toByteArray());

        byte2image(data, "C:/Users/admin/Desktop/pdf.bmp" );
    }

    //byte数组到图片
    public static void byte2image(byte[] data, String path) {
        if (data.length < 3 || path.equals("")) {return;}
        try {
            FileImageOutputStream imageOutput = new FileImageOutputStream(new File(path));
            imageOutput.write(data, 0, data.length);
            imageOutput.close();
            System.out.println("Make Picture success,Please find image in " + path);
        } catch (Exception ex) {
            System.out.println("Exception: " + ex);
            ex.printStackTrace();
        }
    }
}

2、场景重现

    /**
     * 生成二维条码
     *
     * @param id             文档id
     * @param signSecureTerm 密级后,是否需要标注保密期限 格式例如:绝密30年
     * @return
     */
    @GetMapping("/getDisBarcode")
    public void getDisBarcode(@RequestParam String id, boolean signSecureTerm, HttpServletResponse response) {
        //必须声明图片格式,否则前端无法取到文件流
        response.setContentType("image/png");
        this.disMng.getDisBarcode(id, signSecureTerm,  response);
    }

3、功能实现

    @Override
    public void getDisBarcode(String id, boolean signSecureTerm, String unitName, HttpServletResponse response) {
        String barcodeStr = "GB0626-2005^GD000014001300000871^广东省**单位^通知^粤**函〔2013〕1**号^**单位^***标题^无^无^20131031^^打字室^20131031^^|";

        //2、生成二维条码
        BarcodePDF417 pdf = new BarcodePDF417();
        try {
            pdf.setText(barcodeStr.getBytes("GBK"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw new Exception("UnsupportedEncodingException");
        }
        Image pdfImg = pdf.createAwtImage(Color.black, Color.white);
        BufferedImage img = new BufferedImage(pdfImg.getWidth(null), pdfImg.getHeight(null), BufferedImage.TYPE_INT_RGB);
        Graphics g = img.getGraphics();

        g.drawImage(pdfImg, 0, 0, Color.white, null);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            ImageIO.write(img, "PNG", baos);
        } catch (IOException e) {
            e.printStackTrace();
            throw new Exception("IOException");
        }

        byte[] fileByte = baos.toByteArray();

        // 设置文件名, 图片转为流的形式返回
        try {
            response.addHeader("Content-Disposition",
                    String.format("attachment;filename*=utf-8'zh_cn'%s", URLEncoder.encode("barcode.png", "UTF-8")));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        byte[] buffer = new byte[1024];
        InputStream is = new ByteArrayInputStream(fileByte);
        try (
                BufferedInputStream bis = new BufferedInputStream(is);
                OutputStream os = response.getOutputStream();
        ) {
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

四、参考文章

1、java生成PDF417条码: https://huhongyu.iteye.com/blog/1969400
2、java用Itext生成条形码和二维码:https://wjrko.iteye.com/blog/2256508