document.write('
Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. import java.io.ByteArrayInputStream;  
  2. import java.io.InputStream;  
  3.  
  4. // Essa classe é a responsavel pela impressao. Ela detecta a impressora  
  5. // instalada, recebe o texto e o imprime.  
  6. public class Impressao {  
  7.  
  8.     // variavel estatica porque será utilizada por inumeras threads  
  9.     private static PrintService impressora;  
  10.  
  11.     public Impressao() {  
  12.  
  13.         detectaImpressoras();  
  14.  
  15.     }  
  16.  
  17.     // O metodo verifica se existe impressora conectada e a  
  18.     // define como padrao.  
  19.     public void detectaImpressoras() {  
  20.  
  21.         try {  
  22.  
  23.             DocFlavor df = DocFlavor.SERVICE_FORMATTED.PRINTABLE;  
  24.             PrintService[] ps = PrintServiceLookup.lookupPrintServices(df, null);  
  25.             for (PrintService p: ps) {  
  26.  
  27.                 System.out.println("Impressora encontrada: " + p.getName());  
  28.  
  29.                 if (p.getName().contains("Text") || p.getName().contains("Generic"))  {  
  30.  
  31.                     System.out.println("Impressora Selecionada: " + p.getName());  
  32.                     impressora = p;  
  33.                     break;  
  34.  
  35.                 }  
  36.  
  37.             }  
  38.  
  39.         } catch (Exception e) {  
  40.  
  41.             e.printStackTrace();  
  42.  
  43.         }  
  44.  
  45.     }  
  46.  
  47.     public synchronized boolean imprime(String texto) {  
  48.  
  49.         // se nao existir impressora, entao avisa usuario  
  50.         // senao imprime texto  
  51.         if (impressora == null) {  
  52.  
  53.             String msg = "Nennhuma impressora foi encontrada. Instale uma impressora padrão \\r\\n(Generic Text Only) e reinicie o programa.";  
  54.             System.out.println(msg);  
  55.  
  56.         } else {  
  57.  
  58.             try {  
  59.  
  60.                 DocPrintJob dpj = impressora.createPrintJob();  
  61.                 InputStream stream = new ByteArrayInputStream(texto.getBytes());  
  62.  
  63.                 DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;  
  64.                 Doc doc = new SimpleDoc(stream, flavor, null);  
  65.                 dpj.print(doc, null);  
  66.  
  67.                 return true;  
  68.  
  69.             } catch (PrintException e) {  
  70.  
  71.                 e.printStackTrace();  
  72.  
  73.             }  
  74.  
  75.         }  
  76.  
  77.         return false;  
  78.  
  79.     }  
  80.  
  81. }
');