我这里有以前收藏的代码,两个类实现了简易的文本打印机的功能,包括预览。简单跟你说一下。
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); } } }