使用 Java,我需要在本地未安装的网络打印机上进行打印。我只知道打印机名称。我见过的所有教程都以类似以下内容开头:
PrintService []services = PrinterJob.lookupPrintServices();
问题是不能安装打印机,所以在那种情况下服务将是空的。我需要直接设置打印机名称,而不仅仅是通过可见打印机进行枚举。
最佳答案
如果打印机未注册到运行打印应用程序的 Windows/Active Directory 用户,则 Java AWT 打印将无法通过路径找到打印机。您必须通过 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;
}
}
}
关于java - 如何使用Java在网络打印机上打印?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11230502/