1

我正在使用 Java 进行调查,并希望有一个可打印的版本。但是,有些问题不在可视区域内(它们在 JScrollPane 中)。下面是我用于打印的代码,但它只打印 JFrame 的可见部分。请问有人可以帮忙吗?

private void printFrame(){
    PrinterJob printerJob = PrinterJob.getPrinterJob();

    printerJob.setPrintable(this);

    // pop up a dialog box for the end user to fine tune the options.
    if ( printerJob.printDialog() )
        {
        try
            {
            // render the component onto the printer or print queue.
            printerJob.print();
            }
        catch ( PrinterException e )
            {
            System.out.println( "Error printing: " + e );
            }
        }
    }

public int print( Graphics gr, PageFormat pageFormat, int pageIndex ){
        if ( pageIndex > 0 )
            {
            return Printable.NO_SUCH_PAGE;
            }

        Graphics2D g2d = (Graphics2D)gr;      
        g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());

        double xScale = 0.33;
        double yScale = 0.33;

        g2d.scale(xScale, yScale);

        paint(g2d);

        return Printable.PAGE_EXISTS;
    }

提前致谢

4

2 回答 2

1

谢谢,亚瑟。我现在可以使用它:

public void PrintFrameToPDF(File file) {
    try {
        Document d = new Document();
        PdfWriter writer = PdfWriter.getInstance(d, new FileOutputStream(file));
        d.open();

        PdfContentByte cb = writer.getDirectContent();
        PdfTemplate template = cb.createTemplate(PageSize.A4.getWidth(),PageSize.A4.getHeight());
        cb.addTemplate(template, 0, 0);

        Graphics2D g2d = template.createGraphics(PageSize.A4.getWidth(),PageSize.A4.getHeight());
        g2d.scale(0.4, 0.4);

        for(int i=0; i< this.getContentPane().getComponents().length; i++){
            Component c = this.getContentPane().getComponent(i);
            if(c instanceof JLabel || c instanceof JScrollPane){
                g2d.translate(c.getBounds().x,c.getBounds().y);
                if(c instanceof JScrollPane){c.setBounds(0,0,(int)PageSize.A4.getWidth()*2,(int)PageSize.A4.getHeight()*2);}
                c.paintAll(g2d);
                c.addNotify();
            }
        }


        g2d.dispose();

        d.close();
    } catch (Exception e) {
        System.out.println("ERROR: " + e.toString());
    }
}

如果有人对上述内容进行了优化,我很乐意听取您的意见。谢谢您的帮助!D

于 2013-06-09T23:47:38.673 回答
0

可以在http://itextpdf.com/找到一个 PDF 库。

于 2013-06-09T23:01:13.660 回答