最近在项目中遇到一个条形码打印的功能,
经过以往项目经验的分析,首先想到的就是通过图片打印条形码,那么条形码如何生成是一个问题,
通过在网上查找资料了解到,可以通过JBarcode生成条形码:
以下整理了下生成条形码图片,应用图片生成pdf的代码:
//获取配置文件中条形码保存的路径
String basepath = ReadProperties.getString("batch_upfile_path");
//条形码图片保存路径全路径
String path = session.getServletContext().getRealPath(basepath);
String barcode="201712345678";//条码
String barcodePath = "pdffile/tidy/barcode/";
String barcodeFileName = "1.jpg"; //图片名称
String filePath = path+barcodePath;
//生成条形码图片
File file = new File(filePath);
if (!file.exists()) {
file.mkdirs();
}
JBarcode localJBarcode = new JBarcode(Code128Encoder.getInstance(), WidthCodedPainter.getInstance(), BaseLineTextPainter.getInstance());
localJBarcode.setShowText(true);
localJBarcode.setBarHeight(12.5);
localJBarcode.setXDimension(0.4);
BufferedImage image1 = localJBarcode.createBarcode(barcode);
FileOutputStream fos = new FileOutputStream(new File(filePath, barcodeFileName));
ImageUtil.encodeAndWrite(image1, "jpeg", fos, 300, 300);
fos.close();
//生成pdf
String pdfFileName = "2.pdf";
com.lowagie.text.Document doc = new com.lowagie.text.Document();
String target = filePath + pdfFileName;
String imagePath =filePath+barcodeFileName;
Image image = Image.getInstance(imagePath);
Rectangle r = new Rectangle(image.getWidth(), image.getHeight());
doc.setPageSize(r);
image.setAbsolutePosition(0, 0);
PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(target));
doc.open();
doc.add(image);
doc.close();
此部分代码需要依赖两个jar包,jbarcode-0.2.8.jar(下载地址:http://download.csdn.net/download/haidong9900/9938111)
、iText-2.0.8.jar(下载地址:http://download.csdn.net/download/haidong9900/9938118)
这两个jar包可以