1/**
2 * Retrieve the specified Print Service; will return null if not found.
3 * @return
4 */
5public static PrintService findPrintService(String printerName) {
6
7 PrintService service = null;
8
9 // Get array of all print services - sort order NOT GUARANTEED!
10 PrintService[] services = PrinterJob.lookupPrintServices();
11
12 // Retrieve specified print service from the array
13 for (int index = 0; service == null && index < services.length; index++) {
14
15 if (services[index].getName().equalsIgnoreCase(printerName)) {
16
17 service = services[index];
18 }
19 }
20
21 // Return the print service
22 return service;
23}
24
25/**
26 * Retrieve a PrinterJob instance set with the PrinterService using the printerName.
27 *
28 * @return
29 * @throws Exception IllegalStateException if expected printer is not found.
30 */
31public static PrinterJob findPrinterJob(String printerName) throws Exception {
32
33 // Retrieve the Printer Service
34 PrintService printService = PrintUtility.findPrintService(printerName);
35
36 // Validate the Printer Service
37 if (printService == null) {
38
39 throw new IllegalStateException("Unrecognized Printer Service \"" + printerName + '"');
40 }
41
42 // Obtain a Printer Job instance.
43 PrinterJob printerJob = PrinterJob.getPrinterJob();
44
45 // Set the Print Service.
46 printerJob.setPrintService(printService);
47
48 // Return Print Job
49 return printerJob;
50}
51
52/**
53 * Printer list does not necessarily refresh if you change the list of
54 * printers within the O/S; you can run this to refresh if necessary.
55 */
56public static void refreshSystemPrinterList() {
57
58 Class[] classes = PrintServiceLookup.class.getDeclaredClasses();
59
60 for (int i = 0; i < classes.length; i++) {
61
62 if ("javax.print.PrintServiceLookup$Services".equals(classes[i].getName())) {
63
64 sun.awt.AppContext.getAppContext().remove(classes[i]);
65 break;
66 }
67 }
68}
69