使用Java热敏打印机进行打印
我必须使用Java通过热敏打印机打印收据。我什么都做了。我的程序从数据库中获取数据,并使用特殊字符、制表符和 \n 转换为一个字符串。然后将字符串传递给另一个将其转换为图形的方法。
问题是,当我点击打印按钮时,白纸出来了。我注意到我的String的前4-5个字符印在纸张最末端右上角的钞票的最后一行上。我的打印机是爱普生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**** \n"
+ "Date: "+Date+" Time: "+Time+"\n"
+ "---------------------------------\n"
+ "Name Qty Rate Amt\n"
+ "---------------------------------\n";
String amt =
"\n \n \nTotal Amount = "+ amt() +"\n"
+ "Tax =" + tax() + "\n"
+ "*********************************\n"
+ "Thank you. \n";
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+"\t"+qty+"\t"+rate+"\t"+amount+"\n";
bill = bill+ items;
i++;
} while(i <= mod.getRowCount()-1);
bill = bill+amt;
System.out.println(bill);
printCard(bill);
dispose();
}
打印账单的方法是:
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());
}
}
问题是什么,我该如何解决?我认为我没有在drawString()Method中设置正确的参数。
还是别的什么?任何帮助我将不胜感激。!