Search code examples
javaprintingnetwork-printers

Printer Line break not works properly using Java


Here is the code I used to Print a String using java

String string2 = "    RECEIPT    \n==============\nHeader2\nHeader 3\nLine 4 Goes Here\nLine 5 Goes Here\n============";

InputStream is = new ByteArrayInputStream(string2.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);

PrintJobWatcher pjDone = new PrintJobWatcher(job);

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

pjDone.waitForDone();

// It is now safe to close the input stream
is.close();

It is printing on the paper like.

 RECEIPT    
        ============== 
                      Header2
                             Header 3
                                     Line 4 Goes Here
                                                     Line 5 Goes Here

Same happens when using inputStream without a String. Any Suggestion plz. And need an explanation how this DocFlavor working.Thanks


Solution

  • You have to use \r\n instead of \r.

    There is two ASCII code \n "line feed". It tell the printer to move to next line. And \r "carriage return" it to move carriage to beginning of the line.