我这里有以前收藏的代码,两个类实现了简易的文本打印机的功能,包括预览。简单跟你说一下。
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实现打印机的更多相关文章
-
Java读取打印机自定义纸张.
打印出现截断? 对于自定义纸张打印, 一定要先在打印机配置那边添加, 不然会出现截断. 例如打印1000*500, 出来是正常的, 打印216*139, 出现了截断. 因为java默认的打印, 会从打 ...
-
java 调用打印机 打印服务
import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import javax ...
-
Java调用打印机打印指定路径图片
依赖 javax.print package com.xgt.util; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; ...
-
java之打印机服务通俗做法
javax.print包是API的主包,其中包含的类和接口能够让你:1)发现打印服务(Print Services)2)指定打印数据的格式 3)从一个打印服务创建打印工作(print jobs) 4) ...
-
关于这两天研究Java打印pdf方法的记录
这两天在研究Java调用打印机打印PDF文件的方法,学到了不少东西,特别来记录一下. 关于Java打印网上最多的而且也是Java正统的打印方法就是使用PrintService,一套比較标准的打印代码例 ...
-
Java调用PDFBox打印自定义纸张PDF
打印对象 一份设置为A3纸张, 页面边距为(10, 10, 10, 10)mm的PDF文件. PageFormat 默认PDFPrintable无法设置页面大小. PDFPrintable print ...
-
关于Jvm的见解(一)
Jvm组成结构 硬件体系(如Intel体系.spac等)——>操作系统(如Windows.Linux等)——>Java Virtual Machine 所以虚拟机与硬件系统并没有直接的交 ...
-
Spark案例分析
一.需求:计算网页访问量前三名 import org.apache.spark.rdd.RDD import org.apache.spark.{SparkConf, SparkContext} /* ...
-
Java jacob调用打印机打印word文档
前面说了Java如何生成复杂的Word文档,今年记录下Java如何调用打印机打印word文档. 起初用的是自带的PrintJob,但是系统提供的打印机制并不成熟完整.网上的代码也是千篇一律,在我的打印 ...
随机推荐
-
使用CSS3制作立体效果的导航菜单
效果如下: 也可以点击网址查看效果:http://keleyi.com/keleyi/phtml/html5/12.htm 请使用支持CSS3的浏览器访问本页面,获得更好效果. 源代码: <st ...
-
RHEL 5 安装phpqrcode生成二维码
VMWARE中全新安装(默认)RHEL. 之后,yum 安装备apache/php 下载并上传phpqrcode 1.1.4版本,并将其解压至/var/www/html/phpqrcode (去掉ip ...
-
[第四版]用getaddrinfo设置tcp基本连接属性
getaddrinfo getaddrinfo的一个重要功能, 很方便的构造struct sockaddr_in对象, 把繁琐的构造过程隐藏起来 getaddrinfo兼有gethostbyname和 ...
-
Canvas处理头像上传
未分类 最近社区系统需要支持移动端,其中涉及到用户头像上传,头像有大中小三种尺寸,在PC端,社区用Flash来处理头像编辑和生成,但该Flash控件的界面不友好而且移动端对Flash的支持不好,考虑到 ...
-
x264_param_t结构
typedef struct x264_param_t { unsigned int cpu; // CPU 标志位 int i_threads; // 并行编码多帧; 线程数,为0则自动多线程编码 ...
-
零行代码为App添加异常加载占位图
前文提要 近期准备重构项目,需要重写一些通用模块,正巧需要设置App异常加载占位图的问题,心血来潮设想是否可以零行代码解决此问题,特在此分享实现思路. 思路分享 对于App占位图,通常需要考虑的控件有 ...
-
SQL模糊查询条件的四种匹配模式
执行数据库查询时,有完整查询和模糊查询之分. 一般模糊语句格式如下: SELECT 字段 FROM 表 WHERE 某字段 LIKE 条件 其中关于条件,SQL提供了四种匹配模式: 1.% :表示任意 ...
-
linux光标操作
看一个真正的专家操作命令行绝对是一种很好的体验-光标在单词之间来回穿梭,命令行不同的滚动. 在这里强烈建立适应GUI节目的开发者尝试一下在提示符下面工作. 但是事情也不是那么简单,还是需要知道“如何去 ...
-
深度学习原理与框架-Alexnet(迁移学习代码) 1.sys.argv[1:](控制台输入的参数获取第二个参数开始) 2.tf.split(对数据进行切分操作) 3.tf.concat(对数据进行合并操作) 4.tf.variable_scope(指定w的使用范围) 5.tf.get_variable(构造和获得参数) 6.np.load(加载.npy文件)
1. sys.argv[1:] # 在控制台进行参数的输入时,只使用第二个参数以后的数据 参数说明:控制台的输入:python test.py what, 使用sys.argv[1:],那么将获得w ...
-
centos 7 一键安装gitlab
# cat /etc/redhat-release CentOS release 6.5 (Final) # strings /lib64/libc.so.6 |grep GLIBC_ 首先升级 如果 ...