使用Java,我需要在网络打印机上打印,而不是在本地安装.我只知道打印机名称.我见过的所有教程都是从以下内容开始的:
PrintService []services = PrinterJob.lookupPrintServices();
问题是没有安装打印机,因此在这种情况下服务将是空的.我需要直接设置打印机名称,而不仅仅是通过可见打印机进行枚举.
Jos*_*hDM 10
如果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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
26143 次 |
| 最近记录: |