对于java的打印问题各种书上谈的很少我想主要原因可能是java的打印功能太弱了没有什么可介绍的 最近我因为工作的关系用到了java的打印图象功能不过因为缺少可参考的例子和教材我只有查看jdk 的API文档的确不是很爽下面就把我的程序给大家讲讲顺便白话一下java的打印(是jdk的) java的打印类都在javaawtprint包下主要有四个类和两个interfacePrinterJobPageFormat PaperBook; PrintablePageable(详细的情况请查看jdk的API文档我只讲我程序中用到的部分)
Interface包括 Printable主要是用来打印的接口在打印的时候它的print()方法不断地被调用直到 返回NO_SUCH_PAGE为止
PrinterJob:初始化打印操作可以显示系统特定的打印对话框例如windows的
PageFormat:描述可打印区例如我的程序用的几个方法
public double getImageableX();
public double getImageableY();
public double getImageableWidth();
public double getImageableHeight();
package jinicupprinter;
import javaawt*;
import javaawtprint*;
import javaawtevent*;
import javaxswingJPanel;
import javaxswingJFrame;
import javaxswingImageIcon;
import javaio*;
/**********************************
* Implemenation of the printer service
***********************************/
public class PrinterImpl extends JPanel
implements Printable {
private Image image;
private PrinterJob printJob;
private double xywh;
private int imagewimageh;
PrinterImpl () {
printJob = PrinterJobgetPrinterJob();
printJobsetPrintable(this);
printJobprintDialog();
}
public int print (Graphics graphics PageFormat pageFormat int pageIndex) throws PrinterException {
Systemoutprintln(pageIndex+pageIndex);
if (pageIndex >= ) {
return PrintableNO_SUCH_PAGE;
}
x = pageFormatgetImageableX();
y = pageFormatgetImageableY();
w = pageFormatgetImageableWidth();
h = pageFormatgetImageableHeight();
if(imagew >= imageh){
h=w*imageh/imagew;
}else{
w=h*imagew/imageh;
}
Systemoutprintln(x+ +y);
Systemoutprintln(w+ +h);
drawGraphics(graphics);
return PrintablePAGE_EXISTS;
}
public void paint (Graphics graphics) {
drawGraphics(graphics);
}
private void drawGraphics (Graphics graphics) {
graphicsdrawImage(image (int)x(int)y(int)w(int)h null);
// graphicsdrawOval( );
}
/**********************************
* starts the printing
* @param byteArrayOfJPEGFile a valid byte array of a jpg file (can be directly from the camera)
***********************************/
public void printByteArray (byte[] byteArrayOfJPEGFile) {
// Toolkit tool = ToolkitgetToolkit();
// image=toolcreateImage(byteArrayOfJPEGFile);
image = (new ImageIcon(byteArrayOfJPEGFile))getImage();
imagew=imagegetWidth(null);
imageh=imagegetHeight(null);
Systemoutprintln(imagew+ +imageh);
Systemoutprintln(kkk);
try {
Systemoutprintln(start printing);
printJobprint();
Systemoutprintln(printing was spooled to the printer);
} catch (Exception ex) {
Systemoutprintln(ex);
}
return;
}
/**********************************
* main method only for text purposes
* @param args no args are used
***********************************/
public static void main (String[] args) {
PrinterImpl pi = new PrinterImpl();
try {
FileInputStream fs = new FileInputStream(e:/testjpg);
Systemoutprintln(fsavailable());
byte[] array = new byte[fsavailable()];
fsread(array);
piprintByteArray(array);
} catch (Exception e) {
Systemoutprintln(e);
}
}
}