private static void print(InputStream is, String printerName) throws Exception{
PrintService printerService = null;
DocFlavor df = new DocFlavor("application/octet-stream", "java.io.InputStream");
PrintService[] lookupPrintServices = PrintServiceLookup.lookupPrintServices(null, null);
//Iterates through all the printers of the sistem
for (PrintService pss2 : lookupPrintServices) {
if (pss2.getName().equals(printerName)) {
printerService = pss2;
break;
}
}
if(printerService==null){
throw new Exception("Printer not found");
}
DocPrintJob createPrintJob = printerService.createPrintJob();
SimpleDoc sc = new SimpleDoc(is, df, null);
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
createPrintJob.print(sc, aset);
}
Requirements:
-You have to put the exact name of the printer. If it has a strange name, it's very easy to change, especially in windows 7. It also works for printers connected to the network.
-You have to transform what you want to print into an InputStream.
The PrinterService classes are very complex and allow you to do plenty of things but the code above should be enough to cover all your needs. If you only have one printer, you could use the method PrintServiceLookup.lookupDefaultPrintService() to avoid the iteration through all the printers.
No hay comentarios:
Publicar un comentario