Java生成条形码并在浏览器下载

直接上代码:
1.controller
@GetMapping("/barCode")
@ResponseBody
public void barCode(HttpServletRequest request, HttpServletResponse response, String codeNo) {
String filePath = "D:\qrCode\barCode" + System.currentTimeMillis() + ".png";
BarcodeUtils.generateFile(codeNo, filePath);
TestUtil.download(request, response, filePath);
}

2.工具类BarcodeUtils
package com.ruoyi.kaigemj.utils;

import org.krysalis.barcode4j.HumanReadablePlacement;
import org.krysalis.barcode4j.impl.code128.Code128Bean;
import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider;

import java.awt.image.BufferedImage;
import java.io.*;

public class BarcodeUtils {
/**
* 生成条形码文件
*
* @param msg 条形码的文本内容
* @param path 生成条形码的文件路径
* @return
*/
public static File generateFile(String msg, String path) {
File file = new File(path);
OutputStream outputStream = null;
try {
outputStream = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
generateBarCode128(msg, 10.0, 0.3, true, false, outputStream);
} catch (Exception e) {
throw new RuntimeException(e);
}
return file;
}

/**
 * 生成code128条形码
 *
 * @param message       要生成的文本
 * @param height        条形码的高度
 * @param width         条形码的宽度
 * @param withQuietZone 是否两边留白
 * @param hideText      隐藏可读文本
 * @param outputStream  输出流
 */
public static void generateBarCode128(String message, Double height, Double width, boolean withQuietZone, boolean hideText, OutputStream outputStream) {
    Code128Bean bean = new Code128Bean();

    // 分辨率,越大条形码就越大
    int dpi = 150;

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

    // 设置条形码高度和宽度
    bean.setBarHeight(height);
    if (width != null) {
        bean.setModuleWidth(width);
    }
    // 设置文本位置(包括是否显示)
    if (hideText) {
        bean.setMsgPosition(HumanReadablePlacement.HRP_NONE);
    }
    // 设置图片类型
    String format = "image/png";
    BitmapCanvasProvider canvas = new BitmapCanvasProvider(outputStream, format, dpi,
            BufferedImage.TYPE_BYTE_BINARY, false, 0);

    /* 生产条形码 */
    bean.generateBarcode(canvas, message);
    try {
        canvas.finish();
    } catch (IOException e) {
        //ByteArrayOutputStream won't happen
    }
}

/*public static void main(String[] args) {
    String msg = "20220602ZXY";
    //生成条形码路径
    String path = "D:\\qrCode\\barcode1.png";
    generateFile(msg, path);
}*/

}

3.工具类TestUtil
package com.ruoyi.kaigemj.utils;

    import javax.servlet.http.HttpServletRequest;

    import javax.servlet.http.HttpServletResponse;

    import java.io.File;

    import java.io.FileInputStream;

    import java.io.IOException;

    import java.io.InputStream;

    import java.net.URLEncoder;

public class TestUtil {

/*

根据文件所在路径下载文件

*/

public static void download(HttpServletRequest request, HttpServletResponse response, String filePath){

    File file = new File(filePath);

// 取得文件名。

    String fileName = file.getName();

    InputStream fis = null;

    try {

        fis = new FileInputStream(file);

        request.setCharacterEncoding("UTF-8");

        String agent = request.getHeader("User-Agent").toUpperCase();

        if ((agent.indexOf("MSIE") > 0) || ((agent.indexOf("RV") != -1) && (agent.indexOf("FIREFOX") == -1)))

            fileName = URLEncoder.encode(fileName, "UTF-8");

        else {

            fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");

        }

        response.reset();

        response.setCharacterEncoding("UTF-8");

        response.setContentType("application/force-download");// 设置强制下载不打开

        response.addHeader("Content-Disposition", "attachment;filename=" + fileName);

        response.setHeader("Content-Length", String.valueOf(file.length()));

        byte[] b = new byte[1024];

        int len;

        while ((len = fis.read(b)) != -1) {

            response.getOutputStream().write(b, 0, len);

        }

        response.flushBuffer();

        fis.close();

    }catch (IOException e) {

        throw new RuntimeException(e);

    }

}

}

如果这篇文章有幸帮到了您,您有空的话可以点个关注或者推荐,谢谢了。

posted @ 2023-01-06 16:54  曾曾曾zzq  阅读(94)  评论(0)    收藏  举报