3

Is there a way to save the com.itextpdf.text.Image file as a jpg file on the file system ?

Barcode39 code39 = new Barcode39();
code39.setCode(barcode);
code39.setStartStopText(false);
image39 = code39.createImageWithBarcode(cb, null, null);
image39.scaleAbsolute(width, height);
image39.setAbsolutePosition(top, left);
cb.addImage(image39);

I am creating a bar code image and adding it to a pdf. At the same time i want the image to be saved on the file system. Any help is appreciated.

OR,

Is it possible to retrieve the barcode from the pdf( both the barcode as well as the numbers under it) as an image file and save it to the file system using itext ?

Adarsh
  • 3,613
  • 2
  • 21
  • 37

2 Answers2

6

Just convert the Barcode39 itext image into an AWT image using createAwtImage:

java.awt.Image awtImage = code39.createAwtImage(Color.BLACK, Color.WHITE);

Then convert it to a BufferedImage and store it:

BufferedImage bImage= new BufferedImage(awtImage.getWidth(), awtImage.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D g = bImage.createGraphics();
g.drawImage(awtImage, 0, 0, null);
g.dispose();

ImageIO.write(bImage, "jpg", new File("code39.jpg"));
sina72
  • 4,931
  • 3
  • 35
  • 36
  • Thank you, that helped. 1 thing, ImageIO.write takes a RenderedImage object, so I will need to pass the BufferedImage object and not the awtImage object. – Adarsh Jul 24 '14 at 22:04
  • @sina72 How about itext7 ? I can not set image dimensions and save as image file like this. Can you please help ? – webyildirim Jun 01 '18 at 14:45
2

You can use this code:

BarcodeQRCode qrcode = new BarcodeQRCode("testo testo testo", 1, 1, null);
Image image = qrcode.createAwtImage(Color.BLACK, Color.WHITE);

BufferedImage buffImg = new BufferedImage(image.getWidth(null), image.getWidth(null), BufferedImage.TYPE_4BYTE_ABGR);
buffImg.getGraphics().drawImage(image, 0, 0, null);
buffImg.getGraphics().dispose();

File file = new File("tmp.png");
ImageIO.write(buffImg, "png", file);

I hope it helps you.

Enrico

newenglander
  • 2,019
  • 24
  • 55
Enrico
  • 31
  • 3