将JScrollPane内容打印为pdf

时间:2016-04-07 12:38:46

标签: java swing pdf jpanel writefile

我找到了这个代码,它将JPanel传输到图像,然后将其打印到PDF文件,但因为我在JScrollPane中有我的JPanel并且不包含任何布局或尺寸,因为它依赖于JScrollPane布局所以我可以打印出来。错误说无法打印高度为0和宽度为0的图片。当我尝试传递JScrollPane本身时,我只获得了JScrollPane的框架,只打印了没有内容的JPanel。

public void printToPDF(java.awt.Image awtImage, String fileName) {
    try {
        Document d = new Document();
        PdfWriter writer = PdfWriter.getInstance(d, new FileOutputStream(
                fileName));
        d.open();


        Image iTextImage = Image.getInstance(writer, awtImage, 1);
        //iTextImage.setAbsolutePosition(100,300);
        iTextImage.scalePercent(100);
        d.add(iTextImage);

        d.close();

    } catch (Exception e) {
        e.printStackTrace();
    }   
}

public static java.awt.Image getImageFromPanel(Component component) {

    BufferedImage image = new BufferedImage(component.getWidth(),
            component.getHeight(), BufferedImage.TYPE_INT_RGB);
    component.paint(image.getGraphics());
    return image;
}

以下是主要方法:

         JScrollPane scrollPane = new JScrollPane();
    scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
    scrollPane.setBounds(0, 0, 600, 510);
    scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
    getContentPane().add(scrollPane);

    GridBagConstraints c = new GridBagConstraints();
    JPanel borderpanel = new JPanel();
    scrollPane.setViewportView(borderpanel);

    Color veryLight = new Color(239,230,230);
    JPanel container = new JPanel();
    borderpanel.add(container, BorderLayout.CENTER);
    container.setLayout(new GridLayout(0,1,0,1));
    container.setBackground(Color.WHITE);

    JPanel test = new JPanel();
    test.setLayout(new GridLayout(0,1,0,1));
    container.add(test, BorderLayout.CENTER);

        JPanel rowPanel = new JPanel();
        rowPanel.setPreferredSize(new Dimension(580,50));
        test.add(rowPanel, BorderLayout.WEST);
        rowPanel.setLayout(null);

        JLabel auctionTitle = new JLabel("Auction Title");
        auctionTitle.setForeground(Color.WHITE);
        auctionTitle.setFont(new Font("Tahoma", Font.PLAIN, 14));
        auctionTitle.setBounds(102, 0, 82, 20);
        rowPanel.add(auctionTitle); 
        rowPanel.setBackground(SystemColor.GRAY);

        JTextArea textArea = new JTextArea();
        textArea.setBackground(veryLight);
        textArea.setBounds(191, 0, 386, 50);
        rowPanel.add(textArea);


        final java.awt.Image image = getImageFromPanel(borderpanel);

        String fileName = "C:\\Users\\Test\\Desktop\\newfile.pdf";
        printToPDF(image, fileName);

我想打印borderpanel

1 个答案:

答案 0 :(得分:1)

使用geom_histogram获取面板图片:

java.awt.Robot