Advertisement
Guest User

Untitled

a guest
Oct 21st, 2014
254
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. public class PrintText {
  2.  
  3. public static void main(String[] args) throws PrintException, IOException {
  4.  
  5. String defaultPrinter =
  6. PrintServiceLookup.lookupDefaultPrintService().getName();
  7. System.out.println("Default printer: " + defaultPrinter);
  8. PrintService service = PrintServiceLookup.lookupDefaultPrintService();
  9.  
  10. // prints the famous hello world! plus a form feed
  11. InputStream is = new ByteArrayInputStream("hello world!f".getBytes("UTF8"));
  12.  
  13. PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
  14. pras.add(new Copies(1));
  15.  
  16. DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
  17. Doc doc = new SimpleDoc(is, flavor, null);
  18. DocPrintJob job = service.createPrintJob();
  19.  
  20. PrintJobWatcher pjw = new PrintJobWatcher(job);
  21. job.print(doc, pras);
  22. pjw.waitForDone();
  23. is.close();
  24. }
  25. }
  26.  
  27. class PrintJobWatcher {
  28. boolean done = false;
  29.  
  30. PrintJobWatcher(DocPrintJob job) {
  31. job.addPrintJobListener(new PrintJobAdapter() {
  32. public void printJobCanceled(PrintJobEvent pje) {
  33. allDone();
  34. }
  35. public void printJobCompleted(PrintJobEvent pje) {
  36. allDone();
  37. }
  38. public void printJobFailed(PrintJobEvent pje) {
  39. allDone();
  40. }
  41. public void printJobNoMoreEvents(PrintJobEvent pje) {
  42. allDone();
  43. }
  44. void allDone() {
  45. synchronized (PrintJobWatcher.this) {
  46. done = true;
  47. System.out.println("Printing done ...");
  48. PrintJobWatcher.this.notify();
  49. }
  50. }
  51. });
  52. }
  53. public synchronized void waitForDone() {
  54. try {
  55. while (!done) {
  56. wait();
  57. }
  58. } catch (InterruptedException e) {
  59. }
  60. }
  61. }
  62.  
  63. Default printer: EPSON TM-T81 Receipt
  64. Printing done ...
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement