10

使用 Java,我需要在本地未安装的网络打印机上打印。我只知道打印机名称。我见过的所有教程都是从以下内容开始的:

PrintService []services = PrinterJob.lookupPrintServices();

问题是无法安装打印机,因此在这种情况下服务将为空。我需要直接设置打印机名称,而不仅仅是通过可见的打印机进行枚举。

4

2 回答 2

12

如果打印机未注册到运行打印应用程序的 Windows / Active Directory 用户,Java AWT 打印将无法通过路径找到打印机。您必须通过 Windows 的“设备和打印机”将打印机路径注册为该用户的打印机才能使其可见。然后,作为该用户,您必须运行以查看可用打印机列表并通过列出的确切名称lookupPrintServices检索正确的打印机。PrintServiceString

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

    PrintService service = null;
    
    // Get array of all print services - sort order NOT GUARANTEED!
    PrintService[] services = PrinterJob.lookupPrintServices();
    
    // Retrieve specified print service from the array
    for (int index = 0; service == null && index < services.length; index++) {
        
        if (services[index].getName().equalsIgnoreCase(printerName)) {

            service = services[index];
        }
    }

    // Return the print service
    return service;
}

/**
 * Retrieve a PrinterJob instance set with the PrinterService using the printerName.
 * 
 * @return
 * @throws Exception IllegalStateException if expected printer is not found.
 */
public static PrinterJob findPrinterJob(String printerName) throws Exception {

    // Retrieve the Printer Service
    PrintService printService = PrintUtility.findPrintService(printerName);

    // Validate the Printer Service
    if (printService == null) {

        throw new IllegalStateException("Unrecognized Printer Service \"" + printerName + '"');
    }
    
    // Obtain a Printer Job instance.
    PrinterJob printerJob = PrinterJob.getPrinterJob();
    
    // Set the Print Service.
    printerJob.setPrintService(printService);

    // Return Print Job
    return printerJob;
}

/**
 * Printer list does not necessarily refresh if you change the list of 
 * printers within the O/S; you can run this to refresh if necessary.
 */
public static void refreshSystemPrinterList() {

    Class[] classes = PrintServiceLookup.class.getDeclaredClasses();

    for (int i = 0; i < classes.length; i++) {

        if ("javax.print.PrintServiceLookup$Services".equals(classes[i].getName())) {

            sun.awt.AppContext.getAppContext().remove(classes[i]);
            break;
        }
    }
}
于 2012-06-27T18:43:59.420 回答
1

在我的情况下,出现身份验证错误,我找不到共享打印机,因为我使用 LocalUser 帐户搜索它们,使用另一个帐户或更改打印机授权我可以找到它。

于 2017-08-11T10:19:19.790 回答