JAVA实现打印机

我这里有以前收藏的代码,两个类实现了简易的文本打印机的功能,包括预览。简单跟你说一下。

1、PrinterDemo.java主体类,也是入口类,里面有main方法可以直接在Eclipse中调试运行,他实现了从本地磁盘读取文本类文件打印以及打印预览的功能,其中File动作按钮中的PrintPreviw就是打印预览功能,你可以运行看看。

2、PrintPreview.java打印预览类,这是专门为预览打印设计的类,通过他的构造方法可以构造出一个预览类,PrinterDemo中的预览功能就是调用了这个类。

两个类的源码:

【PrinterDemo.java】的源码:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Event;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
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 java.awt.print.PrinterJob;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Vector;

import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JScrollPane;
import javax.swing.KeyStroke;

public class PrinterDemo extends JFrame{
    private static final long serialVersionUID = 1L;
    private PageFormat        pageFormat;
    private FilePageRenderer  pageRenderer;
    private String            title;
    public PrinterDemo(){
        super();
        init();
        PrinterJob pj = PrinterJob.getPrinterJob();
        pageFormat = pj.defaultPage();
        setVisible(true);
    }
    protected void init()
    {
        setSize(350, 300);
        center();
        Container content = getContentPane();
        content.setLayout(new BorderLayout());
        JMenuBar mb = new JMenuBar();
        JMenu file = new JMenu("File", true);
        file.add(new FileOpenAction()).setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,Event.CTRL_MASK));
        file.add(new FilePrintPreviwAction()).setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, Event.ALT_MASK));
        file.add(new FilePrintAction()).setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P,Event.CTRL_MASK));
        file.add(new FilePageSetupAction()).setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, Event.CTRL_MASK| Event.SHIFT_MASK));
        file.addSeparator();
        file.add(new FileQuitAction()).setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q,
                                                                                 Event.CTRL_MASK));
            mb.add(file);
            JMenu page = new JMenu("Page", true);
            page.add(new PageNextPageAction())
                .setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, 0));
            page.add(new PagePreviousPageAction())
                .setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, 0));
            mb.add(page);
            setJMenuBar(mb);
            getContentPane().setLayout(new BorderLayout());
            addWindowListener(new WindowAdapter()
            {
                public void windowClosing(WindowEvent e)
                {
                    System.exit(0);
                }
            });
        }

        protected void center()
        {
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            Dimension frameSize = getSize();
            int x = (screenSize.width - frameSize.width) / 2;
            int y = (screenSize.height - frameSize.height) / 2;
            setLocation(x, y);
        }

        public void showTitle()
        {
            int currentPage = pageRenderer.getCurrentPage() + 1;
            int numPages = pageRenderer.getNumPages();
            setTitle(title + " - page " + currentPage + " of " + numPages);
        }

        public class FileOpenAction extends AbstractAction
        {
            private static final long serialVersionUID = 1L;

            public FileOpenAction()
            {
                super("Open...");
            }

            public void actionPerformed(ActionEvent ae)
            {
                // Pop up a file dialog.
                JFileChooser fc = new JFileChooser(".");
                int result = fc.showOpenDialog(PrinterDemo.this);
                if (result != 0)
                {
                    return;
                }
                java.io.File f = fc.getSelectedFile();
                if (f == null)
                {
                    return;
                }
                // Load the specified file.
                try
                {
                    pageRenderer = new FilePageRenderer(f, pageFormat);
                    title = "[" + f.getName() + "]";
                    showTitle();
                    JScrollPane jsp = new JScrollPane(pageRenderer);
                    getContentPane().removeAll();
                    getContentPane().add(jsp, BorderLayout.CENTER);
                    validate();
                } catch (java.io.IOException ioe)
                {
                    System.out.println(ioe);
                }
            }
        }

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

        public class FilePrintPreviwAction extends AbstractAction{
            private static final long serialVersionUID = 1L;

            public FilePrintPreviwAction(){
                super("PrintPreviw");
            }

            public void actionPerformed(ActionEvent ae){
                new PrintPreview(pageRenderer,"PrintPreviw",pageFormat.getOrientation());
            }
        }

        public class FilePrintAction extends AbstractAction{
            private static final long serialVersionUID = 1L;

            public FilePrintAction(){
                super("Print");
            }

            public void actionPerformed(ActionEvent ae){
                PrinterJob pj = PrinterJob.getPrinterJob();
                pj.setPrintable(pageRenderer, pageFormat);
                if (pj.printDialog()){
                    try{
                        pj.print();
                    } catch (PrinterException e){
                        System.out.println(e);
                    }
                }
            }
        }

        public class FilePageSetupAction extends AbstractAction {
            private static final long serialVersionUID = 1L;

            public FilePageSetupAction(){
                super("Page setup...");
            }

            public void actionPerformed(ActionEvent ae){
                PrinterJob pj = PrinterJob.getPrinterJob();
                pageFormat = pj.pageDialog(pageFormat);
                if (pageRenderer != null){
                    pageRenderer.pageInit(pageFormat);
                    showTitle();
                }
            }
        }

        public class FileQuitAction extends AbstractAction{
            private static final long serialVersionUID = 1L;

            public FileQuitAction(){
                super("Quit");
            }

            public void actionPerformed(ActionEvent ae){
                System.exit(0);
            }
        }

        public class PageNextPageAction extends AbstractAction{
            private static final long serialVersionUID = 1L;

            public PageNextPageAction(){
                super("Next page");
            }

            public void actionPerformed(ActionEvent ae){
                if (pageRenderer != null)
                    pageRenderer.nextPage();
                showTitle();
            }
        }

        public class PagePreviousPageAction extends AbstractAction{
            private static final long serialVersionUID = 1L;

            public PagePreviousPageAction(){
                super("Previous page");
            }

            public void actionPerformed(ActionEvent ae){
                if (pageRenderer != null)
                    pageRenderer.previousPage();
                showTitle();
            }
        }

        class FilePageRenderer extends JComponent implements Printable{
            private static final long serialVersionUID = 1L;
            private int       currentPageIndex;
            private Vector    lineVector;
            private Vector    pageVector;
            private Font      font;
            private int       fontSize;
            private Dimension preferredSize;

            public FilePageRenderer(File file, PageFormat pageFormat) throws IOException{
                fontSize = 12;
                font = new Font("Serif", Font.PLAIN, fontSize);
                BufferedReader in = new BufferedReader(new FileReader(file));
                String line;
                lineVector = new Vector();
                while ((line = in.readLine()) != null)
                    lineVector.addElement(line);
                in.close();
                pageInit(pageFormat);
            }

            public void pageInit(PageFormat pageFormat){
                currentPageIndex = 0;
                pageVector = new Vector();
                float y = fontSize;
                Vector page = new Vector();
                for (int i = 0; i < lineVector.size(); i++)
                {
                    String line = (String) lineVector.elementAt(i);
                    page.addElement(line);
                    y += fontSize;
                    if (y + fontSize * 2 > pageFormat.getImageableHeight())
                    {
                        y = 0;
                        pageVector.addElement(page);
                        page = new Vector();
                    }
                }
                if (page.size() > 0)
                    pageVector.addElement(page);
                preferredSize = new Dimension((int) pageFormat.getImageableWidth(),
                                              (int) pageFormat.getImageableHeight());
                repaint();
            }

            public void paintComponent(Graphics g) {
                Graphics2D g2 = (Graphics2D) g;
                java.awt.geom.Rectangle2D r = new java.awt.geom.Rectangle2D.Float(0,
                                                                                  0,
                                                                                  preferredSize.width,
                                                                                  preferredSize.height);
                g2.setPaint(Color.white);
                g2.fill(r);
                Vector page = (Vector) pageVector.elementAt(currentPageIndex);
                g2.setFont(font);
                g2.setPaint(Color.black);
                float x = 0;
                float y = fontSize;
                for (int i = 0; i < page.size(); i++){
                    String line = (String) page.elementAt(i);
                    if (line.length() > 0)
                        g2.drawString(line, (int) x, (int) y);
                    y += fontSize;
                }
            }

            public int print(Graphics g, PageFormat pageFormat, int pageIndex){
                if (pageIndex >= pageVector.size())
                    return NO_SUCH_PAGE;
                int savedPage = currentPageIndex;
                currentPageIndex = pageIndex;
                Graphics2D g2 = (Graphics2D) g;
                g2.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
                paint(g2);
                currentPageIndex = savedPage;
                return PAGE_EXISTS;
            }

            public Dimension getPreferredSize(){
                return preferredSize;
            }

            public int getCurrentPage(){
                return currentPageIndex;
            }

            public int getNumPages(){
                return pageVector.size();
            }

            public void nextPage() {
                if (currentPageIndex < pageVector.size() - 1)
                    currentPageIndex++;
                repaint();
            }
            public void previousPage(){
                if (currentPageIndex > 0)
                    currentPageIndex--;
                repaint();
            }
        }
    }

