如何使用Java检测打印机是否连接到您的计算机?

时间:2009-09-07 06:22:08

标签: java

我正在使用swing Java创建一个GUI。我必须使用一个按钮“打印”,它将直接开始打印我设置的文件而不打开默认的打印对话框。 我必须先检查打印机是否连接到我的电脑上?

1 个答案:

答案 0 :(得分:1)

可能正在使用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的数量应该至少为1。如果有实际打印机,则可能至少为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)。