繁体   English   中英

如何制作JFrame的PDF(包括未显示的JScrollPane部件)?

[英]How do I make a PDF of the JFrame (including the JScrollPane parts not shown)?

我正在使用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;
    }

提前致谢

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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