0

I have this code that sends a document to a printer for printing. Currently everything is working ok and the code for that is shown below.

 public int print(Graphics g, PageFormat pf, int page) throws
                                                            PrinterException {

        if (page > 0) {
            return NO_SUCH_PAGE;
        }


        Graphics2D g2d = (Graphics2D)g;
        g2d.translate(pf.getImageableX(), pf.getImageableY());


        g.drawString(content, 100, 100);

         return PAGE_EXISTS;
    }

      public void printDocument(String doc) {
          content = doc;

         PrinterJob job = PrinterJob.getPrinterJob();
         job.setPrintable(this);
         boolean ok = job.printDialog();
         if (ok) {
             try {
                  job.print();
             } catch (PrinterException ex) {
              /* The job did not successfully complete */
                 JOptionPane.showMessageDialog(null, ex.getMessage());
             }
         }
    }

The problem now is when I try to print a document that has a new line it, it still prints it out as one line. the code for calling the function is shown below.

String message ="Library user name: \t" + user +"\n"
                            +"Item Loaned: \t" + book +"\n"
                            +"Date Loaned: \t" + dateLoaned +"\n"
                            +"Return Date: \t" + returnDate +"\n";

            print.printDocument(message);

2 Answers2

3

Are you using windows? try this:

+ "\r\n"

Or even better, use this for a portable solution:

System.lineSeparator()

If the above doesn't help, it means that the printer is expecting HTML line breaks, then you should try this:

+ "<br/>"
Óscar López
  • 232,561
  • 37
  • 312
  • 386
  • Does this work with `PrinterJob`? I have similar situation long time ago but don't remember if this is the solution. AFAIK this `System.lineSeparator` works in `PrintWriter` and similar, but not in graphics as shown here: `g.drawString(content, 100, 100);`. – Luiggi Mendoza Jan 26 '15 at 14:35
  • @LuiggiMendoza good point. In those cases, it might be a better idea to use `
    `
    – Óscar López Jan 26 '15 at 14:38
0

That may be because of this: In Windows, a new Line is "\r\n", while in Linux a "\n" is sufficient.

Therefore if you'll run your Prog in Linux, it would propably work.

If you write "\r\n" your Prog will run on Windows, but there would be an extra empty line if it is run on Linux. This is a common Linux/Windows Problem.

kappadoky
  • 321
  • 2
  • 12