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

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

PrintService []services = PrinterJob.lookupPrintServices();

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

回答:

如果Java AWT Printing未向运行打印应用程序的Windows / Active

Directory用户注册,则无法通过路径找到打印机。您必须通过Windows“设备和打印机”将打印机路径注册为该用户的打印机,才能使其可见。然后,您必须运行lookupPrintServices以查看可用的打印机列表,并PrintService通过String列出的确切名称检索正确的打印机。

/**

* 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在网络打印机上进行打印? 的全部内容, 来源链接: utcz.com/qa/401942.html

回到顶部