domingo, 22 de enero de 2012

Printing PDF's and more in Java

The code we had in Java to print, used to be a system invoke and send the files to the spool but we had to start printing in 3 different printers and two of them had to recieve special strings but we saw that what we had, didn't work. After some research, we found the PrintService class. Here is the code that will allow you to print PDF's, strings, images or whatever you need:

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