1.環境:eclipse+jdk1.7+tomcat6.0
2.jar:使用谷歌的baCodejar(可以自己下載)
3.開發詳細代碼如下:
實現的代碼:
/**
*
*/
package com.wisco.ty.comm;
import java.io.File;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.m6.base.BaseBO;
import org.m6.exception.AppException;
import org.springframework.stereotype.Component;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.wisco.framework.utils.AppUtils;
/**
* 二維碼生成
* @file TyjcComm05BO.java
* @author 姓名</a>
* @date 2014-11-19下午1:55:47
* @version 1.0
*/
@Component("tyjcComm05BO")
public class TyjcComm05BO extends BaseBO {
public final static String CLASS_VERSION = "$Id: TyjcComm05.java,v 1.0 2014-10-20,下午02:03:14 $";
/**生成二維碼
* @param infoMap
* @return
*/
public File getTdCode(Map<String, Object> infoMap){
String str = getInfoMapToString(infoMap);
String timestamp = "" + System.currentTimeMillis();
String path = AppUtils.getErpPropertyValueByKey("ERP_HOME","")+"/public/barCode";
//String path = "public/barCode";
createDir(path);
String fileName = timestamp + ".png";
path += "/" + fileName;
File outputFile = new File(path.toString());
Map<EncodeHintType, Object> hints = new TreeMap<EncodeHintType, Object>();
// 指定糾錯等級
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
// 指定編碼格式
hints.put(EncodeHintType.CHARACTER_SET, "GBK");
// 設置邊框 0 條碼周圍不留空白邊框
hints.put(EncodeHintType.MARGIN, 0);
try {
BitMatrix bitMatrix = new MultiFormatWriter().encode(str,
BarcodeFormat.QR_CODE, 100, 100, hints);//QR_CODE DATA_MATRIX
MatrixToImageWriter.writeToFile(bitMatrix, "png", outputFile);
} catch (Exception e) {
throw new AppException("生成二維碼失敗!");
}
return outputFile;
}
/**解析infoMap,將map的key與value連接,格式如 key1:value1 | key2:value2。
* @param infoMap
* @return
*/
public String getInfoMapToString(Map<String, Object> infoMap){
String str = "";
Set<String> keySet = infoMap.keySet();
for(Iterator<String> it=keySet.iterator();it.hasNext();){
String key = it.next();
str += key + ":";
String value = (String)infoMap.get(key);
str += value + "|";
}
str = str.substring(0,str.length()-1);
return str;
}
/**
* 創建二維碼的輸出目錄
* */
private void createDir(String path) {
File dir = new File(path);
if (!dir.exists()) {
if (!dir.mkdirs()) {
throw new AppException("tyjcComm05BO.createDir(" + path
+ "),創建目錄失敗...");
}
}
}
}
在birt中調用相應的方法,把二維碼打印出來,因爲birt不方便把代碼copy,所以附上照
1.添加一個image的控件,設置屬性值中的Event Handle爲生產二維碼文件的路徑
2.設置屬性之中的binding爲具體業務的方法,綁定二維碼掃描結果的值
2.實際打印出來的二維碼