1. 程式人生 > >JBarcode生成條形碼(帶漢字)

JBarcode生成條形碼(帶漢字)

 JBarcode生成條形碼(帶漢字);請注意Maven裡面現在沒有這個jar報的依賴,需要自己下載,並手動匯入Maven


import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.jbarcode.JBarcode;
import org.jbarcode.JBarcodeFactory;
import org.jbarcode.encode.Code128Encoder;
import org.jbarcode.encode.InvalidAtributeException;
import org.jbarcode.paint.TextPainter;
import org.jbarcode.util.ImageUtil;

public class JBarcodeUtil {
	
	// 設定條形碼高度
	private static final int BARCODE_HEIGHT = 50;
	// 設定條形碼預設解析度
	//private static final int BARCODE_DPI = ImageUtil.DEFAULT_DPI;
	private static final int BARCODE_DPI = ImageUtil.DEFAULT_DPI;
	// 設定條形碼字型樣式
	//private static final String FONT_FAMILY = "微軟雅黑";
	//private static final String FONT_FAMILY = "STXihei";
	private static final String FONT_FAMILY = "Microsoft YaHei";
	// 設定條形碼字型大小
	private static final int FONT_SIZE = 14;
	// 設定條形碼文字
	/*public static String TEXTONE = "";
	public static String TEXTTWO = "";
	public static String TEXTTHREE = "";*/
	public static String TEXT = "";
	// 建立jbarcode
	private static JBarcode jbc = null;

	/**
	 * 1.靜態程式碼塊的作用:當類被載入時,靜態程式碼塊被執行,且只被執行一次,靜態塊常用來執行類屬性的初始化。  
     * 2.常量條形碼的高度和字型大小設定很重要,若是設定小了會看不到設定的檔案 
	 * @return
	 * @throws InvalidAtributeException
	 */
	static JBarcode getJBarcode() throws InvalidAtributeException {
		/**
		 * 參考設定樣式:
		 * barcode.setEncoder(Code128Encoder.getInstance()); //設定編碼
		 * barcode.setPainter(WidthCodedPainter.getInstance());// 設定Painter
		 * barcode.setTextPainter(BaseLineTextPainter.getInstance()); //設定TextPainter
		 * barcode.setBarHeight(17); //設定高度
		 * barcode.setWideRatio(Double.valueOf(30).doubleValue());// 設定寬度比率
		 * barcode.setXDimension(Double.valueOf(2).doubleValue()); // 設定尺寸,大小 密集程度
		 * barcode.setShowText(true); //是否顯示文字 
		 * barcode.setCheckDigit(true); //是否檢查數字
		 * barcode.setShowCheckDigit(false); //是否顯示檢查數字
		 */
		if (jbc == null) {
			// 	生成code128
			jbc = JBarcodeFactory.getInstance().createCode128();
			jbc.setEncoder(Code128Encoder.getInstance());
			//	設定TextPainter
			jbc.setTextPainter(CustomTextPainter.getInstance());
			//	設定設定條形碼高度
			jbc.setBarHeight(BARCODE_HEIGHT);
			//	設定尺寸,大小 密集程度
			jbc.setXDimension(Double.valueOf(0.8).doubleValue());
			//	是否顯示文字 
			jbc.setShowText(true);
		}
		return jbc;
	}

