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

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);
}
}
}

JAVA实现打印机的更多相关文章

  1. Java读取打印机自定义纸张.

    打印出现截断? 对于自定义纸张打印, 一定要先在打印机配置那边添加, 不然会出现截断. 例如打印1000*500, 出来是正常的, 打印216*139, 出现了截断. 因为java默认的打印, 会从打 ...

  2. java 调用打印机 打印服务

    import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import javax ...

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

    依赖 javax.print package com.xgt.util; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; ...

  4. java之打印机服务通俗做法

    javax.print包是API的主包,其中包含的类和接口能够让你:1)发现打印服务(Print Services)2)指定打印数据的格式 3)从一个打印服务创建打印工作(print jobs) 4) ...

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

    这两天在研究Java调用打印机打印PDF文件的方法,学到了不少东西,特别来记录一下. 关于Java打印网上最多的而且也是Java正统的打印方法就是使用PrintService,一套比較标准的打印代码例 ...

  6. Java调用PDFBox打印自定义纸张PDF

    打印对象 一份设置为A3纸张, 页面边距为(10, 10, 10, 10)mm的PDF文件. PageFormat 默认PDFPrintable无法设置页面大小. PDFPrintable print ...

  7. 关于Jvm的见解(一)

    Jvm组成结构 硬件体系(如Intel体系.spac等)——>操作系统(如Windows.Linux等)——>Java Virtual Machine  所以虚拟机与硬件系统并没有直接的交 ...

  8. Spark案例分析

    一.需求:计算网页访问量前三名 import org.apache.spark.rdd.RDD import org.apache.spark.{SparkConf, SparkContext} /* ...

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

    前面说了Java如何生成复杂的Word文档,今年记录下Java如何调用打印机打印word文档. 起初用的是自带的PrintJob,但是系统提供的打印机制并不成熟完整.网上的代码也是千篇一律,在我的打印 ...

随机推荐

  1. 基于jquery的消息提示框toastr.js

    //消息提示全局配置 toastr.options = { "closeButton": false,//是否配置关闭按钮 "debug": false,//是 ...

  2. 在移动端如何选择字体大小和布局的单位,px或dp?

    android开发中,文字大小的单位是sp,非文字的尺寸单位用dp,但是我们在设计稿用的单位是px.这些单位如何换算,是设计师.开发者需要了解的关键. 简单理解的话,px(像素)是我们UI设计师在PS ...

  3. linux下截取给定路径中的目录部分

    在日常运维中,有时会要求截取一个路径中的目录部分.截取目录的方法,有以下两种:1)dirname命令(最常用的方法):用于取给定路径的目录部分.很少直接在shell命令行中使用,一般把它用在shell ...

  4. asp.net core 日志

    日志输出是应用程序必不可少的部分,log4net,nlog这些成熟的组件在之前的项目中被广泛使用,在asp.net core的项目中没有找到与之对应的log4net版本,nlog对core提供了很好的 ...

  5. git 本地分支与远程分支

    github上已经有master分支 和dev分支 在本地 git checkout -b dev 新建并切换到本地dev分支 git pull origin dev 本地分支与远程分支相关联 在本地 ...

  6. Ruby中 使用Builder Xml Markup 操作XML

    =begin Ruby中 使用Xml Markup 轻松的对XML文档操作, 项目地址:http://builder.rubyforge.org/ 使用之前我们需要安装Builder xml mark ...

  7. Handler 消息传递机制

    1,Handler 的概念Handler 是用来干什么的?1)执行计划任务,可以在预定的时间执行某些任务,可以模拟定时器 2)线程间通信.在Android的应用启动时,会创建一个主线程,主线程会创建一 ...

  8. 学习C++.Primer.Plus 6 分支语句和逻辑操作符

    ||. &&操作符是一个顺序点 < 操作符从左向右结合 ; < age < )//17<age为true, = 1,肯定 < 27.所以为整个条件为tru ...

  9. ajax请求过程中下载文件在火狐下的兼容问题

    项目中碰到的问题,记录如下. 需求很简单,点击一个文件链接下载该文件,同时向后台发送请求.需求很常见,用户点击下载后通常要进行下载量的统计,统计的话可以利用 script标签 或者 img标签(图片p ...

  10. 求连续最大子序列积 - leetcode. 152 Maximum Product Subarray

    题目链接:Maximum Product Subarray solutions同步在github 题目很简单,给一个数组,求一个连续的子数组,使得数组元素之积最大.这是求连续最大子序列和的加强版,我们 ...