打印一个JFrame及其组件(Printing a JFrame and its component

2019-06-18 11:17发布

我曾经在一个大的计划一直在努力和它的功能之一应当是打印的主窗口中的内容。 我查了API,发现这个例子:

http://docs.oracle.com/javase/tutorial/2d/printing/gui.html

这是非常有帮助,我试图通过将该我的打印按钮的actionPerformed方法内使用该代码在我的程序:

PrinterJob job = PrinterJob.getPrinterJob();
     job.setPrintable(this);
     boolean ok = job.printDialog();
     if (ok) {
         try {

             job.print();
         } catch (PrinterException ex) {
          /* The job did not successfully complete */
         }
     }

如果我点击打印按钮,我得到一台打印机对话框,当我告诉它来打印,它只是打印一个空白文档。 我知道上面的代码是不是我所需要的,因为我已经看到了API的例子有一个print()方法,但显然他们从来没有称呼它,所以它是非常令人迷惑。 我已经打过电话,并使用了很多次,但没有成功。

另外,我觉得,当我终于得到它的打印,我的窗口需要在横向进行打印,甚至可能需要一些缩放。 如何做到这一点任何想法?

我想任何有益的帮助,帮助我顺利实现此代码。 我知道我应该能够通过自己只是通过检查的文件做(我试过近2天了),但我无法得到它的工作。 我已经学会了所有我通过网络知道编程。 任何帮助将不胜感激。

Answer 1:

这里有一个简单的解决方案。 我有一个实现打印的打印机类,它会处理打印作业:

public static class Printer implements Printable {
    final Component comp;

    public Printer(Component comp){
        this.comp = comp;
    }

    @Override
    public int print(Graphics g, PageFormat format, int page_index) 
            throws PrinterException {
        if (page_index > 0) {
            return Printable.NO_SUCH_PAGE;
        }

        // get the bounds of the component
        Dimension dim = comp.getSize();
        double cHeight = dim.getHeight();
        double cWidth = dim.getWidth();

        // get the bounds of the printable area
        double pHeight = format.getImageableHeight();
        double pWidth = format.getImageableWidth();

        double pXStart = format.getImageableX();
        double pYStart = format.getImageableY();

        double xRatio = pWidth / cWidth;
        double yRatio = pHeight / cHeight;


        Graphics2D g2 = (Graphics2D) g;
        g2.translate(pXStart, pYStart);
        g2.scale(xRatio, yRatio);
        comp.paint(g2);

        return Printable.PAGE_EXISTS;
    }
}

接下来,将其打印出来:

JFrame yourComponent = new JFrame();
PrinterJob pjob = PrinterJob.getPrinterJob();
PageFormat preformat = pjob.defaultPage();
preformat.setOrientation(PageFormat.LANDSCAPE);
PageFormat postformat = pjob.pageDialog(preformat);
//If user does not hit cancel then print.
if (preformat != postformat) {
    //Set print component
    pjob.setPrintable(new Printer(yourComponent), postformat);
    if (pjob.printDialog()) {
        pjob.print();
    }
}


Answer 2:

这是我的想法捻...

打印,以适应...

打印填写...

public class TestPrinting {

    public static void main(String[] args) {    
        try {
            printComponentToFile(new PrintForm(), true);
            printComponentToFile(new PrintForm(), false);
        } catch (PrinterException exp) {
            exp.printStackTrace();
        }
    }

    public static void printComponent(JComponent comp, boolean fill) throws PrinterException {
        PrinterJob pjob = PrinterJob.getPrinterJob();
        PageFormat pf = pjob.defaultPage();
        pf.setOrientation(PageFormat.LANDSCAPE);

        PageFormat postformat = pjob.pageDialog(pf);
        if (pf != postformat) {
            //Set print component
            pjob.setPrintable(new ComponentPrinter(comp, fill), postformat);
            if (pjob.printDialog()) {
                pjob.print();
            }
        }    
    }

    public static void printComponentToFile(Component comp, boolean fill) throws PrinterException {    
        Paper paper = new Paper();
        paper.setSize(8.3 * 72, 11.7 * 72);
        paper.setImageableArea(18, 18, 559, 783);

        PageFormat pf = new PageFormat();
        pf.setPaper(paper);
        pf.setOrientation(PageFormat.LANDSCAPE);

        BufferedImage img = new BufferedImage(
                        (int) Math.round(pf.getWidth()),
                        (int) Math.round(pf.getHeight()),
                        BufferedImage.TYPE_INT_RGB);

        Graphics2D g2d = img.createGraphics();
        g2d.setColor(Color.WHITE);
        g2d.fill(new Rectangle(0, 0, img.getWidth(), img.getHeight()));
        ComponentPrinter cp = new ComponentPrinter(comp, fill);
        try {
            cp.print(g2d, pf, 0);
        } finally {
            g2d.dispose();
        }

        try {
            ImageIO.write(img, "png", new File("Page-" + (fill ? "Filled" : "") + ".png"));
        } catch (IOException ex) {
            ex.printStackTrace();
        }        
    }

    public static class ComponentPrinter implements Printable {

        private Component comp;
        private boolean fill;

        public ComponentPrinter(Component comp, boolean fill) {
            this.comp = comp;
            this.fill = fill;
        }

        @Override
        public int print(Graphics g, PageFormat format, int page_index) throws PrinterException {

            if (page_index > 0) {
                return Printable.NO_SUCH_PAGE;
            }

            Graphics2D g2 = (Graphics2D) g;
            g2.translate(format.getImageableX(), format.getImageableY());

            double width = (int) Math.floor(format.getImageableWidth());
            double height = (int) Math.floor(format.getImageableHeight());

            if (!fill) {

                width = Math.min(width, comp.getPreferredSize().width);
                height = Math.min(height, comp.getPreferredSize().height);

            }

            comp.setBounds(0, 0, (int) Math.floor(width), (int) Math.floor(height));
            if (comp.getParent() == null) {
                comp.addNotify();
            }
            comp.validate();
            comp.doLayout();
            comp.printAll(g2);
            if (comp.getParent() != null) {
                comp.removeNotify();
            }

            return Printable.PAGE_EXISTS;
        }

    }

}

一些范围更广的问题...

  • 你成为负责组件的布局被印刷,或多或少。 至少你会希望确保他们要么适合或你有某种溢出机制,摸索出...
  • 您可能需要那些尚未被显示在屏幕上,以为他们是“欺骗”成分......因此所有的周围淤泥质addNotify / validate / doLayout 。 显示在屏幕上即使,如果你修改自己的界限,你可能需要调用这些方法。


文章来源: Printing a JFrame and its components