2012-08-16 27 views
6

我試圖發送一個簡單的字符串(「世界,你好」)連接到打印機,但由於某些原因,只打印第一個字符(「H」)發送純文本爲默認打印機

這裏的代碼

public class CardPrinter { 
    public static void main(String[] args) { 
     try { 
      PrintService mPrinter = null; 
      Boolean bFoundPrinter = false; 

      PrintService[] printServices = PrinterJob.lookupPrintServices(); 

      // 
      // Iterates the print services and print out its name. 
      // 
      for (PrintService printService : printServices) { 
       String sPrinterName = printService.getName(); 
       if (sPrinterName.equals("DTC4000 Card Printer")) { 
        mPrinter = printService; 
        bFoundPrinter = true; 
       } 
      } 

      // Open the image file 
      String testData = "Hello World !"; 
      InputStream is = new ByteArrayInputStream(testData.getBytes()); 
      DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE ; 

      // Find the default service 
      PrintService service = PrintServiceLookup.lookupDefaultPrintService(); 
      System.out.println(service); 

      // Create the print job 
      DocPrintJob job = service.createPrintJob(); 
      Doc doc= new SimpleDoc(is, flavor, null); 

      // Monitor print job events; for the implementation of PrintJobWatcher, 
      PrintJobWatcher pjDone = new PrintJobWatcher(job); 

      // Print it 
      job.print(doc, null); 

      // Wait for the print job to be done 
      pjDone.waitForDone(); 

      // It is now safe to close the input stream 
      is.close(); 
     } catch (PrintException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

    static class PrintJobWatcher { 
     // true iff it is safe to close the print job's input stream 
     boolean done = false; 

     PrintJobWatcher(DocPrintJob job) { 
      // Add a listener to the print job 
      job.addPrintJobListener(new PrintJobAdapter() { 
       public void printJobCanceled(PrintJobEvent pje) { 
        allDone(); 
       } 
       public void printJobCompleted(PrintJobEvent pje) { 
        allDone(); 
       } 
       public void printJobFailed(PrintJobEvent pje) { 
        allDone(); 
       } 
       public void printJobNoMoreEvents(PrintJobEvent pje) { 
        allDone(); 
       } 
       void allDone() { 
        synchronized (PrintJobWatcher.this) { 
         done = true; 
         PrintJobWatcher.this.notify(); 
        } 
       } 
      }); 
     } 
     public synchronized void waitForDone() { 
      try { 
       while (!done) { 
        wait(); 
       } 
      } catch (InterruptedException e) { 
      } 
     } 
    } 
} 

任何想法?

回答

5

添加進紙,

String testData = "Hello World !\f"; 

問題解決了

+0

能否請您檢查爲什麼它不打印任何東西到我的打印機? – YumYumYum 2016-07-04 09:47:26

+1

確切地說,我可以檢查您的打印機嗎? :-) – Shai 2016-07-04 10:28:15

+0

我可以給你teamviewer嗎?與攝像頭?因爲代碼不工作先生。 – YumYumYum 2016-07-04 10:45:17

相關問題