如何使用Java在网络打印机上打印?

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

PrintService []services = PrinterJob.lookupPrintServices();

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

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

 /** * 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; } } } 

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