I have to print receipts through a thermal printer using Java. I have done everything.
My program takes the data from the database and converts in one string using special characters, tabs and
. Then the string is passed on to another method that converts it into graphics.
The problem is that when I click the print button, white paper comes out. I noticed that the first 4-5 characters of my String are getting printed on the last line of the bill on the right corner at the extreme end of the paper. My printer is Epson TM - T81.
public void printThisBill()
{
DefaultTableModel mod = (DefaultTableModel) jTable1.getModel();
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
DateFormat timeFormat = new SimpleDateFormat("HH:mm");
//get current date time with Date()
Date date = new Date();
Date time = new Date();
String Date = dateFormat.format(date);
String Time = timeFormat.format(time);
String Header =
" ****Super Market****
"
+ "Date: "+Date+" Time: "+Time+"
"
+ "---------------------------------
"
+ "Name Qty Rate Amt
"
+ "---------------------------------
";
String amt =
"
Total Amount = "+ amt() +"
"
+ "Tax =" + tax() + "
"
+ "*********************************
"
+ "Thank you.
";
String bill = Header;
int i = 0;
do
{
String name = ""+ mod.getValueAt(i, 2);
String qty = ""+ mod.getValueAt(i, 3);
String rate = ""+ mod.getValueAt(i, 4);
String amount = ""+ mod.getValueAt(i, 6);
if(name.length() > 12)
{
name = name.substring(0, 12)+" ";
}
else
{
for(int j= name.length()-12; j<= name.length(); j++);
{
name = name+" ";
}
}
if(qty.length()<=5)
{
for(int j= 0; j<= qty.length()-5; j++);
{
qty = qty+" ";
}
}
rate = rate;
String items =
name+""+qty+""+rate+""+amount+"
";
bill = bill+ items;
i++;
} while(i <= mod.getRowCount()-1);
bill = bill+amt;
System.out.println(bill);
printCard(bill);
dispose();
}
And the method that prints the bill is:
public static void printCard(final String bill )
{
Printable contentToPrint = new Printable(){
@Override
public int print(Graphics graphics, PageFormat pageFormat, int page) throws PrinterException
{
if (page > 0) {
return NO_SUCH_PAGE;
}
pageFormat.setOrientation(PageFormat.LANDSCAPE);
Graphics2D g2d = (Graphics2D)graphics.create();
g2d.setPaint(Color.black);
g2d.setFont(new Font("Arial", Font.BOLD, 10));
g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableX());
g2d.drawString(bill, 0, 0);
return PAGE_EXISTS;
}
};
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(contentToPrint);
//You can show a print dialog before printing by job by wrapping the following blocks with a conditional statement if(job.printDialog()){...}
try
{
job.print();
} catch (PrinterException e)
{
System.err.println(e.getMessage());
}
}
What is the problem and how can I solve it? I think that I'm not setting the right parameters at drawString() Method.
Or is it something else? Any help would me appreciated.!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…