I\'m trying to get some information about the printers on my system.
On Windows and Linux, with this code, only the PrinterName
attribute is filled:
There are other PrintServiceAttribute
implementations, but if you want to fetch more...
This is a dirty code only, you can also fetch unsupported values for doc flavor:
PrintService[] printServices =
PrintServiceLookup.lookupPrintServices(null, null); //get printers
for (PrintService printService : printServices) {
System.out.println("Found print service: " + printService);
Set<Attribute> attribSet = new LinkedHashSet<Attribute>();
Class<? extends Attribute>[] supportedAttributeCategories = (Class<? extends Attribute>[]) printService.getSupportedAttributeCategories();
for (Class<? extends Attribute> category : supportedAttributeCategories) {
DocFlavor[] flavors = printService.getSupportedDocFlavors();
for (DocFlavor flavor : flavors) {
Object supportedAttributeValues = printService.getSupportedAttributeValues(category, flavor, printService.getAttributes());
if (supportedAttributeValues instanceof Attribute) {
Attribute attr = (Attribute) supportedAttributeValues;
attribSet.add(attr);
} else if (supportedAttributeValues != null) {
Attribute[] attrs = (Attribute[]) supportedAttributeValues;
for (Attribute attr : attrs) {
attribSet.add(attr);
}
}
}
}
for (Attribute attr : attribSet) {
System.out.println(attr.getName());
System.out.println(printService.getDefaultAttributeValue(attr.getCategory()));
}
}
Note: You may see repeated values, but they can be filtered.
Below is a modular, more understandable version of the code provided in hGx's answer:
public static Set<Attribute> getAttributes(PrintService printer) {
Set<Attribute> set = new LinkedHashSet<Attribute>();
//get the supported docflavors, categories and attributes
Class<? extends Attribute>[] categories = (Class<? extends Attribute>[]) printer.getSupportedAttributeCategories();
DocFlavor[] flavors = printer.getSupportedDocFlavors();
AttributeSet attributes = printer.getAttributes();
//get all the avaliable attributes
for (Class<? extends Attribute> category : categories) {
for (DocFlavor flavor : flavors) {
//get the value
Object value = printer.getSupportedAttributeValues(category, flavor, attributes);
//check if it's something
if (value != null) {
//if it's a SINGLE attribute...
if (value instanceof Attribute)
set.add((Attribute) value); //...then add it
//if it's a SET of attributes...
else if (value instanceof Attribute[])
set.addAll(Arrays.asList((Attribute[]) value)); //...then add its childs
}
}
}
return set;
}
This will return a Set
with the Attributes
discovered of the given printer.
Note: Duplicate values may appear. They can be filtered, however.