可能正在使用PrintServiceLookup?
此类的实现为特定类型的打印服务(通常等同于打印机)提供查找服务。
DocFlavor flavor = DocFlavor.INPUT_STREAM.POSTSCRIPT;
PrintRequestAttributeSet aset = new HashPrintRequestHashAttributeSet();
aset.add(MediaSizeName.ISO_A4);
PrintService[] pservices =PrintServiceLookup.lookupPrintServices(flavor, aset);
if (pservices.length > 0) {
DocPrintJob pj = pservices[0].createPrintJob();
//....
}
注意:如果有打印机,PrintService 的数量应至少为一个。如果有实际打印机,则可能至少有 2 个,因为您可以在计算机上安装纯软件打印机。另见this thread。
取决于平台和jdk,它可以有some bug,否则,下面的方法应该至少列出打印机:
import java.awt.print.*;
import javax.print.*;
import javax.print.attribute.*;
import java.text.*;
import javax.print.attribute.standard.*;
public class ShowPrinters {
public ShowPrinters() {
}
public static void main(String[] args) {
DocFlavor myFormat = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
PrintService[] services =PrintServiceLookup.lookupPrintServices(myFormat, aset);
System.out.println("The following printers are available");
for (int i=0;i<services.length;i++) {
System.out.println(" service name: "+services[i].getName());
}
}
}
在这个eclipse code source,你已经看到使用PrinterState来检查打印机是否真的连接了:
AttributeSet attributes = new HashPrintServiceAttributeSet(
new PrinterName(printerName, Locale.getDefault()));
PrintService[] services = PrintServiceLookup.lookupPrintServices(
DocFlavor.SERVICE_FORMATTED.PRINTABLE,
attributes);
PrintService printService = services[0];
PrintServiceAttributeSet printServiceAttributes = printService.getAttributes();
PrinterState printerState = (PrinterState) printServiceAttributes.get(PrinterState.class);
检查printerState 是否不为空。注意:这可能还不够(请参阅this thread)。