On the server, however, printing is just one more stop in a process flow. It has to just happen automatically, which means you have a specific printer in mind for the stuff to go to. Notice on the PrintServiceLookup class, there is no method to get a specific named printer service. In my mind, that is a deficiency, but one that is easily rectified.
Here is the code I use to lookup a named printer service. The name is kept in a properties file that gets bound to JNDI, or it could be kept in a database, etc. Basically you pass in null for the DocFlavor and AttributeSet to get all print services on the machine. Then loop through those looking for a match, and return the matching service, or throw an Exception.
import javax.print.*;
...
public PrintService getNamedPrintService(String prnName)
throws Exception
{
PrintService[] prnSvcs;
PrintService prnSvc = null;
// get all print services for this machine
prnSvcs = PrintServiceLookup.lookupPrintServices(null, null);
if (prnSvcs.length > 0)
{
int ii = 0;
while ( ii < prnSvcs.length )
{
log.debug("Named Printer found: "+prnSvcs[ii].getName());
if (prnSvcs[ii].getName().equalsIgnoreCase(prnName))
{
prnSvc = prnSvcs[ii];
log.debug("Named Printer selected: "+prnSvcs[ii].getName()+"*");
break;
}
ii++;
}
}
if (prnSvc == null)
{
throw new Exception("Printer " + prnName + " was not found on this system.");
}
return prnSvc;
}
No comments:
Post a Comment