【问题标题】:is it possible to get an awt image of barcode with text是否有可能获得带有文本的条形码的 awt 图像
【发布时间】:2015-08-08 07:56:13
【问题描述】:

是否可以扩展条形码类型的 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

【问题讨论】:

  • 好问题(我不明白反对票)。您提到了createAwtImage(),这确实是一种仅创建没有任何文本的条​​形码的方法。 iText 不会向此 AWT Image 添加文本。但是,您可以使用此图像并使用普通的旧 Java 代码添加文本。这个问题可以改写为:“如何在 Java 中扩展图像的大小并为该图像添加一些文本?”我将更新标签以反映这一点。
  • 您发布的 groovy 代码基本上是 Java,每行末尾没有分号...您有什么理由不能使用它?还是编辑是您自己问题的答案?如果是这样,您应该将其发布为答案(并在此过程中获得一些代表)。 :-)

标签: java image itext bufferedimage itextpdf


【解决方案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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-27
    • 1970-01-01
    • 1970-01-01
    • 2011-08-11
    • 1970-01-01
    • 2018-12-15
    • 2020-12-25
    相关资源
    最近更新 更多