Java如何获取打印服务属性集?

此示例演示如何使用javax.printAPI获取打印服务的属性集。首先,我们使用PrintServiceLookup该类为当前机器找到默认打印机。这将为我们提供一个PrintService对象,null如果未找到打印服务,则可能为该对象。

最后一步是通过调用的getAttributes()方法来获取打印服务属性集PrintService。我们可以AttributeSet使用toArray()方法将返回的值转换为数组并对其进行迭代。

package org.nhooo.example.print;

import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.attribute.Attribute;
import javax.print.attribute.AttributeSet;

public class PrinterAttribute {
    public static void main(String[] args) {
        // 找到此环境的默认打印服务。
        PrintService printer = PrintServiceLookup.lookupDefaultPrintService();

        if (printer != null) {
            // 获取打印服务的属性集。
            AttributeSet attributes = printer.getAttributes();
            for (Attribute a : attributes.toArray()) {
                String name = a.getName();
                String value = attributes.get(a.getClass()).toString();
                System.out.println(name + " : " + value);
            }
        }
    }
}

该程序的示例结果是:

printer-is-accepting-jobs : accepting-jobs
color-supported : supported
printer-name : HP LaserJet P1005
queued-job-count : 0