Verse Of The Day

Wednesday, February 14, 2007

Server Printing Using Java Print Service

The first and most obvious thing you will notice about the Java Print Service (JPS) API's is that it is pretty much geared toward client side printing. For example, to look up print services you use javax.print.PrintServiceLookup, which has methods to lookup the default print service, lookup all the print services that match the given AttributeSets and/or DocFlavor's. That all makes sense if you are building a print dialog with the default printer selected already, and a list of all the other printers defined on the system, to allow the user to choose one.

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()+"*");

if (prnSvc == null)
throw new Exception("Printer " + prnName + " was not found on this system.");

return prnSvc;

No comments: