用iText可导出条形码图片,但在图片中是不包含条形码的,只有在PDF中才有createImageWithBarcode这个方法,下面的代码是对导出的图片进行处理,将条形码加入到图片中,具体代码如下:
- private static final int HEIGHT_SPACE = 20;// 图片之间的间隔
-
- public static void main(String[] args) throws Exception {
- List<String> codeList = new ArrayList<String>();
- codeList.add("ABCD124645765");
- codeList.add("ABCD12-4645-765");
- codeList.add("ABCD12464-5765");
- codeList.add("AB-CD1-246457-65");
- createBarcodeImage(200, 100, codeList);
- System.out.println("The image is created.");
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
- */
- public static void createBarcodeImage(int barCodeWidth, int barCodeHeight,
- List<String> codeList) throws Exception {
-
- Assert.assertTrue("The list can not empty.", codeList.size() > 0);
-
- int imageWidth = (barCodeWidth + barCodeWidth / 2) * codeList.size() + barCodeWidth / 2;
-
- int imageHeight = barCodeHeight + HEIGHT_SPACE * 2;
- 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 = barCodeWidth / 2;
-
- int imageStartY = (imageHeight - barCodeHeight - stringHeight) / 2;
- int stringStartY = imageStartY * 2 + barCodeHeight;
- for (String code : codeList) {
- int codeWidth = (int) font.getStringBounds(code, fontRenderContext).getWidth();
- barcode128.setCode(code);
- Image codeImg = barcode128.createAwtImage(Color.black, Color.white);
- g.drawImage(codeImg, startX, imageStartY, barCodeWidth, barCodeHeight, Color.white, null);
-
- AttributedString ats = new AttributedString(code);
- ats.addAttribute(TextAttribute.FONT, font, 0, code.length());
- AttributedCharacterIterator iter = ats.getIterator();
-
- g.setColor(Color.BLUE);
-
- g.drawString(iter, startX + (barCodeWidth - codeWidth) / 2, stringStartY);
-
- startX = startX + barCodeWidth / 2 + barCodeWidth;
- }
- g.dispose();
- OutputStream os = new BufferedOutputStream(new FileOutputStream("/home/admin/codeList.png"));
- ImageIO.write(img, "PNG", os);
- }
(责任编辑:admin) |