【PrintPreview.java】的源码:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Insets;
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 javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JToolBar;
import javax.swing.border.MatteBorder;

public class PrintPreview extends JFrame
{
    private static final long serialVersionUID = 1L;
    protected int              m_wPage;
    protected int              m_hPage;
    protected int              m_orientation;
    protected Printable        m_target;
    protected JComboBox        m_cbScale;
    protected PreviewContainer m_preview;

    public PrintPreview(Printable target)
    {
        this(target, "Print   Preview ", PageFormat.PORTRAIT);
    }

    public PrintPreview(Printable target, String title, int orientation)
    {
        super(title);
        setSize(600, 400);
        getContentPane().setLayout(new BorderLayout());
        m_target = target;
        m_orientation = orientation;
        JToolBar tb = new JToolBar();
        JButton bt = new JButton("Print ", new ImageIcon("print.gif "));
        ActionListener lst = new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                try
                {
                    PrinterJob prnJob = PrinterJob.getPrinterJob();
                    PageFormat pageFormat = prnJob.defaultPage();
                    pageFormat.setOrientation(m_orientation);
                    prnJob.setPrintable(m_target, pageFormat);
                    if (!prnJob.printDialog())
                        return;
                    setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
                    prnJob.print();
                    setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
                    dispose();
                } catch (PrinterException ex)
                {
                    ex.printStackTrace();
                    System.err.println("Printing   error:   " + ex.toString());
                }
            }
        };
        bt.addActionListener(lst);
        bt.setAlignmentY(0.5f);
        bt.setMargin(new Insets(4, 6, 4, 6));
        tb.add(bt);
        bt = new JButton("Close ");
        lst = new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                dispose();
            }
        };
        bt.addActionListener(lst);
        bt.setAlignmentY(0.5f);
        bt.setMargin(new Insets(2, 6, 2, 6));
        tb.add(bt);
        String[] scales = { "10%", "25%", "50%", "100%" };

        m_cbScale = new JComboBox(scales);
        lst = new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                String str = m_cbScale.getSelectedItem().toString();
                if (str.endsWith("%"))
                    str = str.substring(0, str.length() - 1);
                str = str.trim();
                int scale = 0;
                try
                {
                    scale = Integer.parseInt(str);
                } catch (NumberFormatException ex)
                {
                    return;
                }
                int w = (int) (m_wPage * scale / 100);
                int h = (int) (m_hPage * scale / 100);
                Component[] comps = m_preview.getComponents();
                for (int k = 0; k < comps.length; k++)
                {
                    if (!(comps[k] instanceof PagePreview))
                        continue;
                    PagePreview pp = (PagePreview) comps[k];
                    pp.setScaledSize(w, h);
                }
                m_preview.doLayout();
                m_preview.getParent().getParent().validate();
            }
        };
        m_cbScale.addActionListener(lst);
        m_cbScale.setMaximumSize(m_cbScale.getPreferredSize());
        m_cbScale.setEditable(true);
        tb.addSeparator();
        tb.add(m_cbScale);
        getContentPane().add(tb, BorderLayout.NORTH);
        m_preview = new PreviewContainer();
        PrinterJob prnJob = PrinterJob.getPrinterJob();
        PageFormat pageFormat = prnJob.defaultPage();
        pageFormat.setOrientation(m_orientation);
        if (pageFormat.getHeight() == 0 || pageFormat.getWidth() == 0)
        {
            System.err.println("Unable   to   determine   default   page   size ");
            return;
        }
        m_wPage = (int) (pageFormat.getWidth());
        m_hPage = (int) (pageFormat.getHeight());
        int scale = 10;
        int w = (int) (m_wPage * scale / 100);
        int h = (int) (m_hPage * scale / 100);
        int pageIndex = 0;
        try
        {
            while (true)
            {
                BufferedImage img = new BufferedImage(m_wPage, m_hPage, BufferedImage.TYPE_INT_RGB);
                Graphics g = img.getGraphics();
                g.setColor(Color.white);
                g.fillRect(0, 0, m_wPage, m_hPage);
                if (target.print(g, pageFormat, pageIndex) != Printable.PAGE_EXISTS)
                    break;
                PagePreview pp = new PagePreview(w, h, img);
                m_preview.add(pp);
                pageIndex++;
            }
        } catch (PrinterException e)
        {
            e.printStackTrace();
            System.err.println("Printing   error:   " + e.toString());
        }
        JScrollPane ps = new JScrollPane(m_preview);
        getContentPane().add(ps, BorderLayout.CENTER);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setVisible(true);
    }

    class PreviewContainer extends JPanel
    {
        private static final long serialVersionUID = 1L;
        protected int H_GAP = 16;
        protected int V_GAP = 10;

        public Dimension getPreferredSize()
        {
            int n = getComponentCount();
            if (n == 0)
                return new Dimension(H_GAP, V_GAP);
            Component comp = getComponent(0);
            Dimension dc = comp.getPreferredSize();
            int w = dc.width;
            int h = dc.height;
            Dimension dp = getParent().getSize();
            int nCol = Math.max((dp.width - H_GAP) / (w + H_GAP), 1);
            int nRow = n / nCol;
            if (nRow * nCol < n)
                nRow++;
            int ww = nCol * (w + H_GAP) + H_GAP;
            int hh = nRow * (h + V_GAP) + V_GAP;
            Insets ins = getInsets();
            return new Dimension(ww + ins.left + ins.right, hh + ins.top + ins.bottom);
        }

        public Dimension getMaximumSize()
        {
            return getPreferredSize();
        }

        public Dimension getMinimumSize()
        {
            return getPreferredSize();
        }

        public void doLayout()
        {
            Insets ins = getInsets();
            int x = ins.left + H_GAP;
            int y = ins.top + V_GAP;
            int n = getComponentCount();
            if (n == 0)
                return;
            Component comp = getComponent(0);
            Dimension dc = comp.getPreferredSize();
            int w = dc.width;
            int h = dc.height;
            Dimension dp = getParent().getSize();
            int nCol = Math.max((dp.width - H_GAP) / (w + H_GAP), 1);
            int nRow = n / nCol;
            if (nRow * nCol < n)
                nRow++;
            int index = 0;
            for (int k = 0; k < nRow; k++)
            {
                for (int m = 0; m < nCol; m++)
                {
                    if (index >= n)
                        return;
                    comp = getComponent(index++);
                    comp.setBounds(x, y, w, h);
                    x += w + H_GAP;
                }
                y += h + V_GAP;
                x = ins.left + H_GAP;
            }
        }
    }

    class PagePreview extends JPanel
    {
        private static final long serialVersionUID = 1L;
        protected int   m_w;
        protected int   m_h;
        protected Image m_source;
        protected Image m_img;

        public PagePreview(int w, int h, Image source)
        {
            m_w = w;
            m_h = h;
            m_source = source;
            m_img = m_source.getScaledInstance(m_w, m_h, Image.SCALE_SMOOTH);
            m_img.flush();
            setBackground(Color.white);
            setBorder(new MatteBorder(1, 1, 2, 2, Color.black));
        }

        public void setScaledSize(int w, int h)
        {
            m_w = w;
            m_h = h;
            m_img = m_source.getScaledInstance(m_w, m_h, Image.SCALE_SMOOTH);
            repaint();
        }

        public Dimension getPreferredSize()
        {
            Insets ins = getInsets();
            return new Dimension(m_w + ins.left + ins.right, m_h + ins.top + ins.bottom);
        }

        public Dimension getMaximumSize()
        {
            return getPreferredSize();
        }

        public Dimension getMinimumSize()
        {
            return getPreferredSize();
        }

        public void paint(Graphics g)
        {
            g.setColor(getBackground());
            g.fillRect(0, 0, getWidth(), getHeight());
            g.drawImage(m_img, 0, 0, this);
            paintBorder(g);
        }
    }
}
时间: 2024-10-06 22:11:52

