Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print image in java

Tags:

java

image

How can we print a buffered image in java? We can send FileInputStream to Print Service, but i need to send buffered Image to it.

FileInputStream fin = new FileInputStream("YOurImageFileName.PNG");
Doc doc = new SimpleDoc(fin, DocFlavor.INPUT_STREAM.GIF, null);
job.print(doc, pras);

Is it possible?

Check the complete code here.

like image 506
vicky Avatar asked May 07 '12 09:05

vicky


People also ask

How to display an image in Java?

Can We Display An Image In Java? JLabel can be used to display an image in Java. The file path is passed to the Files class by pass the Image’s path. ImageIO is next used to transform the image into a BufferedImage object. It is now time to create the icon for the JLabel.

What is the use of print () method in Java?

The print () method is used to print text on the console. It is an overloaded method of the PrintStream class. It accepts a string as a parameter. After printing the statement, the cursor remains on the same line.

How to print a statement in Java?

In Java, we usually use the println () method to print the statement. It belongs to the PrintStream class. The class also provides the other methods for the same purpose. In this section, we will learn how to print in Java. Along with this, we will also explain the statement System.out.println ().

How do I add an image to a JLabel in Java?

JLabel extends JComponent, and we can attach this component to a JFrame. To read the image file, we use the File class and pass the path of the image. Next we convert the image to a BufferedImage object using ImageIO.read (). Now we create an icon to be shown in the JLabel.


2 Answers

PrinterJob printJob = PrinterJob.getPrinterJob();
printJob.setPrintable(new Printable() {
        public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
                if (pageIndex != 0) {
                    return NO_SUCH_PAGE;
                }
                graphics.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
                return PAGE_EXISTS;
        }
});     
try {
    printJob.print();
} catch (PrinterException e1) {             
    e1.printStackTrace();
}
like image 181
vivek Avatar answered Nov 14 '22 21:11

vivek


You can use the iText library.. there is a simple example to print an Image to pdf .

Adding an IText Image to a PDF document

like image 26
LyB8899 Avatar answered Nov 14 '22 23:11

LyB8899