有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java有可能获得带有文本的条形码的awt图像吗

是否可以扩展条形码类型的createAwtImage以提供与createImageWithBarcode相同的输出(即,包括下面的文本),以便可以将其直接写入图像而不是PDF

目前,我不得不使用barcode4j来实现这一点,但我更喜欢使用iText。或者我可以用java.awt.Image,在底部添加一些额外的空间,并在这个额外的空间中添加文本。我该怎么做

编辑: groovy代码来实现这一点

 img = barcode.createAwtImage(Color.BLACK, Color.WHITE)
 int w = barcode.getBarcodeSize().getWidth()*3
 int h = barcode.getBarcodeSize().getHeight()*3
 bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB)
 int fontSize = 20
 g2 = bi.createGraphics()
 g2.setColor(Color.WHITE)
 g2.fillRect(0,0,w,h)
 g2.drawImage(img, 0, 0, w, h-fontSize, null)
 g2.setFont(new Font('Arial', Font.PLAIN, fontSize))
 stringLen = g2.getFontMetrics().getStringBounds(fm_content, g2).getWidth()
 start = w/2 - stringLen/2
 g2.setColor(Color.BLACK)
 g2.drawString(fm_content, start.toInteger(), h-2)
 g2.dispose()
 return bi

共 (1) 个答案

  1. # 1 楼答案

    按照代码编辑回答。。 填充背景,将条形码放置在低于垂直高度的地方,并使用图像的setFont方法-首先测量文本宽度,并在图像大小和文本大小之间的一半距离处开始测量

     img = barcode.createAwtImage(Color.BLACK, Color.WHITE);
     int w = barcode.getBarcodeSize().getWidth() * 3;
     int h = barcode.getBarcodeSize().getHeight() * 3;
    
     BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
     int fontSize = 20;
    
     Graphics2D g2 = bi.createGraphics();
     g2.setColor(Color.WHITE);
     g2.fillRect(0, 0, w, h);
     g2.drawImage(img, 0, 0, w, h - fontSize, null);
    
     g2.setFont(new Font('Arial', Font.PLAIN, fontSize));
     double stringLen = g2.getFontMetrics().getStringBounds(fm_content, g2).getWidth();
     double start = w / 2 - stringLen / 2;
     g2.setColor(Color.BLACK);
     g2.drawString(fm_content, (int) Math.round(start), h - 2);
    
     g2.dispose();
    
     return bi;