简体   繁体   中英

Converting JPanel to Image to be added in iText PDF with white or transparent background

I am trying to convert a JPanel to Image and will be writing it to a PDF using iText. I have searched ways on how to convert JPanel to Image and found two "Working" solutions.

private BufferedImage createImage(JPanel panel) {
    int w = panel.getWidth();
    int h = panel.getHeight();
    BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = bi.createGraphics();
    panel.print(g);
    return bi;
}

public static java.awt.Image getImageFromPanel(JPanel component) {
    BufferedImage image = new BufferedImage(component.getWidth(),
            component.getHeight(), BufferedImage.TYPE_INT_ARGB);
    component.paint(image.getGraphics());
    return image;
}

As you can see, I already used "ARGB" to try to convert it to image with a transparent or white background but it doesnt work. See attached image. Is there a way to convert it to image and print it to PDF with white or transparent background?

Below is the image converted from the JPanel using codes above Image written on PDF

Bottom is the JPanel I want to convert to Image JPanel I want to convert

Is there a way to convert it to image and print it to PDF with white or transparent background?

Well by default a JPanel is opaque and has its own background so the background get copied to the image.

I have never tried this before but maybe nesting panels something like this will work:

JPanel imagePanel = new JPanel();
imagePanel.setOpaque(false);
JPanel backgroundPanel = new JPanel( new BorderLayout() );
backgroundPanel.add( imagePanel );
frame.add( backgroundPanel );

So now the imagePanel should be be transparent when you create the BufferedImage. But it will inherit the background color of the backgroundPanel so it still looks correct in the frame.

I think the easiest way is to fit the Panel size to the inside components, then the components may cover all the Panel background

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM