標籤:direct des desktop redirect com ima tput lin cep
1、將要使用到的jar包匯入項目(1、commons-lang-2.3.jar 2、barcode4j-light-2.0.jar)
2、建立類 BarcodeUtil
3、代碼部分
package com.sale.util;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.commons.lang.StringUtils;
import org.krysalis.barcode4j.impl.code128.Code128Bean;
import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider;
import org.krysalis.barcode4j.tools.UnitConv;
/**
*
* @author Saffi
* @date 2017年10月6日
*/
public class BarcodeUtil {
/**
* 組建檔案
*
* @param msg
* @param path
* @return
*/
public File generateFiles(String msg, String path) {
File file = new File(path);
try {
generates(msg, new FileOutputStream(file));
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
return file;
}
/**
* 產生位元組
*
* @param msg
* @return
* @throws IOException
*/
public byte[] generates(String msg) throws IOException {
ByteArrayOutputStream ous = new ByteArrayOutputStream();
generates(msg, ous);
ous.close();
return ous.toByteArray();
}
/**
* 產生到流
*
* @param msg
* @param ous
*/
public static void generates(String msg, OutputStream ous) {
if (StringUtils.isEmpty(msg) || ous == null) {
return;
}
// 條碼類型
//Code39Bean bean = new Code39Bean();
Code128Bean bean = new Code128Bean();
// 精細度
final int dpi = 150;
// module寬度
final double moduleWidth = UnitConv.in2mm(2.0f / dpi);
// 設定物件
bean.setModuleWidth(moduleWidth);
bean.doQuietZone(false);
String format = "image/png";
try {
// 輸出到流
BitmapCanvasProvider canvas = new BitmapCanvasProvider(ous, format, dpi, BufferedImage.TYPE_BYTE_BINARY,
false, 0);
// 產生條碼
bean.generateBarcode(canvas, msg);
// 結束繪製
canvas.finish();
ous.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
4、調用介面
/**
* 產生條碼
* @author Saffi
* @throws IOException
*/
@RequestMapping("testOrderBarcodes.action")
public @ResponseBody String testOrderBarcodes(HttpServletResponse respon) throws IOException {
String result="error";
try {
//調用介面
BarcodeUtil util = new BarcodeUtil();
//條碼內容
String msg = ‘Te123456‘;
//路徑
String path ="C:/Users/Administrator/Desktop/barcode/barcode"+msg+".png";
util.generateFiles(msg, path);
result="succ";
} catch (Exception e) {
e.printStackTrace();
respon.sendRedirect("error.action");
log.error("系統錯誤", e.fillInStackTrace());
}
return result;
}
Java使用barcode4j產生條碼