9

我需要使用 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;
    }
}

打印机服务提供类

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;
    }
}
4

9 回答 9

9

这样做: -

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;
于 2012-10-09T06:58:05.770 回答
6

好的,最后我为我的账单打印任务找到了一个很好的解决方案,它对我来说工作正常。

该类提供打印服务

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;
    }
}

这个类演示票据打印任务,

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();
        }
    }
}
于 2012-10-15T04:54:18.023 回答
3
String newline = System.getProperty("line.separator");
System.out.println("First line" + newline);
System.out.println("Second line" + newline);
System.out.println("Third line");
于 2015-12-11T10:39:44.773 回答
2
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";

这应该有效。

于 2014-09-05T03:41:15.800 回答
0

您可以尝试使用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());   
于 2012-10-09T08:07:28.473 回答
0

我认为你把它弄得太复杂了。当您想要存储属性时使用 AttributedString - 在打印上下文中。但是您正在其中存储数据。属性字符串

简单地说,将您的数据存储到 Document 对象中,并在 AttributedString 中传递 Font、Bold、Italic 等属性。

希望这会有所帮助 快速教程深入教程

于 2012-10-12T12:30:45.597 回答
0

在字符串之间添加 /r/n 为我解决了这个问题。试试看。粘贴时不要包含用于排除的“//”。

例如:选项01\r\n选项02\r\n选项03

这将输出为
Option01
Option02
Option03

于 2020-07-06T14:21:37.017 回答
-1

使用字符串缓冲区。

  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");
于 2012-10-09T07:30:26.830 回答
-1
package test2;

public class main {

    public static void main(String[] args) {
        vehical vehical1 = new vehical("civic", "black","2012");
        System.out.println(vehical1.name+"\n"+vehical1.colour+"\n"+vehical1.model);
    }
}
于 2018-04-08T17:16:56.610 回答