	/**
	 * @descript:		生成條形碼檔案(呼叫此方法進行生成工作)
	 * @param message	顯示的文字內容
	 * @param file		生成檔案地址
	 * @param content	條形碼內容
	 * @return 
	 */
	public static String createBarcode(String message, File file, String content) {
		try {
			FileOutputStream fos = new FileOutputStream(file);
			createBarcode(message, fos, content);
			fos.close();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		return "scuccs";
	}

	/**
	 * @descript:		生成條形碼並寫入指定輸出流
	 * @param message	條形碼內容
	 * @param os		輸出流
	 * @param text		文字內容
	 */
	private static void createBarcode(String message, OutputStream os, String text) {
		try {
			/*String[]  strs = text.split("-");
			// 設定條形碼文字
			switch(strs.length){
			case 1:
				TEXTONE = strs[0].toString();
				TEXTTWO = "";
				TEXTTHREE = "";
			    break;
			case 2:
				TEXTONE = strs[0].toString();
				TEXTTWO = strs[1].toString();
				TEXTTHREE = "";
			    break;
			default:
				TEXTONE = strs[0].toString();
				TEXTTWO = strs[1].toString();
				TEXTTHREE = strs[2].toString();
			    break;
			}*/
			int lenght = message.length();
			String zero = "";
			for (int i = lenght; i < 7; i++) {
				zero += "0";
			}
			message = zero + message;
			
			TEXT = text;
			// 建立條形碼的BufferedImage影象
			BufferedImage image = getJBarcode().createBarcode(message);
			/*int a = image.getWidth();
			int b = image.getHeight();
			System.out.println("生成的圖片:寬為"+a+"、高為"+b);*/
			
			ImageUtil.encodeAndWrite(image, ImageUtil.PNG, os, BARCODE_DPI, BARCODE_DPI);
			os.flush();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 靜態內部類 自定義的 TextPainter, 允許定義字型,大小,文字等
	 * 參考底層實現:BaseLineTextPainter.getInstance()
	 */
	private static class CustomTextPainter implements TextPainter {
		private static CustomTextPainter instance = new CustomTextPainter();

		public static CustomTextPainter getInstance() {
			return instance;
		}

		public void paintText(BufferedImage barCodeImage, String text, int width) {
			// 繪圖
			Graphics g2d = barCodeImage.getGraphics();
			// 建立字型
			Font font = new Font(FONT_FAMILY, Font.PLAIN, FONT_SIZE * width);
			g2d.setFont(font);
			//g2d.drawRect(0, 0, 500, 500);
			FontMetrics fm = g2d.getFontMetrics();
			//	高度
			int height = fm.getHeight();
			//	中心	這裡的text是指的條形碼數字
			int center = (barCodeImage.getWidth() - fm.stringWidth(text)) / 2 + 10;
			
			/*int a = (barCodeImage.getWidth() - fm.stringWidth(TEXTONE)) / 2;
			int b = (barCodeImage.getWidth() - fm.stringWidth(TEXTTWO)) / 2;
			int c = (barCodeImage.getWidth() - fm.stringWidth(TEXTTHREE)) / 2;*/
			int d = (barCodeImage.getWidth() - fm.stringWidth(TEXT)) / 2;
			
			//	條形內容上下的顏色
			g2d.setColor(Color.WHITE);
			//	條形碼-----碼的上部
			//g2d.fillRect(0, 0, barCodeImage.getWidth(), barCodeImage.getHeight() * 1 / 20);
			g2d.fillRect(0, 0, barCodeImage.getWidth(), barCodeImage.getHeight() * 7 / 20);
			
			//	條形碼-----碼的底部
			g2d.fillRect(0, barCodeImage.getHeight() - (height * 9 / 10), barCodeImage.getWidth(), (height * 9 / 10));
			
			//	顯示的字型顏色(包括條形碼下方的數字)
			g2d.setColor(Color.BLACK);
			// 	繪製文字
			/*g2d.drawString(TEXTONE, a, 145);
			g2d.drawString(TEXTTWO, b, 170);
			g2d.drawString(TEXTTHREE, c, 195);*/
			g2d.drawString(TEXT, d, 30);
			//	繪製安保或者涉案字樣
			g2d.drawString("SA", 16, 55);
			// 繪製條形碼的數字內容
			//g2d.drawString(text, center, barCodeImage.getHeight() - (height / 10) - 2);//在最下面
			g2d.drawString(text, center, 55);//在中間
		}
	}
	
	public static void main(String[] args) {
		BlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(50);
		ThreadPoolExecutor executor = new ThreadPoolExecutor(8, 8, 1, TimeUnit.DAYS, queue);
		Long data = new Date().getTime();
		String datas = data.toString();
		List<File> fileList = new ArrayList<File>();
		// 存放地址
		File newImagepath = new File("d:/" + datas + ".jpg");
		fileList.add(newImagepath);
		// 生成條形碼的內容
		String content = "6";
		// 顯示在條形碼上的文字
		String text = "第04箱";
		try {
			if (executor.getQueue().size() > 30) {
				Thread.sleep(200);
			}
			// 生成條形碼的方法
			MultithreadForBarCod barCode = new MultithreadForBarCod();
			barCode.setMessage(content);
			barCode.setFile(newImagepath);
			barCode.setText(text);

			executor.execute(barCode);
			Thread.sleep(20);
		} catch (Exception e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
			try {
				Thread.sleep(500);
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}
		}
		executor.shutdown();
	}
	
}