在java中打印2页jframe [英] printing a 2 pages of jframe in java

查看:20
本文介绍了在java中打印2页jframe的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想打印一个包含大量文本字段和包含数据的按钮的 jframe.我想通过单击打印 j"按钮来打印此 jframe.我试过这个代码.

i would like to print a jframe that contain a lot of textfield and buttons that contain a data. i want to print this jframe by clicking a Print jbutton. i tried this code.

protected void print() {
PrinterJob job = PrinterJob.getPrinterJob();
if(job.printDialog()){
  try {
    job.setPrintable(new Printable() {

      @Override
      public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
        if(pageIndex == 0){
          Graphics2D g2d = (Graphics2D)graphics;
          g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());

        Dimension dim = ODietListJFrame.this.getSize();
        double cHeight = dim.getHeight();
        double cWidth = dim.getWidth();

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

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

        g2d.scale(xRatio, yRatio);

          ODietListJFrame.this.printAll(g2d);
          return PAGE_EXISTS;
        }
        return NO_SUCH_PAGE;
      }
    });
    job.print();
  } catch (PrinterException e) {
    e.printStackTrace();
  }
} else {
  System.err.println("Error printing");
}

}

我的问题是我的 jframe 太大,必须分两页打印,此代码打印第二页.我想从 jframe 打印第一部分.

My problem is that my jframe is too large that is must be print in two pages and this code print the second page. i want to print the first part from the jframe.

感谢您的帮助.

推荐答案

因此,我们需要做的第一件事是确保打印的组件是首选尺寸...

So, the first thing we need to is make sure that the component been printed is at it's preferred size...

component.setSize(component.getPreferredSize());

这很重要,但也要记住,这会影响屏幕上的组件...

This is important, but also remember, that this will affect the component that is on the screen...

接下来,我们需要确定是打印新页面还是重新打印当前页面.发生这种情况是因为 print 可能会为给定页面多次调用...

Next, we need to work out if we are printing a new page or re-printing the current page. This occurs because print might be called multiple times for a given page...

if (lastPage != pageIndex) {
    lastPage = pageIndex;
    //...
}

然后我们需要计算适合当前页面的组件的 y 偏移量...

We then need to calculate the y offset of the component that fits the current page...

yOffset = height * pageIndex;
if (yOffset > component.getHeight()) {
    yOffset = -1;
}

如果 yOffset 大于 component 的高度,那么我们不想打印更多的页面.

If the yOffset is greater then the component height, then we don't want to print any more pages.

接下来,我们打印页面,为此,我们需要翻译 Graphics 上下文,以便 yOffset 成为新的 0位置...

Next, we print the page, to do this, we need to translate the Graphics context so that the yOffset becomes the new 0 position...

g2d.translate(0, -yOffset);

然后我们打印组件...

Then we print the component...

component.printAll(g2d);

例如...

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.MediaSizeName;
import javax.print.attribute.standard.PrinterResolution;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.Scrollable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class PrintMe {

    public static void main(String[] args) {
        new PrintMe();
    }

    public PrintMe() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                TestPane testPane = new TestPane();

                JButton btn = new JButton("Print");
                btn.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
                        aset.add(MediaSizeName.ISO_A4);
                        aset.add(new PrinterResolution(300, 300, PrinterResolution.DPI));

                        PrinterJob pj = PrinterJob.getPrinterJob();
                        pj.setPrintable(new MultiPagePrintable(testPane));

                        if (pj.printDialog(aset)) {
                            try {
                                pj.print(aset);
                                testPane.getParent().invalidate();
                                testPane.getParent().validate();
                            } catch (PrinterException ex) {
                                ex.printStackTrace();
                            }
                        }
                    }
                });

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new JScrollPane(testPane));
                frame.add(btn, BorderLayout.SOUTH);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel implements Scrollable {

        private BufferedImage img;

        public TestPane() {
            try {
                img = ImageIO.read(new File("Get your own image"));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

        @Override
        public Dimension getPreferredSize() {
            return img == null ? new Dimension(200, 200) : new Dimension(img.getWidth(), img.getHeight());
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            if (img != null) {
                Graphics2D g2d = (Graphics2D) g.create();
                int x = (getWidth() - img.getWidth()) / 2;
                int y = (getHeight() - img.getHeight()) / 2;
                g2d.drawImage(img, x, y, this);
                g2d.dispose();
            }
        }

        @Override
        public Dimension getPreferredScrollableViewportSize() {
            return new Dimension(200, 200);
        }

        @Override
        public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) {
            return 128;
        }

        @Override
        public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) {
            return 128;
        }

        @Override
        public boolean getScrollableTracksViewportWidth() {
            return false;
        }

        @Override
        public boolean getScrollableTracksViewportHeight() {
            return false;
        }

    }

    public class MultiPagePrintable implements Printable {

        private JComponent component;
        private int lastPage = 0;
        private double yOffset;

        public MultiPagePrintable(JComponent component) {
            this.component = component;
        }

        @Override
        public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
            int result = NO_SUCH_PAGE;

            double height = pageFormat.getImageableHeight();
            component.setSize(component.getPreferredSize());

            if (lastPage != pageIndex) {
                lastPage = pageIndex;
                yOffset = height * pageIndex;
                if (yOffset > component.getHeight()) {
                    yOffset = -1;
                }
            }

            if (yOffset >= 0) {
                Graphics2D g2d = (Graphics2D) graphics;

                g2d.translate((int) pageFormat.getImageableX(),
                                (int) pageFormat.getImageableY());

                g2d.translate(0, -yOffset);
                component.printAll(g2d);
                result = PAGE_EXISTS;
            }
            return result;
        }

    }

}

现在,这个例子只在垂直方向打印,如果你需要它也打印水平方向,它会稍微复杂一些,但基本概念保持不变

Now, this example only prints in the vertical direction, if you need it to print the horizontal direction as well, it gets a little more complicated, but that the basic concept remains the same

这篇关于在java中打印2页jframe的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