使用Java,我需要将内容打印到网络打印机上,但该打印机未在本地安装。我只知道打印机名称。所有我看到的教程都是从以下代码开始:
PrintService []services = PrinterJob.lookupPrintServices();
问题在于可能没有安装任何打印机,因此在这种情况下服务将为空。我需要直接设置打印机名称,而不仅仅是枚举可见打印机。
使用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;
}
}
}
lookupPrintServices
不能保证返回任何顺序或大小,因为在任何给定时间可用于Windows用户的值可能会有所不同;您需要自行对它们进行排序。 AppContext
是sun.awt.AppContext
。 - JoshDM在我的情况下,出现了身份验证错误,因为我使用本地用户帐户搜索打印机,所以找不到共享打印机。使用其他帐户或更改打印机授权后,我可以找到它。