2013-02-14 50 views
3

目前獲取安裝在我的機器上打印的默認打印機。我希望能夠選擇文檔所屬的打印機。這樣做的最好方法是什麼?如何指定我想在Java中使用的打印機?

代碼:

PrintService[] services = 
       PrintServiceLookup.lookupPrintServices(psInFormat, null); 
     System.out.println("Printer Selected " + services[Printerinx]); 

     //PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService(); 

     DocFlavor[] docFalvor = services[Printerinx].getSupportedDocFlavors(); 
     for (int i = 0; i < docFalvor.length; i++) { 
      System.out.println(docFalvor[i].getMimeType()); 
     } 

回答

3

創建PrintUtility類下面,將其導入並嘗試調用PrintUtility.findPrintService("name_of_my_printer");,如果你知道你的打印機名稱;如果你不知道什麼打印機,您可以訪問,請致電PrintUtility.getPrinterServiceNameList();包含所有可行登記的打印機名稱的List

或者看到my answer to this SO question瞭解更多詳情:

package com.stackoverflow.print; 

import java.awt.print.PrinterJob; 
import javax.print.PrintService; 
import java.util.List; 
import java.util.ArrayList; 

public final class PrintUtility { 

    /** 
    * Retrieve a Print Service with a name containing the specified PrinterName; will return null if not found. 
    * 
    * @return 
    */ 
    public static PrintService findPrintService(String printerName) { 

     printerName = printerName.toLowerCase(); 

     PrintService service = null; 

     // Get array of all print services 
     PrintService[] services = PrinterJob.lookupPrintServices(); 

     // Retrieve a print service from the array 
     for (int index = 0; service == null && index < services.length; index++) { 

      if (services[index].getName().toLowerCase().indexOf(printerName) >= 0) { 
       service = services[index]; 
      } 
     } 

     // Return the print service 
     return service; 
    } 

    /** 
    * Retrieves a List of Printer Service Names. 
    * 
    * @return List 
    */ 
    public static List<String> getPrinterServiceNameList() { 

     // get list of all print services 
     PrintService[] services = PrinterJob.lookupPrintServices(); 
     List<String> list = new ArrayList<String>(); 

     for (int i = 0; i < services.length; i++) { 
      list.add(services[i].getName()); 
     } 

     return list; 
    } 

    /** 
    * Utility class; no construction! 
    */ 
    private PrintUtility() {} 
} 
5

PrintServiceLookup.lookupPrintService()方法提供了一種按名稱查詢打印機。製備HashAttributeSetPrinterName屬性對象,並將其傳遞給查找方法。

使用代碼象下面這樣:

AttributeSet aset = new HashAttributeSet(); 
aset.add(new PrinterName("MyPrinter", null)); 
PrintService[] pservices = 
    PrintServiceLookup.lookupPrintServices(null, aset); 

在Linux上工作的杯子。

+0

工作在Windows上也是如此。 – elixir 2016-10-19 18:53:15

-2
int i ; 

DocFlavor fl= null; 

PrintService printService[]= PrintServiceLookup.lookupPrintServices(fl,null); 

for(i=0;i<printService.length;i++) 
{ 
    System.out.println(printService[i]); 

} 
相關問題