Hello! I am developing a POS System. I have need to print Sales receipt. I have no physical printer to test my printing but i have print on xps document. I am facing a problem with indentation of my data on Sales receipt. Following is the code which i wrote to print my recipt:

@Override
public int print(Graphics graphics,
PageFormat pageFormat, int pageIndex)     
throws PrinterException {

    if(pageIndex > 0){
       return NO_SUCH_PAGE; 
    }
    Font f;
    int y = 15;
    int rowCount = model.getRowCount();
    String s = String.format("%s  %30s  %30s 
  %30s", "item","Qty","Price","Amount");
    String s2 = String.format("%s %30s %30s 
    %30s","-----" ,"-----","-----","-----" );

    f = new Font(Font.SANS_SERIF,Font.PLAIN, 
   8);
    graphics.setFont(f);

    Graphics2D g2D = (Graphics2D)graphics;

 g2D.translate(pageFormat.getImageableX(),
 pageFormat.getImageableY());
    graphics.drawString(s, 100, y);
    y=y+15;
    graphics.drawString(s2, 100, y);

                // extracting all the values from.    
                jTable

    for(int i=0;i<rowCount;i++){
      String s1 =String.format("%s  %30s  %30s  
    %30s", model.getValueAt(i, 0), 
 model.getValueAt(i, 1), model.getValueAt(i, 
 2), model.getValueAt(i, 3));   
      y = y+15;
      graphics.drawString(s1, 100, y);
    }

     return PAGE_EXISTS;
}

    And below is the code which i wrote under 
    the 
    Actionperformed event of my 'Print' 
   Button

   private void.  
   btnPrintActionPerformed
  (java.awt.event.ActionEvent evt) {                                         

    PrinterJob job = PrinterJob.getPrinterJob();
    PageFormat pageFormat =  
      job.defaultPage();
    Paper paper = new Paper();
    paper.setSize((double)paper.getWidth(), 
   (double) (paper.getHeight()));
    paper.setImageableArea(20, 20, 
    paper.getWidth()-20,paper.getHeight()-20);
    pageFormat.setPaper(paper);
   job.setPrintable(this,pageFormat);
   boolean ok = job.printDialog();
  if(ok){
  try{
    job.print();
  } catch (PrinterException ex) {
    Logger.getLogger(Sale.class.getName()).
   log(Level.SEVERE, null, ex);
   }
 }
 else{
  JOptionPane.showMessageDialog(null,"Job.     
 did not successfully complete");
   }

    }          

Below is the ouptut on xps document:

Item. Qty. Price. Amount

Rubber. 10. 20. 200
Foor rubber. 20. 100. 2000
Handle grip. 30. 100. 3000
Helmet. 1. 500. 500

As you can see that in the code I have given a space of %30s between every field.
But in output when an item name length extends,the space value remains same(%30s) but the indentation is spoiled. So what should i do
so that my items indentaion remain correct?

I have given a space of %30s between every field

That's not how it works. The width spec is the minimum width to use for the field, not the space between fields.

Your format is "%s %30s %30s %30s" That means the first item is printed a String with no padding, and the rest are printed as Strings padded to 30 chars wide.
If you want the first field printed at a fixed width then you need somethig like "%30s %30s %30s %30s"

Yes u r right. By using this format: "%30s %30s %30s %30s" alignment of items column is perfect. But alignment of other 3 fields is not good as you can see below. What is the reason behind this?

Items. Qty. Price. Amount

Rubber. 10. 20. 200
Foot rubber. 20. 100. 2000
Handle grip. 30. 100. 3000
Helmet. 1. 500. 500

I can't see the layout you are getting unless you format your post to retain blanks etc, but in general...
if you are formating a string followed by 3 numbers you would left-justify the string, and format the numbers with a numeric format (right justified), eg "%-30s %10d %10d %10d\n"

Yes i want to show you screenshot of my output. But i could not find that how to post screenshot here

Try posting it as code - that will preserve spaces

         Item.         Qty.        Price.          Amount
Honda madgad.    10.     60.         600
Honda indicator.  10.    50.          500
Handle.               10.    60.          600
Bumper.               10.     600.       6000 

James bro, as i posted below my first column
Named "items" is aligned successfully but values of other 3 columns do not aligned.

Item. Qty. Price. Amount
Honda madgad. 10. 60. 600
Honda indicator.10. 50. 500
Handle. 10. 60. 600
Bumper. 10. 600. 6000

During writing my reply here i use spaces but after posting spaces vanish from my reply.

I don't know what your latest code looks like, but here's an example that works...

        System.out.printf("%-30s %10s %10s %10s\n", 
                              "Item", "Quantity", "Price", "Amount");

        String format = "%-30s %10.2f %10.2f %10d\n";
        System.out.printf(format ,"a",1.1,2.0 ,400);
        System.out.printf(format,"bb",100.,20.99,4);

Output is

Item                             Quantity      Price     Amount
a                                    1.10       2.00        400
bb                                 100.00      20.99          4

Bother you are giving correct format. There is no problem in alignment if i print it on console. Problem in alignment occurs when i print on xps document. The first column appears in perfect alignment. But the data of other 3 columns appears with incorrect allignment

Qty.    Price.     Amount 
10.      100.        1000
   10.      100.        1000
20.        100.        2000
15.       100.          1500

Maybe it'sthe font in the xps document.Are you sure you are using a mono-spaced font (like courier for example)?

I have no idea that what font i am using in xps.
I have xps viewer only.
When print dialog appears i only select "xps document" from the printers list and press print button. All the data prints on xps document.

How can i check that which font my xps file is using?

Looking at your code again it seems you are setting the font on line 17.
SANS_SERIF is a porportional font where blanks and letters have different widths, so columns will not align.
Try MONOSPACED instead.

Thanks a lot James bro. I used mono-spaced font and my problem has solved.
If u don't mind i have another confusion i want to discuss with you. As you know i am developing a pos(want to launch it as a product) and obviously i cannot predict that whether the user will use a receipt printer or A4 printer. So how can i tackle printing formats and paper size e.t.c. for both type of printers?

About supporting diffferent paper sizes, etc.

For that you want to think about TEMPLATES that your code reads in to format the output.

For example your receipt code would be vastly upgraded to read some text file that it uses to tailor the receipt to the printer and client.

For example, I used a rather spiffy HTML file as my template and used variables in my template file to indicate what was to be replaced in that string. EXAMPLE:
&DATE& &TIME&

Would be in the template file. So your receipt printer routine reads that line into a string then you substitute the date and time in the string with the current date/time then print that string.

This template method means you can tailor your system to each client and printer.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.