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);
}
}
}
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,但是系统提供的打印机制并不成熟完整.网上的代码也是千篇一律,在我的打印 ...
随机推荐
- C语言操作内存
炒了个栗子 #include <stdio.h> #define N1 (5) #define N2 (7) #define N3 (3) int main(){ int *ip; int ...
- SharePoint GroupedItemPicker Control
这个控件SharePoint用来选择Field ,和Content Type, 以下是一个完整的示例. <SharePoint:GroupedItemPicker ID="Select ...
- M3U8格式讲解及实际应用分析
M3U8格式讲解及实际应用分析 M3U8有啥好处 ? 网上搜索了一下,大家众说纷纭,个人理解主要是可以做多码率的适配,根据网络带宽,客户端会选择一个适合自己码率的文件进行播放,保证视频流的流畅. 在I ...
- ORACLE 定时执行存储过程
推荐用dbms_scheduler方式更好 (2012-11-19注) /* 查询: select job,broken,what,interval,t.* from user_jobs t; job ...
- ROS系统python代码测试之rostest
ROS系统中提供了测试框架,可以实现python/c++代码的单元测试,python和C++通过不同的方式实现, 之后的两篇文档分别详细介绍各自的实现步骤,以及测试结果和覆盖率的获取. ROS系统中p ...
- Expression Blend4经验分享:文字公告无缝循环滚动效果
这次分享一个类似新闻公告板的无缝循环滚动效果,相信很多项目都会应用到这个效果.之前我也百度了一下,网上的一些Silverlight的文字或图片滚动效果,都是一次性滚动的,如果要做到无缝循环滚动,多数要 ...
- JQuery实现资讯上下滚动悬停效果
第一步:使用repeater绑定一个table. <table width="530" id="rollBar"> <asp:Repeater ...
- <实训|第六天>偷偷让新手的Linux无限重启附linux主机名称不是随便乱改的!
先说个事情:这几天我正在忙一个项目的设计,8月1号之前要弄出来,所以每天都要弄到很晚,可能更新就有点跟不上了,不过我如果有时间的话,我就更新,没时间的话,我会在8月1号之后统一更新出来,希望大家谅解! ...
- 突破自我,开源NetWorkSocket通讯组件
前言 在<化茧成蝶,开源NetWorkSocket通讯组件>发表之后,收到大家很多个star,在此感谢!更可贵的是,一些网友提出了许多好建议,经过一些时间的思考,决定将NetworkSoc ...
- Web Audio API 实现音频可视化
声明:本文为原创文章,如需转载,请注明来源WAxes,谢谢! 一转眼就已经有三个月没写博客了,毕业季事情确实多,现在也终于完全毕业了,博客还是不能落下.偶尔还是要写一下. 玩HTML5的Audio A ...