Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8677197
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T20:23:43+00:00 2026-06-12T20:23:43+00:00

I need to print a string using java so I fond the following solution

  • 0

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

printer service providing class

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 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-12T20:23:45+00:00Added an answer on June 12, 2026 at 8:23 pm

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

    This class provides the print service

    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();
            }
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a result jsp page, which print the string variable of java class.
this is the problem: inside a lib i need to print MONTHNAMES to string
I need to print last 20 characters of string, but only whole words. Delimiter
I need a function that can print Turkish characters. public String convert(String input) {
I need help with using an if statement in java, here is my code
I need to fetch HTML from Turkish webpages using Java. However, I am finding
I need to run the Oracle EXP command through a Java program and print
I need to create a Mortgage Calculator for my Java class, and I have
I need to download a file using Java. I can use this code to
I have a Java string which looks like this, it is actually an XML

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.