天天看点

how to send raw data to printer in java

  1. import java.io.ByteArrayInputStream;  
  2. import java.io.InputStream;  
  1. import javax.print.Doc;  
  2. import javax.print.DocFlavor;  
  3. import javax.print.DocPrintJob;  
  4. import javax.print.PrintService;  
  5. import javax.print.PrintServiceLookup;  
  6. import javax.print.SimpleDoc;  
  7. public class MyPrintTest {  
  8. public void executePrint(String sample){  
  9. //data for printing  
  10. String data = sample;  
  11. try {  
  12. //locate printer  
  13. PrintService printService = PrintServiceLookup.lookupDefaultPrintService();  
  14. System.out.println("Printer online: "+printService);  
  15. //create a print job  
  16. DocPrintJob job = printService.createPrintJob();  
  17. //define the format of print document  
  18. InputStream is = new ByteArrayInputStream(data.getBytes());  
  19. DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;  
  20. //print the data  
  21. Doc doc = new SimpleDoc(is, flavor, null);  
  22. job.print(doc, null);  
  23. is.close();  
  24. System.out.println("Printing Done!!");  
  25. } catch (Exception e) {  
  26. e.printStackTrace();  
  27. }  
  28. }  
  29. public static void main(String[] args) {  
  30. new MyPrintTest().executePrint("testing Printing");  
  31. }