使用jar包:itext-2.0.1.jar
条形码相关代码:
String strInfo="9009090909"; int barCodeWidth=150; int barCodeHeight=60; int HEIGHT_SPACE = 20; //图片宽度 int imageWidth = barCodeWidth; // 图片高度 int imageHeight = barCodeHeight + HEIGHT_SPACE ; BufferedImage img = new BufferedImage(imageWidth, imageHeight,BufferedImage.TYPE_INT_RGB); Graphics2D g = (Graphics2D) img.getGraphics(); g.fillRect(0, 0, imageWidth, imageHeight); Font font = new java.awt.Font("", java.awt.Font.PLAIN, 12); Barcode128 barcode128 = new Barcode128(); FontRenderContext fontRenderContext = g.getFontRenderContext(); //条形码(文字)的高度 int stringHeight = (int) font.getStringBounds("",fontRenderContext).getHeight(); // 图片横坐标开始位置 int startX = 0; // 图片纵坐标开始位置 int imageStartY = 0; int stringStartY = imageHeight-8;// 条形码(文字)开始位置 int codeWidth = (int) font.getStringBounds(strInfo, fontRenderContext).getWidth(); barcode128.setCode(strInfo); java.awt.Image codeImg = barcode128.createAwtImage(Color.black, Color.white); g.drawImage(codeImg, startX, imageStartY, barCodeWidth, barCodeHeight, Color.white, null); //为图片添加条形码(文字),位置为条形码图片的下部居中 AttributedString ats = new AttributedString(strInfo); ats.addAttribute(TextAttribute.FONT, font, 0, strInfo.length()); AttributedCharacterIterator iter = ats.getIterator(); // 设置条形码(文字)的颜色 g.setColor(Color.BLACK); // 绘制条形码(文字) g.drawString(iter, startX + (barCodeWidth - codeWidth) / 2, stringStartY); g.dispose(); ImageIO.write(img, "PNG",new File("D:\\33333.png"));
二维码相关代码:
String strInfo="9009090909"; BarcodePDF417 barcodePDF417 = new BarcodePDF417(); barcodePDF417.setText(strInfo.getBytes("GBK")); //计算公式为:(17 * codeColumns +3)+18 //得到的这个值,正是二维码图片的宽度 barcodePDF417.setCodeColumns(7); //二维码的内容也就是setText的值,内容越多,高度也会变高 //是一个动态的高 barcodePDF417.setYHeight(2); barcodePDF417.setOptions(BarcodePDF417.PDF417_FIXED_COLUMNS | BarcodePDF417.PDF417_USE_ERROR_LEVEL); java.awt.Image pdfImg = barcodePDF417.createAwtImage(Color.black, Color.white); BufferedImage img = new BufferedImage( pdfImg.getWidth(null),pdfImg.getHeight(null), BufferedImage.TYPE_INT_RGB); Graphics g = img.createGraphics(); g.drawImage(pdfImg, 0, 0, Color.WHITE, null); g.dispose(); ImageIO.write(img, "PNG",new File("D:\\33333.png"));