2011-04-06 21 views
7

Estoy tratando de obtener información sobre las impresoras en mi sistema.
En Windows y Linux, con este código, sólo el atributo PrinterName está lleno:Información extendida de la impresora en Java

PrintService[] printServices = PrintServiceLookup.lookupPrintServices(null,null); 
for(PrintService printService : printServices) { 
    log.info("Found print service: "+printService); 
    log.info(printService.getAttribute(PrinterName.class)); 
    log.info(printService.getAttribute(PrinterLocation.class)); 
    log.info(printService.getAttribute(PrinterMakeAndModel.class)); 
    log.info(printService.getAttribute(PrinterMessageFromOperator.class)); 
    log.info(printService.getAttribute(PrinterMoreInfo.class)); 
    log.info(printService.getAttribute(PrinterMoreInfoManufacturer.class)); 
    log.info(printService.getAttribute(PrinterState.class)); 
    log.info(printService.getAttribute(PrinterStateReasons.class)); 
    log.info(printService.getAttribute(PrinterURI.class)); 
} 

Después de usar la función toArray() en él ...

log.info("Found print service: "+printService); 
for(Attribute a : printService.getAttributes().toArray()) { 
    log.info("* "+a.getName()+": "+a); 
} 

... este es el resultado:

Found print service: Win32 Printer : Brother MFC-9420CN BR-Script3 
* color-supported: supported 
* printer-name: Brother MFC-9420CN BR-Script3 
* printer-is-accepting-jobs: accepting-jobs 
* queued-job-count: 0

¿Cómo puedo obtener más información, como la impresora c omment?

+0

¿Qué ves si repites el retorno de 'PrintService.getAttributes()'? –

+0

No puede iterar sobre él. Además, miré la fuente Java y comencé a pensar que los desarrolladores de Java odian las impresoras. Al principio construyen una gran API, y luego incluso ellos mismos solo llenan el conjunto de atributos con 4 (!) De ~ 20 atributos posibles, en Linux y Windows. Lo siento, pero esto es triste. – Daniel

+2

Claro que puede: simplemente use 'toArray' del súper tipo (' AttributeSet') e itere la matriz. –

Respuesta

3

Hay otras implementaciones PrintServiceAttribute, pero si se desea obtener más ...

Ésta es una sucia único código , también puede recuperar los valores no admitidos para el sabor doc:

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())); 
    } 
} 

Nota: Puede ver valores repetidos, pero se pueden filtrar.

+0

+1 Okey, recupera más información sobre la impresora, pero necesitaba obtener alguna información única Cadena por impresora. Tendré que asignarlo dentro de mi aplicación, creo. – Daniel

+0

@Daniel - Busque mi respuesta. Mi código simplemente devuelve una lista más amplia de 'Atributos' que el valor predeterminado' getAttributes() '. Probablemente es lo que necesitas. –

+0

Quería atributos del servicio de impresión en sí, no sobre las configuraciones posibles para trabajos en la impresora. Necesito esta información para almacenar ajustes de configuración específicos de la impresora comprensibles para mi aplicación. – Daniel

3

continuación se presenta una versión modular, más comprensible del código proporcionado en 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; 
} 

Esto devolverá un Set con el Attributes descubierto de la impresora determinada.
Nota: Pueden aparecer valores duplicados. Sin embargo, se pueden filtrar.

Cuestiones relacionadas