JAVA实现打印机的相关文章

java连接打印机

package com.gdpe.ws.bpmn.web;import java.io.File;import java.io.FileInputStream; import javax.print.Doc;import javax.print.DocFlavor;import javax.print.DocPrintJob;import javax.print.PrintService;import javax.print.PrintServiceLookup;import javax.pri

Java 调用打印机打印图片

import java.io.FileInputStream; import java.io.IOException; import javax.print.Doc; import javax.print.DocFlavor; import javax.print.DocPrintJob; import javax.print.PrintException; import javax.print.PrintService; import javax.print.PrintServiceLooku

Java调用打印机打印指定路径图片

依赖 javax.print package com.xgt.util; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.FileInputStream; import java.io.IOException; import javax.print.Doc; import javax.print.DocFlavor; impo

java 调用打印机打印文件

/** * 进行打印 * * @param file * @param saveFile * @param preFix * @param formatFile * @return * @throws NoOfficeException */ public static void doPrintDoc(File file) { if (file == null || !file.exists()) { return; } // 获取文件后缀名 int index = file.getName()

关于这两天研究Java打印pdf方法的记录

这两天在研究Java调用打印机打印PDF文件的方法,学到了不少东西,特别来记录一下. 关于Java打印网上最多的而且也是Java正统的打印方法就是使用PrintService,一套比較标准的打印代码例如以下: public class PrintDemo { public static void main(String[] args) { JFileChooser fileChooser = new JFileChooser(); // 创建打印作业 int state = fileChoose

java8改进的接口

java8对接口进行了改进,允许在接口中定义默认方法,默认方法可以提供方法实现. 5.6.1 接口的概念 类是一种具体实现类,而接口定义了一种规范,接口定义了某一批类所需要遵守的规范,接口不关心这些类的内部状态数据,也不关心这些类里方法的实现细节,它只规定这批类里必须提供某些方法,提供这些方法的类就可满足实际需要. 接口是从多个类中抽象出来的规范,接口不提供任何实现.接口体现的是规范和实现分离的设计哲学. 5.6.2 java中接口的定义 示例:[修饰符]interface 接口名 extend

设计模式(2)_代理模式 ————— 控制对象访问

设计模式(2)_代理模式 ----- 控制对象访问 一.动机 需求 现在有这样一个需求:有一个出版社,该出版社有一个工厂,专门用来生产制造图书,该工厂里有很多台生产制造图书的机器.每个机器有自己的位置坐标,用 int表示,机器的状态,{正在工作,暂停,故障},已经印刷了多少页图书.在出版社 在工厂 厂长的电脑屏幕上,可以随时打印出任何一台机器的报告信息(report infomation). 下来 我们用代码实现这个需求: PrinterMachine.java package com.crg;

Java jacob调用打印机打印word文档

前面说了Java如何生成复杂的Word文档,今年记录下Java如何调用打印机打印word文档. 起初用的是自带的PrintJob,但是系统提供的打印机制比不成熟完整.网上的代码也是千篇一律,在我的打印设备Canon iR2525/2530 UFRII LT上,我能获取到打印机的各属性,当前任务数.但是打印机没反应. 可参考这两篇文章: http://www.360doc.com/content/05/0916/11/332_12789.shtml http://www.ibm.com/devel

android java epson串口打印机

package com.common.util.portprinter; import java.io.IOException; import java.io.OutputStream; import com.common.util.PrinterParameterConf; /** * @author ChenMing * */ public class PortPrinterBase {     private OutputStream out;     protected int line