官方的demo中有條形碼的工具,但是生成出來的樣式不好調整,這裏還是放出官方的demo地址,大家可以test試試:https://itextpdf.com/en/resources/examples/itext-5-legacy/generating-and-displaying-bar-codes
怎麼使用我們自己生成的條形碼呢?
安裝依賴
<properties>
<zxing.version>3.3.3</zxing.version>
</properties>
<!-- google zxing 多格式1D / 2D條碼圖像處理庫-->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>${zxing.version}</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>${zxing.version}</version>
</dependency>
封裝工具:
public class BarCodeUtil {
/**
* 獲取base64格式條形碼
* @param contents
* @return
* @throws WriterException
* @throws IOException
*/
public static String getBase64Encode(String contents) throws WriterException, IOException {
return new String("data:image/jpeg;base64,"+Base64.encode(getBytes(contents)));
}
/**
* 獲取字節碼
* @param contents
* @return
* @throws WriterException
* @throws IOException
*/
public static byte[] getBytes(String contents) throws WriterException, IOException {
BufferedImage bufferedImage = encode(contents);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ImageIO.write(bufferedImage,"jpeg",outputStream);
outputStream.close();
return outputStream.toByteArray();
}
/**
* 生成條形碼
* @param contents 內容
* @return
*/
public static BufferedImage encode(String contents) throws WriterException {
//配置參數
Map<EncodeHintType,Object> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
// 容錯級別 這裏選擇最高H級別
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
//設置條碼邊距 默認爲10
hints.put(EncodeHintType.MARGIN, 0);
//寬度爲條碼自動生成規則的寬度
int width = new Code128Writer().encode(contents).length;
//高度可由前端控制 不影響編碼識別
int height = 70;
//條碼放大倍數
int codeMultiples = 1;
//條碼內容寬度
int codeWidth = width * codeMultiples;
// 參數分別爲 編碼內容,編碼類型,內容寬度,內容高度,設置參數
BitMatrix bitMatrix = new MultiFormatWriter().encode(contents,
BarcodeFormat.CODE_128, codeWidth, height, hints);
return MatrixToImageWriter.toBufferedImage(bitMatrix);
}
/**
* 解析條形碼
* @param inputStream
* @return
*/
public static String decode(InputStream inputStream) {
BufferedImage image = null;
Result result = null;
try {
image = ImageIO.read(inputStream);
if (image == null) {
throw new RuntimeException("the decode image may be not exists.");
}
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
result = new MultiFormatReader().decode(bitmap, null);
return result.getText();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
在Itext5中根據數據生成對應條形碼,這樣生成條形碼的時候,調整起來方便很多
// 條形碼
Image barCodeImg = Image.getInstance(BarCodeUtil.getBytes(no));
barCodeImg.scaleAbsolute(120, 40);
cell = new PdfPCell(barCodeImg, false);