将 JPanel 转换为图像以添加到具有白色或透明背景的 iText PDF 中



我正在尝试将JPanel转换为图像,并将使用iText将其写入PDF。我已经搜索了如何将 JPanel 转换为图像的方法,并找到了两个"工作"解决方案。

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;
}

如您所见,我已经使用"ARGB"尝试将其转换为具有透明或白色背景的图像,但它不起作用。见附图。有没有办法将其转换为图像并将其打印为具有白色或透明背景的PDF?

下面是使用上面的代码从 JPanel 转换的图像图片写在 PDF 上

底部是我要转换为图像的JPanel我想转换的

有没有办法将其转换为图像并将其打印为具有白色或透明背景的PDF?

默认情况下,JPanel 是不透明的,并且有自己的背景,因此背景会被复制到图像中。

我以前从未尝试过这个,但也许嵌套这样的面板会起作用:

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

所以现在,当您创建缓冲图像时,imagePanel 应该是透明的。但它将继承背景面板的背景颜色,因此它在框架中看起来仍然正确。

我认为最简单的方法是将面板尺寸适合内部组件,然后组件可能会覆盖所有面板背景

最新更新