打印java应用程序的界面.可以指定是这个界面中的任何一个组件.

今天组长说要打印FSI系统的界面.我上叫我research下先.我google下看了别人的文章写了下面这个工具类.

/*
 * Created on 2005-3-23
 */
package com.dengyin.awt.printutils;

import java.awt.Component;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.PrintJob;
import java.awt.Toolkit;
import java.util.Properties;

/**
 * PrintUtil用于打印一个java应用程序(Frame)或是这个应用程序中的某个组件(Component)的界面.
 * 它不适用于打印文本,它的作用相当于先截取一个java应用程序(Frame)或是这个应用程序中的某个组
 * 件(Component)的图像,然后用打印机打印出来.
 *
 * 我写这个类时主要是参照了这篇文章
 *
 * @see <a
 *      href="http://www-900.ibm.com/developerWorks/cn/java/l-javaprint/index.shtml">Java打印程序设计
 *      </a>
 * @see java.awt.PrintJob
 * @version 0.1 2005-3-23
 * @author 邓胤
 */
public class PrintUtil {

    /**
     *
     * @param frame
     *            java应用程序的主Frame
     * @param com
     *            你想打印的在主Frame中的组件(可以是任何继承java.awt.Component的类型)
     */
    public static void print(Frame frame, Component com) {

        Toolkit kit = Toolkit.getDefaultToolkit(); //获取工具箱
        Properties props = new Properties();
        props.put("awt.print.printer", "durango");//设置打印属性
        props.put("awt.print.numCopies", "2");
        if (kit != null) {
            //获取工具箱自带的打印对象
            PrintJob printJob = kit.getPrintJob(frame, "Print Frame", props);
            if (printJob != null) {
                Graphics pg = printJob.getGraphics();//获取打印对象的图形环境
                if (pg != null) {
                    try {
                        com.printAll(pg);//打印该窗体及其所有的组件
                    } finally {
                        pg.dispose();//注销图形环境
                    }
                }
                printJob.end();//结束打印作业
            }
        }

    }

    /**
     * 这个方法依赖于PrintPreviewDialog
     *
     * @param frame
     *            java应用程序的主Frame
     * @param com
     *            你想预览打印的在主Frame中的组件(可以是任何继承java.awt.Component的类型)
     */
    public static void printPreview(Frame frame, Component com) {
        PrintPreviewDialog pd = new PrintPreviewDialog(frame, "print preview",
                true, com);
        pd.setSize(400, 600);
        pd.setVisible(true);
    }

}

package com.dengyin.awt.printutils;

import java.awt.event.*;
import java.awt.*;
import java.awt.print.*;
import javax.swing.*;

import com.szallcom.tools.SystemProperties;

import java.awt.geom.*;

/**
 * 我只是将网上的这个例子拿下来改了改 详情请见
 *
 * @see <a
 *      href="http://www-900.ibm.com/developerWorks/cn/java/l-javaprint/index.shtml">Java打印程序设计
 *      </a>
 * @author 邓胤
 */
public class PrintPreviewDialog extends JDialog implements ActionListener {

    private JButton closeButton = new JButton("Close");

    private JButton printButton = new JButton("Ok! I want to print now.");

    private JPanel buttonPanel = new JPanel();

    private PreviewCanvas canvas;

    private Frame parent;

    private Component com;

    public PrintPreviewDialog(Frame parent, String title, boolean modal,
            Component pt) {
        super(parent, title, modal);
        this.parent = parent;
        this.com = pt;
        canvas = new PreviewCanvas(pt);
        setLayout();
    }

    private void setLayout() {
        this.getContentPane().setLayout(new BorderLayout());
        this.getContentPane().add(canvas, BorderLayout.CENTER);

        closeButton.setMnemonic('N');
        closeButton.addActionListener(this);

        printButton.setMnemonic('N');
        printButton.addActionListener(this);

        buttonPanel.add(closeButton);
        buttonPanel.add(printButton);
        this.getContentPane().add(buttonPanel, BorderLayout.SOUTH);
        this.setBounds((int) ((SystemProperties.SCREEN_WIDTH - 400) / 2),
                (int) ((SystemProperties.SCREEN_HEIGHT - 400) / 2), 400, 400);
    }

    public void actionPerformed(ActionEvent evt) {
        Object src = evt.getSource();
        if (src == closeButton)
            closeAction();
        else if (src == printButton)
            printNow();
    }

    private void printNow() {
        PrintUtil.print(parent, com);
    }

    private void closeAction() {
        this.setVisible(false);
        this.dispose();
    }

    class PreviewCanvas extends JPanel {
        private int currentPage = 0;

        private Component preview;

