如何在java中打印带换行符的字符串 [英] How to print strings with line breaks in java

查看:230
本文介绍了如何在java中打印带换行符的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用java打印一个字符串,所以我喜欢以下解决方案经过google搜索了很多。我做了一些更改来打印字符串而不显示打印对话框。我的问题是虽然这个方法正确地打印了字符串,但它不会像我定义的那样破坏行。请告诉我如何打印带换行符的字符串。

I need to print a string using java so I fond the following solution After googled a lot. I have done some changes to print the string without showing the print dialog. My problem is although this method prints the string properly it doesn't breaks the lines as I have defined. Please tell me how to print strings with line breaks.

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


推荐答案

确定,最后我找到了一个很好的解决方案,我的帐单打印任务,它正在为我正常工作。

OK, finally I found a good solution for my bill printing task and it is working properly for me.

此类提供打印服务

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

此课程演示了帐单打印任务,

This class demonstrates the bill printing task,

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

这篇关于如何在java中打印带换行符的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