-1

I have a jLabel with an Icon that I want to print in a printer (canon,hp,epson anything) using a button. How can I do that? Any useful code? Code snippet? links? All I can see is like this: How to print content of a label in java?

But It's not what I want. I'm using netbeans Thanks in advance.

Community
  • 1
  • 1
user3260589
  • 168
  • 1
  • 4
  • 12
  • Take a look at [this example](http://stackoverflow.com/questions/12764634/printing-a-jframe-and-its-components/12765916#12765916) – MadProgrammer Feb 27 '14 at 04:05
  • 1
    It's printing a Jframe. I only want jLabel to be printed. – user3260589 Feb 27 '14 at 04:13
  • If you took the time to look at the code and not the title, you would have seen this nice method called `public static void printComponent(JComponent comp, boolean fill)` ... which takes a `Component` you wanted printed on a piece of paper....Printing a frame generally is the same process for printing just about any component in Swing...that's what makes it nice – MadProgrammer Feb 27 '14 at 04:15

1 Answers1

1

Basically, the answer will depend on whether the label is displayed on the screen or not. To ensure that the label (or in fact, any component) can be printed, it must first be sized properly...

This can be done using setSize and feeding it getPreferredSize at the very basic level.

The next step is passing using the components printAll method (or print method depending on your needs) which is better suited for...printing...as it disables double buffering and won't produce nasty exceptions when it's not attached to a native peer...

Example printed as preferred size...

Normal

Example printed to fill available area...

Filled

Now the example uses the printComponentToFile method, but you'll want to use the printComponent method for actually printing it a printer, the first is useful for doing things like page previews and screen dumps...

import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

public class PrintALabel {

    public static void main(String[] args) {
        try {
            JLabel label = new JLabel(
                    "This is a test",
                    new ImageIcon("path/to/image"),
                    JLabel.CENTER);
            printComponentToFile(label, true);
            printComponentToFile(label, false);
        } catch (PrinterException exp) {
            exp.printStackTrace();
        }
    }

    public static void printComponent(JComponent comp, boolean fill) throws PrinterException {
        PrinterJob pjob = PrinterJob.getPrinterJob();
        PageFormat pf = pjob.defaultPage();
        pf.setOrientation(PageFormat.LANDSCAPE);

        PageFormat postformat = pjob.pageDialog(pf);
        if (pf != postformat) {
            //Set print component
            pjob.setPrintable(new ComponentPrinter(comp, fill), postformat);
            if (pjob.printDialog()) {
                pjob.print();
            }
        }
    }

    public static void printComponentToFile(Component comp, boolean fill) throws PrinterException {
        Paper paper = new Paper();
        paper.setSize(8.3 * 72, 11.7 * 72);
        paper.setImageableArea(18, 18, 559, 783);

        PageFormat pf = new PageFormat();
        pf.setPaper(paper);
        pf.setOrientation(PageFormat.LANDSCAPE);

        BufferedImage img = new BufferedImage(
                (int) Math.round(pf.getWidth()),
                (int) Math.round(pf.getHeight()),
                BufferedImage.TYPE_INT_RGB);

        Graphics2D g2d = img.createGraphics();
        g2d.setColor(Color.WHITE);
        g2d.fill(new Rectangle(0, 0, img.getWidth(), img.getHeight()));
        ComponentPrinter cp = new ComponentPrinter(comp, fill);
        try {
            cp.print(g2d, pf, 0);
        } finally {
            g2d.dispose();
        }

        try {
            ImageIO.write(img, "png", new File("Page-" + (fill ? "Filled" : "") + ".png"));
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public static class ComponentPrinter implements Printable {

        private Component comp;
        private boolean fill;

        public ComponentPrinter(Component comp, boolean fill) {
            this.comp = comp;
            this.fill = fill;
        }

        @Override
        public int print(Graphics g, PageFormat format, int page_index) throws PrinterException {

            if (page_index > 0) {
                return Printable.NO_SUCH_PAGE;
            }

            Graphics2D g2 = (Graphics2D) g;
            g2.translate(format.getImageableX(), format.getImageableY());

            double width = (int) Math.floor(format.getImageableWidth());
            double height = (int) Math.floor(format.getImageableHeight());

            if (!fill) {

                width = Math.min(width, comp.getPreferredSize().width);
                height = Math.min(height, comp.getPreferredSize().height);

            }

            comp.setBounds(0, 0, (int) Math.floor(width), (int) Math.floor(height));
            if (comp.getParent() == null) {
                comp.addNotify();
            }
            comp.validate();
            comp.doLayout();
            comp.printAll(g2);
            if (comp.getParent() != null) {
                comp.removeNotify();
            }

            return Printable.PAGE_EXISTS;
        }

    }

}
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • This is good, but can I have a shorter one? Or the one can put under a button – user3260589 Feb 27 '14 at 07:15
  • Only if you pay me - ie No, that's about as short as you're going to be able to get it, unless you don't bother showing the print dialog, but then how would you know where it's been printed... – MadProgrammer Feb 27 '14 at 07:16
  • I wanted to know what should I put under the button. – user3260589 Feb 27 '14 at 07:21
  • something here: `private void btnOKActionPerformed(java.awt.event.ActionEvent evt)` – user3260589 Feb 27 '14 at 07:21
  • I assume you have some kind of button that when clicked you want to print the image? In that case you should just call `printComponent(label, false);` depending on your circumstances... – MadProgrammer Feb 27 '14 at 07:22
  • 1
    I'm having trouble putting this on netbeans. Not sure what should I put or not – user3260589 Feb 27 '14 at 07:29
  • What you need is the `printComponent` method and `ComponentPrinter` class. You could merge the two (as `printComponent` is `static`), these need to be placed into your project somewhere and imported into you current class, you then just need to call them like any other class/`static` method... – MadProgrammer Feb 27 '14 at 10:00
  • I still don't get it. :( Sorry that I'm still a noobie. – user3260589 Feb 27 '14 at 13:34
  • I really need this printing capability for the project. Please help :( – user3260589 Feb 27 '14 at 13:39
  • Copy the ComponetPrinter class(and the bottom of the source example) and place it in its own class within your project (you not need static in the class declaration). Copy the printComponent method and put it within you source code somewhere (probably within the class with the button) and call it passing the label you want to print – MadProgrammer Feb 27 '14 at 21:03
  • Sorry but I can't get it. I'll post my code later, please help where should I put those. – user3260589 Feb 28 '14 at 11:39
  • 1
    So here's my code: http://pastebin.com/FYqi4uks Unfortunately, I can't post anything here right now :( – user3260589 Feb 28 '14 at 13:06