        public PreviewCanvas(Component pt) {
            preview = pt;
        }

        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) g;
            PageFormat pf = PrinterJob.getPrinterJob().defaultPage();

            double xoff;
            double yoff;
            double scale;
            double px = pf.getWidth();
            double py = pf.getHeight();
            double sx = getWidth() - 1;
            double sy = getHeight() - 1;
            if (px / py < sx / sy) {
                scale = sy / py;
                xoff = 0.5 * (sx - scale * px);
                yoff = 0;
            } else {
                scale = sx / px;
                xoff = 0;
                yoff = 0.5 * (sy - scale * py);
            }
            g2.translate((float) xoff, (float) yoff);
            g2.scale((float) scale, (float) scale);

            Rectangle2D page = new Rectangle2D.Double(0, 0, px, py);
            g2.setPaint(Color.white);
            g2.fill(page);
            g2.setPaint(Color.black);
            g2.draw(page);

            preview.print(g2);
        }

    }
}

详情请见http://www-900.ibm.com/developerWorks/cn/java/l-javaprint/index.shtml

上面实现的当窗体宽度大于纸张的宽度时.只能打印出一部分.

经过自己的东拼西凑自己解决了这个问题.

/*
 * Created on 2005-3-23
 */
package com.fsillc.print.test;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.PrintJob;

import java.awt.Toolkit;
import java.awt.geom.AffineTransform;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.util.Properties;

/**
 * PrintUtil用于打印一个java应用程序(Frame)或是这个应用程序中的某个组件(Component)的界面.
 * 它不适用于打印文本,它的作用相当于先截取一个java应用程序(Frame)或是这个应用程序中的某个组
 * 件(Component)的图像,然后用打印机打印出来.
 *
 * 我写这个类时主要是参照了这篇文章
 *
 * @see <a
 *      href="http://www-900.ibm.com/developerWorks/cn/java/l-javaprint/index.shtml">Java打印程序设计
 *      </a>
 * @see java.awt.PrintJob
 * @version 0.1 2005-3-23
 * @author 邓胤
 */
public abstract class PrintUtil implements Printable{

