2012-10-09 37 views
6

Tôi cần in chuỗi bằng java nên tôi thích giải pháp sau Sau khi googled rất nhiều. Tôi đã thực hiện một số thay đổi để in chuỗi mà không hiển thị hộp thoại in. Vấn đề của tôi là mặc dù phương pháp này in chuỗi đúng cách nó không phá vỡ các dòng như tôi đã xác định. Vui lòng cho tôi biết cách in các chuỗi có ngắt dòng.Cách in các chuỗi có ngắt dòng trong java

public class PrintBill implements Printable { 

    private static final String mText = "SHOP MA\n" 
      + "----------------------------\n" 
      + "Pannampitiya\n" 
      + "09-10-2012 harsha no: 001\n" 
      + "No Item Qty Price Amount\n" 
      + "1 Bread 1 50.00 50.00\n" 
      + "____________________________\n"; 

    private static final AttributedString mStyledText = new AttributedString(mText); 

    static public void main(String args[]) throws PrinterException { 
     PrinterService ps = new PrinterService(); 
     PrintService pss = ps.getCheckPrintService("Samsung-ML-2850D-2");//get the printer service by printer name 


     PrinterJob printerJob = PrinterJob.getPrinterJob(); 
     printerJob.setPrintService(pss); 

     Book book = new Book(); 
     book.append(new PrintBill(), new PageFormat());  

     printerJob.setPageable(book); 


     try { 
      printerJob.print(); 
      System.out.println(printerJob.getPrintService().getName()); 
      System.out.println("Print compleated.."); 
     } catch (PrinterException exception) { 
      System.err.println("Printing error: " + exception); 
      exception.printStackTrace(); 
     } 

    @Override 
    public int print(Graphics g, PageFormat format, int pageIndex) { 
     Graphics2D g2d = (Graphics2D) g; 

     g2d.translate(format.getImageableX(), format.getImageableY()); 

     g2d.setPaint(Color.black);   

     Point2D.Float pen = new Point2D.Float(); 
     AttributedCharacterIterator charIterator = mStyledText.getIterator(); 
     LineBreakMeasurer measurer = new LineBreakMeasurer(charIterator, g2d.getFontRenderContext()); 
     float wrappingWidth = (float) format.getImageableWidth(); 

     while (measurer.getPosition() < charIterator.getEndIndex()) { 
      TextLayout layout = measurer.nextLayout(wrappingWidth); 
      pen.y += layout.getAscent(); 
      float dx = layout.isLeftToRight() ? 0 : (wrappingWidth - layout.getAdvance()); 
      layout.draw(g2d, pen.x + dx, pen.y); 
      pen.y += layout.getDescent() + layout.getLeading(); 

     } 
     return Printable.PAGE_EXISTS; 
    } 
} 

dịch vụ máy in cung cấp lớp

public class PrinterService { 

    public PrintService getCheckPrintService(String printerName) { 
     PrintService ps = null; 
     DocFlavor doc_flavor = DocFlavor.STRING.TEXT_PLAIN; 
     PrintRequestAttributeSet attr_set = 
       new HashPrintRequestAttributeSet(); 

     attr_set.add(new Copies(1)); 
     attr_set.add(Sides.ONE_SIDED); 
     PrintService[] service = PrintServiceLookup.lookupPrintServices(doc_flavor, attr_set); 

     for (int i = 0; i < service.length; i++) { 
      System.out.println(service[i].getName()); 
      if (service[i].getName().equals(printerName)) { 
       ps = service[i]; 
      } 
     } 
     return ps; 
    } 
} 
+1

Bạn đã thử '\ r \ n' thay vì' \ n' chưa? – Keppil

+0

Thử sử dụng 'StringBuilder' và sử dụng phương thức' append'. –

+0

@ Keppil - nó không hoạt động. – Harsha

Trả lời

4

OK, cuối cùng tôi tìm thấy một giải pháp tốt cho công việc in ấn hóa đơn của tôi và nó hoạt động đúng cho tôi.

Lớp này cung cấp các dịch vụ in ấn

public class PrinterService { 

    public PrintService getCheckPrintService(String printerName) { 
     PrintService ps = null; 
     DocFlavor doc_flavor = DocFlavor.STRING.TEXT_PLAIN; 
     PrintRequestAttributeSet attr_set = 
       new HashPrintRequestAttributeSet(); 

     attr_set.add(new Copies(1));   
     attr_set.add(Sides.ONE_SIDED); 
     PrintService[] service = PrintServiceLookup.lookupPrintServices(doc_flavor, attr_set); 

     for (int i = 0; i < service.length; i++) { 
      System.out.println(service[i].getName()); 
      if (service[i].getName().equals(printerName)) { 
       ps = service[i]; 
      } 
     } 
     return ps; 
    } 
} 

lớp này cho thấy nhiệm vụ in hóa đơn,

public class HelloWorldPrinter implements Printable { 

