本文主要介绍Java中调用打印机打印代码,可以通过查找(LookUpPrint和/PrintServiceLookup.lookupPrintServices)打印机名称找到打印机进行打印。

1、 通过LookUpPrint查找

//设置打印属性 构造一个新的空打印请求属性集。                
PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
pras.add(new Copies(3));//打印份数,3份
//设置打印数据的格式        DocFlavor.BYTE_ARRAY.PNG     MIME 类型 = "image/png",打印数据表示形式类名 = "[B"(byte 数组)的 DocFlavor。
DocFlavor flavor = DocFlavor.BYTE_ARRAY.PNG;
//创建打印数据
Doc myDoc = new SimpleDoc(new File(""), flavor, null); 
//查找所有符合条件的打印服务                         lookupPrintServices(flavor, pras);查找能够打印指定 DocFlavor 的 PrintService。
PrintService[] printService = PrintServiceLookup.lookupPrintServices(flavor, pras);
//将所有查找出来的打印机与自己想要的打印机进行匹配,找出自己想要的打印机 
LookUpPrint p=new LookUpPrint();
PrintService myPrintService = p.GetPrintService("printName");
 //可以输出打印机的各项属性 
AttributeSet att = myPrintService.getAttributes(); 
for (Attribute a : att.toArray()) { 
    System.out.println("attributeName:"+a.getName()+ "     attributeValue:" +  att.get(a.getClass()).toString()); 
}
if (myPrintService != null) { 
    DocPrintJob job = myPrintService.createPrintJob();//创建文档打印作业 
    try { 
        job.print(myDoc, pras);//打印文档 
    } catch (Exception pe) { 
        pe.printStackTrace(); 
    } 
}else{
    System.out.println("no printer services found");
} 

2、通过PrintServiceLookup.lookupPrintServices查找打印

public void print()
{
PrinterJob printerJob = PrinterJob.getPrinterJob();
Book book = new Book();
book.append(new MyPrintTest(), printerJob.defaultPage());
printerJob.setPageable(book);
HashAttributeSet hs = new HashAttributeSet();
String printerName="EPSON TM-U220 Receipt";
hs.add(new PrinterName(printerName,null));
PrintService[] pss = PrintServiceLookup.lookupPrintServices(null, hs);
if(pss.length==0)
{
System.out.println("无法找到打印机:"+printerName);
return ;
}
try
{
printerJob.setPrintService(pss[0]);
printerJob.print();
}
catch (PrinterException ex)
{
System.out.println(ex.getMessage());
}
}

3、测试打印的代码

private static void doTest() {
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
aset.add(Chromaticity.MONOCHROME);
MediaSize isoA5Size = MediaSize.getMediaSizeForName(MediaSizeName.ISO_A5);
float[] size = isoA5Size.getSize(Size2DSyntax.INCH);
Paper paper = new Paper();
paper.setSize(size[0] * 72.0, size[1] * 72.0);
paper.setImageableArea(0.0, 0.0, size[0] * 72.0, size[1] * 72.0);
PageFormat pf = new PageFormat();
pf.setPaper(paper);
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(new WrongPaperPrintingTest(), job.validatePage(pf));
if (job.printDialog()) {
try {
job.print(aset);
} catch (PrinterException pe) {
throw new RuntimeException(pe);
}
}
}