    /**
     *
     * @param frame
     *            java应用程序的主Frame
     * @param com
     *            你想打印的在主Frame中的组件(可以是任何继承java.awt.Component的类型)
     */
    public static void print(Component com) {
        /*
         * Toolkit kit = Toolkit.getDefaultToolkit(); //获取工具箱 Properties props =
         * new Properties(); props.put("awt.print.printer", "durango");//设置打印属性
         * props.put("awt.print.numCopies", "2"); if (kit != null) {
         * //获取工具箱自带的打印对象 PrintJob printJob = kit.getPrintJob(frame, "Print
         * Frame", props); if (printJob != null) { Graphics pg =
         * printJob.getGraphics();//获取打印对象的图形环境
         *
         * if (pg != null) { try { com.printAll(pg);//打印该窗体及其所有的组件 } finally {
         * pg.dispose();//注销图形环境 } } printJob.end();//结束打印作业 } }
         */
        PrinterJob job = PrinterJob.getPrinterJob();
        job.setJobName("Maxim 1");
        job.setPrintable((Printable) com);
        try {
            job.print();
        } catch (PrinterException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 这个方法依赖于PrintPreviewDialog
     *
     * @param frame
     *            java应用程序的主Frame
     * @param com
     *            你想预览打印的在主Frame中的组件(可以是任何继承java.awt.Component的类型)
     */
    public static void printPreview(Frame p,Component com) {
        PrintPreviewDialog pd = new PrintPreviewDialog(p,"print Preview",true,com);
        pd.setSize(800, 600);
        pd.setVisible(true);
    }
    public static int printAble(Component c,Graphics g,PageFormat pageFormat,int pageIndex){
        if (pageIndex == 0) {

//          this.setSize((int) pageFormat.getImageableWidth(), (int) pageFormat
//                  .getImageableHeight());
//          this.validate();
//          g.translate((int) pageFormat.getImageableX(), (int) pageFormat
//                  .getImageableY());
//          this.printAll(g);
//          return PAGE_EXISTS;

                      Dimension prefSize = c.getPreferredSize();
                      c.setSize(prefSize);
                      c.validate();
                      double ratio = pageFormat.getImageableWidth() / prefSize.width;
                      Graphics2D g2d = (Graphics2D) g;
                      // translate origin toimageable origin
                      g2d.transform(AffineTransform.getTranslateInstance(pageFormat
                              .getImageableX(), pageFormat.getImageableY()));
                      // // scale output
                      g2d.transform(AffineTransform.getScaleInstance(ratio, ratio));
                      c.printAll(g2d);
                      return PAGE_EXISTS;
      }
      return NO_SUCH_PAGE;
       
    }

  
}

package com.fsillc.print.test;

import java.awt.event.*;
import java.awt.*;
import java.awt.print.*;
import javax.swing.*;

import java.awt.geom.*;

public class PrintPreviewDialog extends JDialog
implements ActionListener
{

    private JButton closeButton = new JButton("Close");
    private JButton printButton = new JButton("Ok! I want to print the current tab.");
    private JPanel buttonPanel = new JPanel();
    private PreviewCanvas canvas;
    private Component c;
    public PrintPreviewDialog(Frame parent, String title, boolean modal, Component pt)
    {
        super(parent, title, modal);
        this.c = pt;
        canvas = new PreviewCanvas(pt);
        setLayout();
    }

    private void setLayout()
    {
        this.getContentPane().setLayout(new BorderLayout());
        this.getContentPane().add(canvas, BorderLayout.CENTER);


        closeButton.setMnemonic('N');
        closeButton.addActionListener(this);
       
        printButton.setMnemonic('N');
        printButton.addActionListener(this);
       
        buttonPanel.add(closeButton);
        buttonPanel.add(printButton);
       
        this.getContentPane().add(buttonPanel, BorderLayout.SOUTH);
        this.setBounds((int)((Toolkit.getDefaultToolkit().getScreenSize().width - 400) / 2), (int)((Toolkit.getDefaultToolkit().getScreenSize().height - 400) / 2), 400, 400);
    }

    public void actionPerformed(ActionEvent evt)
    {
        Object src = evt.getSource();
        if  (src == closeButton)
            closeAction();
         else if (src==printButton)
             PrintUtil.print(c);
    }

    private void closeAction()
    {
        this.setVisible(false);
        this.dispose();
    }


    class PreviewCanvas extends JPanel
    {
 
        private int currentPage = 0;
        private Component preview;

        public PreviewCanvas(Component pt)
        {

            preview = pt;
        }

        public void paintComponent(Graphics g)
        {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            PageFormat pf = PrinterJob.getPrinterJob().defaultPage();

            double xoff;
            double yoff;
            double scale;
            double px = pf.getWidth();
            double py = pf.getHeight();
            double sx = getWidth() - 1;
            double sy = getHeight() - 1;
            if (px / py < sx / sy)
            {
                scale = sy / py;
                xoff = 0.5 * (sx - scale * px);
                yoff = 0;
            }
            else
            {
                scale = sx / px;
                xoff = 0;
                yoff = 0.5 * (sy - scale * py);
            }
            g2.translate((float)xoff, (float)yoff);
            g2.scale((float)scale, (float)scale);

            Rectangle2D page = new Rectangle2D.Double(0, 0, px, py);
            g2.setPaint(Color.white);
            g2.fill(page);
            g2.setPaint(Color.black);
            g2.draw(page);

            try
            {
                ((Printable)preview).print(g2, pf, currentPage);
            }
            catch(PrinterException pe)
            {
                g2.draw(new Line2D.Double(0, 0, px, py));
                g2.draw(new Line2D.Double(0, px, 0, py));
            }
        }

    }
}

/*
 * Created on 2005-3-23
 */
package com.fsillc.print.test;

import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

/**
 * @author 邓胤
 */
public class PrintTest extends JFrame implements Printable {

    private JTextField txt1;

    private JLabel lab1;

    private JButton button;

    private JButton button1;

    private void printFrame(){
        PrintUtil.print(this);
       
    }

    private void previewFrame(){
        PrintUtil.printPreview(this,this);
    }
    /**
     * @param title
     * @throws java.awt.HeadlessException
     */
    public PrintTest(String title) throws HeadlessException {
        super(title);
        this.addWindowListener(new WindowsListener());
        txt1 = new JTextField("dafadsfads");
        lab1 = new JLabel("dsafad");
        button = new JButton("print!");
        button1 = new JButton("preview");
        Container c = this.getContentPane();
       
       
        c.setLayout(new FlowLayout());
        c.add(txt1);
        c.add(lab1);
        c.add(button);
        c.add(button1);
        button.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                printFrame();
            }
        });
       
        button1.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent e) {
                previewFrame();
               
            }
            });
    }

    public int print(Graphics graphics, PageFormat pageFormat, int pageIndex)
            throws PrinterException {
        return PrintUtil.printAble(this,graphics,pageFormat,pageIndex);
    }

    public static void main(String[] args) {
        JFrame f = new PrintTest("Print me!");
        f.setSize(600, 400);
        f.setVisible(true);
    }

    private class WindowsListener extends WindowAdapter {

        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
    }

}

运行这个test看效果.

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值