    @Override 
    public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException { 
     if (pageIndex > 0) { /* We have only one page, and 'page' is zero-based */ 
      return NO_SUCH_PAGE; 
     } 

     Graphics2D g2d = (Graphics2D) graphics; 
     g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY()); 

     //the String to print in multiple lines 
     //writing a semicolon (;) at the end of each sentence 
     String mText = "SHOP MA;" 
       + "Pannampitiya;" 
       + "----------------------------;" 
       + "09-10-2012 harsha no: 001 ;" 
       + "No Item Qty Price Amount ;" 
       + "----------------------------;" 
       + "1 Bread 1 50.00 50.00 ;" 
       + "----------------------------;"; 

     //Prepare the rendering 
     //split the String by the semicolon character 
     String[] bill = mText.split(";"); 
     int y = 15; 
     Font f = new Font(Font.SANS_SERIF, Font.PLAIN, 8); 
     graphics.setFont(f); 
     //draw each String in a separate line 
     for (int i = 0; i < bill.length; i++) { 
      graphics.drawString(bill[i], 5, y); 
      y = y + 15; 
     } 

     /* tell the caller that this page is part of the printed document */ 
     return PAGE_EXISTS; 
    } 

    public void pp() throws PrinterException { 
     PrinterService ps = new PrinterService(); 
     //get the printer service by printer name 
     PrintService pss = ps.getCheckPrintService("Deskjet-1000-J110-series-2"); 

     PrinterJob job = PrinterJob.getPrinterJob(); 
     job.setPrintService(pss); 
     job.setPrintable(this); 

     try { 
      job.print(); 
     } catch (PrinterException ex) { 
      ex.printStackTrace(); 
     } 

    } 

    public static void main(String[] args) { 
     HelloWorldPrinter hwp = new HelloWorldPrinter(); 
     try { 
      hwp.pp(); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 
} 
7

làm theo cách này: -

String newline = System.getProperty("line.separator"); 

private static final String mText = "SHOP MA" + newline + 
     + "----------------------------" + newline + 
     + "Pannampitiya" + newline + 
     + "09-10-2012 harsha no: 001" + newline + 
     + "No Item Qty Price Amount" + newline + 
     + "1 Bread 1 50.00 50.00" + newline + 
     + "____________________________" + newline; 
+1

điều này cũng không hoạt động. – Harsha

+0

Làm việc này để in trực tuyến, nhưng không phải khi gửi đến máy in. – KimvdLinde

-1

Sử dụng chuỗi đệm.

final StringBuffer mText = new StringBuffer("SHOP MA\n" 
     + "----------------------------\n" 
     + "Pannampitiya\n" 
     + "09-10-2012 harsha no: 001\n" 
     + "No Item Qty Price Amount\n" 
     + "1 Bread 1 50.00 50.00\n" 
     + "____________________________\n"); 
+0

"AttributedString mStyledText" yêu cầu một chuỗi – Harsha

+0

điều này không hoạt động – Harsha

0

Bạn có thể thử sử dụng StringBuilder: -

final StringBuilder sb = new StringBuilder(); 

    sb.append("SHOP MA\n"); 
    sb.append("----------------------------\n"); 
    sb.append("Pannampitiya\n"); 
    sb.append("09-10-2012 harsha no: 001\n"); 
    sb.append("No Item Qty Price Amount\n"); 
    sb.append("1 Bread 1 50.00 50.00\n"); 
    sb.append("____________________________\n"); 

    // To use StringBuilder as String.. Use `toString()` method.. 
    System.out.println(sb.toString()); 
+0

điều này không phải là lo lắng – Harsha

+0

@Harsha ..: (... –

+0

@Harsha Bạn đang gặp phải vấn đề gì ?? –

0

Tôi nghĩ rằng bạn đang làm nó quá phức tạp. AttributedString được sử dụng khi bạn muốn lưu trữ các thuộc tính - trong bối cảnh in ấn. Nhưng bạn đang lưu trữ dữ liệu bên trong đó. AttributedString

Đơn giản, lưu trữ dữ liệu của bạn vào đối tượng Tài liệu và chuyển các thuộc tính như Phông chữ, In đậm, Nghiêng tất cả mọi thứ trong AttributedString.

Hy vọng điều này sẽ rất hữu ích A quick tutorialIn depth tutorial

1
private static final String mText = "SHOP MA" + "\n" + 
     + "----------------------------" + "\n" + 
     + "Pannampitiya" + newline + 
     + "09-10-2012 harsha no: 001" + "\n" + 
     + "No Item Qty Price Amount" + "\n" + 
     + "1 Bread 1 50.00 50.00" + "\n" + 
     + "____________________________" + "\n"; 

này nên làm việc.

1
String newline = System.getProperty("line.separator"); 
System.out.println("First line" + newline); 
System.out.println("Second line" + newline); 
System.out.println("Third line"); 
Các vấn đề liên quan