使用热敏打印机在java中打印接收 [英] Printing reciepts with thermal printer in java

查看:106
本文介绍了使用热敏打印机在java中打印接收的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须使用Java通过热敏打印机打印收据。我做了一切。
我的程序从数据库中获取数据,并使用特殊字符,制表符和\ n转换为一个字符串。然后将字符串传递给另一个将其转换为图形的方法。

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 \n. Then the string is passed on to another method that converts it into graphics.

问题是,当我单击打印按钮时,会出现白皮书。我注意到我的字符串的前4-5个字符被打印在纸张末端右角的帐单的最后一行。我的打印机是Epson TM - T81。

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****       \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()方法中设置正确的参数。

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.!

推荐答案

我发现了这个:

Java Pos热敏打印机示例

它对我有用。不需要外部库。

It worked for me. No need for external libraries.

import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.util.ArrayList;
import java.util.List;

import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;

public class PrinterService implements Printable {

    public List<String> getPrinters(){

        DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
        PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();

        PrintService printServices[] = PrintServiceLookup.lookupPrintServices(
                flavor, pras);

        List<String> printerList = new ArrayList<String>();
        for(PrintService printerService: printServices){
            printerList.add( printerService.getName());
        }

        return printerList;
    }

    @Override
    public int print(Graphics g, PageFormat pf, int page)
            throws PrinterException {
        if (page > 0) { /* We have only one page, and 'page' is zero-based */
            return NO_SUCH_PAGE;
        }

        /*
         * User (0,0) is typically outside the imageable area, so we must
         * translate by the X and Y values in the PageFormat to avoid clipping
         */
        Graphics2D g2d = (Graphics2D) g;
        g2d.translate(pf.getImageableX(), pf.getImageableY());
        /* Now we perform our rendering */

        g.setFont(new Font("Roman", 0, 8));
        g.drawString("Hello world !", 0, 10);

        return PAGE_EXISTS;
    }

    public void printString(String printerName, String text) {

        // find the printService of name printerName
        DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
        PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();

        PrintService printService[] = PrintServiceLookup.lookupPrintServices(
                flavor, pras);
        PrintService service = findPrintService(printerName, printService);

        DocPrintJob job = service.createPrintJob();

        try {

            byte[] bytes;

            // important for umlaut chars
            bytes = text.getBytes("CP437");

            Doc doc = new SimpleDoc(bytes, flavor, null);


            job.print(doc, null);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public void printBytes(String printerName, byte[] bytes) {

        DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
        PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();

        PrintService printService[] = PrintServiceLookup.lookupPrintServices(
                flavor, pras);
        PrintService service = findPrintService(printerName, printService);

        DocPrintJob job = service.createPrintJob();

        try {

            Doc doc = new SimpleDoc(bytes, flavor, null);

            job.print(doc, null);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private PrintService findPrintService(String printerName,
            PrintService[] services) {
        for (PrintService service : services) {
            if (service.getName().equalsIgnoreCase(printerName)) {
                return service;
            }
        }

        return null;
    }
}

主要类:

public class Main {

    public static void main(String[] args) {

        PrinterService printerService = new PrinterService();

        System.out.println(printerService.getPrinters());

        //print some stuff. Change the printer name to your thermal printer name.
        printerService.printString("EPSON-TM-T20II", "\n\n testing testing 1 2 3eeeee \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");

        // cut that paper!
        byte[] cutP = new byte[] { 0x1d, 'V', 1 };

        printerService.printBytes("EPSON-TM-T20II", cutP);

    }

}

这篇关于使用热敏打印机在java中打印接收的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