Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving com.itextpdf.text.Image as a image file

Tags:

java

image

itext

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 ?

like image 799
Adarsh Avatar asked Jun 09 '26 15:06

Adarsh


2 Answers

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"));
like image 87
sina72 Avatar answered Jun 12 '26 04:06

sina72


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

like image 34
Enrico Avatar answered Jun 12 '26 04:06

Enrico