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;
}
}
Bạn đã thử '\ r \ n' thay vì' \ n' chưa? – Keppil
Thử sử dụng 'StringBuilder' và sử dụng phương thức' append'. –
@ Keppil - nó không hoạt động. – Harsha