我目前使用以下代码片段检索一些有关可能的介质托盘的打印机信息:

 Media med[] = (Media[])printService.getSupportedAttributeValues(Media.class, null, null);
 if( med != null ) {
     for (int k=0; k<med.length; k++) {
          sb.append("Name : " + med[k].getClass() + " - Value : " + med[k].getValue() +
                " - Name : " + med[k].getName()+"\n" );
     }
 }


可悲的是,这只会返回一些纸盘编号,我发现它们相对没有用:

Name : class javax.print.attribute.standard.MediaSizeName - Value : 40 - Name : media
Name : class javax.print.attribute.standard.MediaSizeName - Value : 41 - Name : media
Name : class javax.print.attribute.standard.MediaSizeName - Value : 42 - Name : media
... more ...
Name : class sun.print.Win32MediaTray - Value : 5 - Name : media
Name : class sun.print.Win32MediaTray - Value : 25 - Name : media
Name : class sun.print.Win32MediaTray - Value : 26 - Name : media
Name : class sun.print.Win32MediaTray - Value : 27 - Name : media


如何检索有用的名称?

最佳答案

这将为您提供所有打印机属性,包括纸盘名称

String printName = "HP Officejet Pro 8500 A910 (Network)";
AttributeSet aset = new HashAttributeSet();
aset.add(new PrinterName(printName, null));
PrintService[] services = PrintServiceLookup.lookupPrintServices(null, aset);
for (int i = 0; i < services.length; i++) {
  PrintService service = services[i];
  System.out.println(service);
  DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PAGEABLE;
  Object o = service.getSupportedAttributeValues(Media.class, flavor, null);
  if (o != null && o.getClass().isArray()) {
    for (Media media : (Media[]) o) {
      System.out.println(media + " ID: " + media.getValue() + "\t" + media.getClass().getName());
    }
  }
}

10-06 15:34